test.cc 682 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453
  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. // Reports whether anything is still listening on a loopback port. A plain
  2892. // connect() is used instead of a Client request because a socket left bound by
  2893. // mistake accepts the connection into its backlog and never answers, which
  2894. // would hang the test instead of failing it.
  2895. static bool is_loopback_port_accepting(int port) {
  2896. sockaddr_in addr{};
  2897. addr.sin_family = AF_INET;
  2898. addr.sin_port = htons(static_cast<uint16_t>(port));
  2899. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2900. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  2901. EXPECT_NE(sock, INVALID_SOCKET);
  2902. if (sock == INVALID_SOCKET) { return false; }
  2903. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  2904. static_cast<socklen_t>(sizeof(addr)));
  2905. detail::close_socket(sock);
  2906. return ret == 0;
  2907. }
  2908. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  2909. Server svr;
  2910. auto port = svr.bind_to_any_port("127.0.0.1");
  2911. ASSERT_TRUE(port > 0);
  2912. svr.stop();
  2913. // bind_to_any_port() already called listen(2), so until stop() closed the
  2914. // descriptor the port kept accepting connections into the backlog. ASSERT
  2915. // rather than EXPECT: with the socket still open, the listen_after_bind()
  2916. // below blocks forever in the accept loop.
  2917. ASSERT_FALSE(is_loopback_port_accepting(port));
  2918. // Nothing is left to accept on, so listen_after_bind() must report failure
  2919. // instead of returning success without ever serving.
  2920. EXPECT_FALSE(svr.listen_after_bind());
  2921. // The failed listen marks the server decommissioned, so a waiter returns
  2922. // instead of spinning forever.
  2923. svr.wait_until_ready();
  2924. }
  2925. #ifdef CPPHTTPLIB_SSL_ENABLED
  2926. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2928. CLIENT_CA_CERT_DIR);
  2929. int port = svr.bind_to_any_port("0.0.0.0");
  2930. ASSERT_TRUE(svr.is_valid());
  2931. ASSERT_TRUE(port > 0);
  2932. svr.stop();
  2933. }
  2934. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2935. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2936. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2937. int port = svr.bind_to_any_port("0.0.0.0");
  2938. ASSERT_TRUE(svr.is_valid());
  2939. ASSERT_TRUE(port > 0);
  2940. svr.stop();
  2941. }
  2942. TEST(BindServerTest, UpdateCertsPem) {
  2943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2944. int port = svr.bind_to_any_port("0.0.0.0");
  2945. ASSERT_TRUE(svr.is_valid());
  2946. ASSERT_TRUE(port > 0);
  2947. // Read PEM files
  2948. std::string cert_pem, key_pem, ca_pem;
  2949. read_file(SERVER_CERT_FILE, cert_pem);
  2950. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2951. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2952. // Update server certificates using PEM API
  2953. ASSERT_TRUE(
  2954. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2955. ASSERT_TRUE(svr.is_valid());
  2956. svr.stop();
  2957. }
  2958. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2959. // Start server with client CA (enables client auth)
  2960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2961. ASSERT_TRUE(svr.is_valid());
  2962. bool handler_called = false;
  2963. svr.Get("/test", [&](const Request &req, Response &res) {
  2964. handler_called = true;
  2965. // Verify client certificate is present
  2966. auto cert = req.peer_cert();
  2967. EXPECT_TRUE(static_cast<bool>(cert));
  2968. res.set_content("ok", "text/plain");
  2969. });
  2970. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. t.join();
  2974. ASSERT_FALSE(svr.is_running());
  2975. });
  2976. svr.wait_until_ready();
  2977. // Read PEM files
  2978. std::string cert_pem, key_pem, ca_pem;
  2979. read_file(SERVER_CERT_FILE, cert_pem);
  2980. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2981. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2982. // Update server certificates and client CA using PEM API while server running
  2983. ASSERT_TRUE(
  2984. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2985. // Connect with client certificate
  2986. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2987. cli.enable_server_certificate_verification(false);
  2988. cli.set_connection_timeout(30);
  2989. auto res = cli.Get("/test");
  2990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2991. ASSERT_EQ(StatusCode::OK_200, res->status);
  2992. ASSERT_TRUE(handler_called);
  2993. EXPECT_EQ("ok", res->body);
  2994. }
  2995. #endif
  2996. TEST(ErrorHandlerTest, ContentLength) {
  2997. Server svr;
  2998. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2999. res.status = StatusCode::OK_200;
  3000. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3001. "text/html"); // <= Content-Length still 13
  3002. });
  3003. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3004. res.set_content("Hello World!\n", "text/plain");
  3005. res.status = 524;
  3006. });
  3007. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3008. auto se = detail::scope_exit([&] {
  3009. svr.stop();
  3010. thread.join();
  3011. ASSERT_FALSE(svr.is_running());
  3012. });
  3013. svr.wait_until_ready();
  3014. {
  3015. Client cli(HOST, PORT);
  3016. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ(StatusCode::OK_200, res->status);
  3019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3020. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3021. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3022. }
  3023. }
  3024. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3025. TEST(ExceptionTest, WithoutExceptionHandler) {
  3026. Server svr;
  3027. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3028. throw std::runtime_error("exception...");
  3029. });
  3030. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3031. throw std::runtime_error("exception\r\n...");
  3032. });
  3033. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. listen_thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. Client cli("localhost", PORT);
  3041. {
  3042. auto res = cli.Get("/exception");
  3043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3044. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3045. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3046. }
  3047. {
  3048. auto res = cli.Get("/unknown");
  3049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3050. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3051. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3052. }
  3053. }
  3054. TEST(ExceptionTest, WithExceptionHandler) {
  3055. Server svr;
  3056. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3057. std::exception_ptr ep) {
  3058. EXPECT_FALSE(ep == nullptr);
  3059. try {
  3060. std::rethrow_exception(ep);
  3061. } catch (std::exception &e) {
  3062. EXPECT_EQ("abc", std::string(e.what()));
  3063. } catch (...) {}
  3064. res.status = StatusCode::InternalServerError_500;
  3065. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3066. "text/html"); // <= Content-Length still 13 at this point
  3067. });
  3068. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3069. res.set_content("Hello World!\n", "text/plain");
  3070. throw std::runtime_error("abc");
  3071. });
  3072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3073. auto se = detail::scope_exit([&] {
  3074. svr.stop();
  3075. thread.join();
  3076. ASSERT_FALSE(svr.is_running());
  3077. });
  3078. svr.wait_until_ready();
  3079. for (size_t i = 0; i < 10; i++) {
  3080. Client cli(HOST, PORT);
  3081. for (size_t j = 0; j < 100; j++) {
  3082. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3084. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3086. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3087. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3088. }
  3089. cli.set_keep_alive(true);
  3090. for (size_t j = 0; j < 100; j++) {
  3091. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3094. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3095. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3096. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3097. }
  3098. }
  3099. }
  3100. TEST(ExceptionTest, AndErrorHandler) {
  3101. Server svr;
  3102. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3103. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3104. });
  3105. svr.set_exception_handler(
  3106. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3107. EXPECT_FALSE(ep == nullptr);
  3108. try {
  3109. std::rethrow_exception(ep);
  3110. } catch (std::exception &e) {
  3111. res.set_content(e.what(), "text/html");
  3112. } catch (...) {}
  3113. res.status = StatusCode::InternalServerError_500;
  3114. });
  3115. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3116. throw std::runtime_error("EXCEPTION");
  3117. });
  3118. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3119. res.set_content("ERROR", "text/html");
  3120. res.status = StatusCode::InternalServerError_500;
  3121. });
  3122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3123. auto se = detail::scope_exit([&] {
  3124. svr.stop();
  3125. thread.join();
  3126. ASSERT_FALSE(svr.is_running());
  3127. });
  3128. svr.wait_until_ready();
  3129. Client cli(HOST, PORT);
  3130. {
  3131. auto res = cli.Get("/exception");
  3132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3134. EXPECT_EQ("EXCEPTION", res->body);
  3135. }
  3136. {
  3137. auto res = cli.Get("/error");
  3138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3139. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3140. EXPECT_EQ("ERROR", res->body);
  3141. }
  3142. {
  3143. auto res = cli.Get("/invalid");
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3146. EXPECT_EQ("NOT_FOUND", res->body);
  3147. }
  3148. }
  3149. #endif
  3150. TEST(NoContentTest, ContentLength) {
  3151. Server svr;
  3152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3153. res.status = StatusCode::NoContent_204;
  3154. });
  3155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. {
  3163. Client cli(HOST, PORT);
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3167. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3168. }
  3169. }
  3170. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3171. #ifdef CPPHTTPLIB_SSL_ENABLED
  3172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3173. ASSERT_TRUE(svr.is_valid());
  3174. #else
  3175. Server svr;
  3176. #endif
  3177. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3178. if (req.path == "/routing_handler") {
  3179. res.set_header("PRE_ROUTING", "on");
  3180. res.set_content("Routing Handler", "text/plain");
  3181. return httplib::Server::HandlerResponse::Handled;
  3182. }
  3183. return httplib::Server::HandlerResponse::Unhandled;
  3184. });
  3185. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3186. res.set_content("Error", "text/html");
  3187. });
  3188. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3189. if (req.path == "/routing_handler") {
  3190. res.set_header("POST_ROUTING", "on");
  3191. }
  3192. });
  3193. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3194. res.set_content("Hello World!\n", "text/plain");
  3195. });
  3196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3197. auto se = detail::scope_exit([&] {
  3198. svr.stop();
  3199. thread.join();
  3200. ASSERT_FALSE(svr.is_running());
  3201. });
  3202. svr.wait_until_ready();
  3203. {
  3204. #ifdef CPPHTTPLIB_SSL_ENABLED
  3205. SSLClient cli(HOST, PORT);
  3206. cli.enable_server_certificate_verification(false);
  3207. #else
  3208. Client cli(HOST, PORT);
  3209. #endif
  3210. auto res = cli.Get("/routing_handler");
  3211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3212. EXPECT_EQ(StatusCode::OK_200, res->status);
  3213. EXPECT_EQ("Routing Handler", res->body);
  3214. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3215. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3216. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3217. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3218. }
  3219. {
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(HOST, PORT);
  3222. cli.enable_server_certificate_verification(false);
  3223. #else
  3224. Client cli(HOST, PORT);
  3225. #endif
  3226. auto res = cli.Get("/hi");
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("Hello World!\n", res->body);
  3230. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3231. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3232. }
  3233. {
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. SSLClient cli(HOST, PORT);
  3236. cli.enable_server_certificate_verification(false);
  3237. #else
  3238. Client cli(HOST, PORT);
  3239. #endif
  3240. auto res = cli.Get("/aaa");
  3241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3243. EXPECT_EQ("Error", res->body);
  3244. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3245. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3246. }
  3247. }
  3248. TEST(RequestHandlerTest, PreRequestHandler) {
  3249. auto route_path = "/user/:user";
  3250. Server svr;
  3251. svr.Get("/hi", [](const Request &, Response &res) {
  3252. res.set_content("hi", "text/plain");
  3253. });
  3254. svr.Get(route_path, [](const Request &req, Response &res) {
  3255. res.set_content(req.path_params.at("user"), "text/plain");
  3256. });
  3257. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3258. if (req.matched_route == route_path) {
  3259. auto user = req.path_params.at("user");
  3260. if (user != "john") {
  3261. res.status = StatusCode::Forbidden_403;
  3262. res.set_content("error", "text/html");
  3263. return Server::HandlerResponse::Handled;
  3264. }
  3265. }
  3266. return Server::HandlerResponse::Unhandled;
  3267. });
  3268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3269. auto se = detail::scope_exit([&] {
  3270. svr.stop();
  3271. thread.join();
  3272. ASSERT_FALSE(svr.is_running());
  3273. });
  3274. svr.wait_until_ready();
  3275. Client cli(HOST, PORT);
  3276. {
  3277. auto res = cli.Get("/hi");
  3278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3279. EXPECT_EQ(StatusCode::OK_200, res->status);
  3280. EXPECT_EQ("hi", res->body);
  3281. }
  3282. {
  3283. auto res = cli.Get("/user/john");
  3284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3285. EXPECT_EQ(StatusCode::OK_200, res->status);
  3286. EXPECT_EQ("john", res->body);
  3287. }
  3288. {
  3289. auto res = cli.Get("/user/invalid-user");
  3290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3291. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3292. EXPECT_EQ("error", res->body);
  3293. }
  3294. }
  3295. // The pre-request handler must run before the request body is read, so a
  3296. // rejected request never forces the server to buffer a (potentially large)
  3297. // body. Here the posted body is larger than the payload limit: if the body
  3298. // were read first the server would answer 413, but because the pre-request
  3299. // handler runs first it answers 403 and the body is never read.
  3300. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3301. Server svr;
  3302. svr.set_payload_max_length(8);
  3303. auto handler_ran = false;
  3304. svr.Post("/reject", [&](const Request &req, Response &res) {
  3305. handler_ran = true;
  3306. res.set_content(req.body, "text/plain");
  3307. });
  3308. svr.Post("/accept", [](const Request &req, Response &res) {
  3309. res.set_content(req.body, "text/plain");
  3310. });
  3311. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3312. if (req.matched_route == "/reject") {
  3313. res.status = StatusCode::Forbidden_403;
  3314. res.set_content("denied", "text/plain");
  3315. return Server::HandlerResponse::Handled;
  3316. }
  3317. return Server::HandlerResponse::Unhandled;
  3318. });
  3319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3320. auto se = detail::scope_exit([&] {
  3321. svr.stop();
  3322. thread.join();
  3323. ASSERT_FALSE(svr.is_running());
  3324. });
  3325. svr.wait_until_ready();
  3326. Client cli(HOST, PORT);
  3327. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3328. // rejects with 403 before the body is read, so 413 is never reached.
  3329. {
  3330. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3333. EXPECT_EQ("denied", res->body);
  3334. EXPECT_FALSE(handler_ran);
  3335. }
  3336. // An approved route still reads the body and enforces the payload limit.
  3337. {
  3338. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3341. }
  3342. }
  3343. TEST(UserDataTest, BasicOperations) {
  3344. httplib::UserData ud;
  3345. // Initially empty
  3346. EXPECT_FALSE(ud.has("key"));
  3347. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3348. // set and get
  3349. ud.set("key", 42);
  3350. EXPECT_TRUE(ud.has("key"));
  3351. auto *p = ud.get<int>("key");
  3352. ASSERT_NE(nullptr, p);
  3353. EXPECT_EQ(42, *p);
  3354. // Type mismatch → nullptr
  3355. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3356. // Overwrite with different type
  3357. ud.set("key", std::string("hello"));
  3358. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3359. auto *s = ud.get<std::string>("key");
  3360. ASSERT_NE(nullptr, s);
  3361. EXPECT_EQ("hello", *s);
  3362. // erase
  3363. ud.erase("key");
  3364. EXPECT_FALSE(ud.has("key"));
  3365. // clear
  3366. ud.set("a", 1);
  3367. ud.set("b", 2);
  3368. ud.clear();
  3369. EXPECT_FALSE(ud.has("a"));
  3370. EXPECT_FALSE(ud.has("b"));
  3371. }
  3372. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3373. struct AuthCtx {
  3374. std::string user_id;
  3375. };
  3376. Server svr;
  3377. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3378. res.user_data.set("auth", AuthCtx{"alice"});
  3379. return Server::HandlerResponse::Unhandled;
  3380. });
  3381. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3382. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3383. ASSERT_NE(nullptr, ctx);
  3384. res.set_content("Hello " + ctx->user_id, "text/plain");
  3385. });
  3386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3387. auto se = detail::scope_exit([&] {
  3388. svr.stop();
  3389. thread.join();
  3390. ASSERT_FALSE(svr.is_running());
  3391. });
  3392. svr.wait_until_ready();
  3393. Client cli(HOST, PORT);
  3394. auto res = cli.Get("/me");
  3395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("Hello alice", res->body);
  3398. }
  3399. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3400. struct RoleCtx {
  3401. std::string role;
  3402. };
  3403. Server svr;
  3404. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3405. res.user_data.set("role", RoleCtx{"admin"});
  3406. return Server::HandlerResponse::Unhandled;
  3407. });
  3408. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3409. auto *ctx = res.user_data.get<RoleCtx>("role");
  3410. ASSERT_NE(nullptr, ctx);
  3411. res.set_content(ctx->role, "text/plain");
  3412. });
  3413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3414. auto se = detail::scope_exit([&] {
  3415. svr.stop();
  3416. thread.join();
  3417. ASSERT_FALSE(svr.is_running());
  3418. });
  3419. svr.wait_until_ready();
  3420. Client cli(HOST, PORT);
  3421. auto res = cli.Get("/role");
  3422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3423. EXPECT_EQ(StatusCode::OK_200, res->status);
  3424. EXPECT_EQ("admin", res->body);
  3425. }
  3426. TEST(InvalidFormatTest, StatusCode) {
  3427. Server svr;
  3428. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3429. res.set_content("Hello World!\n", "text/plain");
  3430. res.status = 9999; // Status should be a three-digit code...
  3431. });
  3432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3433. auto se = detail::scope_exit([&] {
  3434. svr.stop();
  3435. thread.join();
  3436. ASSERT_FALSE(svr.is_running());
  3437. });
  3438. svr.wait_until_ready();
  3439. {
  3440. Client cli(HOST, PORT);
  3441. auto res = cli.Get("/hi");
  3442. ASSERT_FALSE(res);
  3443. }
  3444. }
  3445. TEST(URLFragmentTest, WithFragment) {
  3446. Server svr;
  3447. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3448. EXPECT_TRUE(req.target == "/hi");
  3449. });
  3450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. {
  3458. Client cli(HOST, PORT);
  3459. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3460. EXPECT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::OK_200, res->status);
  3462. res = cli.Get("/hi%23key1=val1=key2=val2");
  3463. EXPECT_TRUE(res);
  3464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3465. }
  3466. }
  3467. TEST(HeaderWriter, SetHeaderWriter) {
  3468. Server svr;
  3469. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3470. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3471. return detail::write_headers(strm, hdrs);
  3472. });
  3473. svr.Get("/hi", [](const Request &req, Response &res) {
  3474. auto it = req.headers.find("CustomClientHeader");
  3475. EXPECT_TRUE(it != req.headers.end());
  3476. EXPECT_EQ(it->second, "CustomClientValue");
  3477. res.set_content("Hello World!\n", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. {
  3487. Client cli(HOST, PORT);
  3488. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3489. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3490. return detail::write_headers(strm, hdrs);
  3491. });
  3492. auto res = cli.Get("/hi");
  3493. EXPECT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. auto it = res->headers.find("CustomServerHeader");
  3496. EXPECT_TRUE(it != res->headers.end());
  3497. EXPECT_EQ(it->second, "CustomServerValue");
  3498. }
  3499. }
  3500. class ServerTest : public ::testing::Test {
  3501. protected:
  3502. ServerTest()
  3503. : cli_(HOST, PORT)
  3504. #ifdef CPPHTTPLIB_SSL_ENABLED
  3505. ,
  3506. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3507. #endif
  3508. {
  3509. #ifdef CPPHTTPLIB_SSL_ENABLED
  3510. cli_.enable_server_certificate_verification(false);
  3511. #endif
  3512. // Allow LARGE_DATA (100MB) responses
  3513. cli_.set_payload_max_length(200 * 1024 * 1024);
  3514. }
  3515. virtual void SetUp() {
  3516. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3517. svr_.set_payload_max_length(200 * 1024 * 1024);
  3518. svr_.set_mount_point("/", "./www");
  3519. svr_.set_mount_point("/mount", "./www2");
  3520. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3521. svr_.Get("/hi",
  3522. [&](const Request & /*req*/, Response &res) {
  3523. res.set_content("Hello World!", "text/plain");
  3524. })
  3525. .Get("/file_content",
  3526. [&](const Request & /*req*/, Response &res) {
  3527. res.set_file_content("./www/dir/test.html");
  3528. })
  3529. .Get("/file_content_with_content_type",
  3530. [&](const Request & /*req*/, Response &res) {
  3531. res.set_file_content("./www/file", "text/plain");
  3532. })
  3533. .Get("/invalid_file_content",
  3534. [&](const Request & /*req*/, Response &res) {
  3535. res.set_file_content("./www/dir/invalid_file_path");
  3536. })
  3537. .Get("/http_response_splitting",
  3538. [&](const Request & /*req*/, Response &res) {
  3539. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3540. EXPECT_EQ(0U, res.headers.size());
  3541. EXPECT_FALSE(res.has_header("a"));
  3542. res.set_header("a", "1\nSet-Cookie: a=1");
  3543. EXPECT_EQ(0U, res.headers.size());
  3544. EXPECT_FALSE(res.has_header("a"));
  3545. res.set_header("a", "1\rSet-Cookie: a=1");
  3546. EXPECT_EQ(0U, res.headers.size());
  3547. EXPECT_FALSE(res.has_header("a"));
  3548. res.set_header("a\r\nb", "0");
  3549. EXPECT_EQ(0U, res.headers.size());
  3550. EXPECT_FALSE(res.has_header("a"));
  3551. res.set_header("a\rb", "0");
  3552. EXPECT_EQ(0U, res.headers.size());
  3553. EXPECT_FALSE(res.has_header("a"));
  3554. res.set_header("a\nb", "0");
  3555. EXPECT_EQ(0U, res.headers.size());
  3556. EXPECT_FALSE(res.has_header("a"));
  3557. res.set_redirect("1\r\nSet-Cookie: a=1");
  3558. EXPECT_EQ(0U, res.headers.size());
  3559. EXPECT_FALSE(res.has_header("Location"));
  3560. })
  3561. .Get("/slow",
  3562. [&](const Request & /*req*/, Response &res) {
  3563. std::this_thread::sleep_for(std::chrono::seconds(4));
  3564. res.set_content("slow", "text/plain");
  3565. })
  3566. #if 0
  3567. .Post("/slowpost",
  3568. [&](const Request & /*req*/, Response &res) {
  3569. std::this_thread::sleep_for(std::chrono::seconds(2));
  3570. res.set_content("slow", "text/plain");
  3571. })
  3572. #endif
  3573. .Get("/remote_addr",
  3574. [&](const Request &req, Response &res) {
  3575. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3576. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3577. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3578. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3579. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3580. #endif
  3581. res.set_content(req.remote_addr, "text/plain");
  3582. })
  3583. .Get("/local_addr",
  3584. [&](const Request &req, Response &res) {
  3585. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3586. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3587. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3588. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3589. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3590. #endif
  3591. auto local_addr = req.local_addr;
  3592. auto local_port = std::to_string(req.local_port);
  3593. res.set_content(local_addr.append(":").append(local_port),
  3594. "text/plain");
  3595. })
  3596. .Get("/endwith%",
  3597. [&](const Request & /*req*/, Response &res) {
  3598. res.set_content("Hello World!", "text/plain");
  3599. })
  3600. .Get("/a\\+\\+b",
  3601. [&](const Request &req, Response &res) {
  3602. ASSERT_TRUE(req.has_param("a +b"));
  3603. auto val = req.get_param_value("a +b");
  3604. res.set_content(val, "text/plain");
  3605. })
  3606. .Get("/", [&](const Request & /*req*/,
  3607. Response &res) { res.set_redirect("/hi"); })
  3608. .Post("/1",
  3609. [](const Request & /*req*/, Response &res) {
  3610. res.set_redirect("/2", StatusCode::SeeOther_303);
  3611. })
  3612. .Get("/2",
  3613. [](const Request & /*req*/, Response &res) {
  3614. res.set_content("redirected.", "text/plain");
  3615. res.status = StatusCode::OK_200;
  3616. })
  3617. .Post("/person",
  3618. [&](const Request &req, Response &res) {
  3619. if (req.has_param("name") && req.has_param("note")) {
  3620. persons_[req.get_param_value("name")] =
  3621. req.get_param_value("note");
  3622. } else {
  3623. res.status = StatusCode::BadRequest_400;
  3624. }
  3625. })
  3626. .Put("/person",
  3627. [&](const Request &req, Response &res) {
  3628. if (req.has_param("name") && req.has_param("note")) {
  3629. persons_[req.get_param_value("name")] =
  3630. req.get_param_value("note");
  3631. } else {
  3632. res.status = StatusCode::BadRequest_400;
  3633. }
  3634. })
  3635. .Get("/person/(.*)",
  3636. [&](const Request &req, Response &res) {
  3637. string name = req.matches[1];
  3638. if (persons_.find(name) != persons_.end()) {
  3639. auto note = persons_[name];
  3640. res.set_content(note, "text/plain");
  3641. } else {
  3642. res.status = StatusCode::NotFound_404;
  3643. }
  3644. })
  3645. .Delete("/person",
  3646. [&](const Request &req, Response &res) {
  3647. if (req.has_param("name")) {
  3648. string name = req.get_param_value("name");
  3649. if (persons_.find(name) != persons_.end()) {
  3650. persons_.erase(name);
  3651. res.set_content("DELETED", "text/plain");
  3652. } else {
  3653. res.status = StatusCode::NotFound_404;
  3654. }
  3655. } else {
  3656. res.status = StatusCode::BadRequest_400;
  3657. }
  3658. })
  3659. .Post("/x-www-form-urlencoded-json",
  3660. [&](const Request &req, Response &res) {
  3661. auto json = req.get_param_value("json");
  3662. ASSERT_EQ(JSON_DATA, json);
  3663. res.set_content(json, "appliation/json");
  3664. res.status = StatusCode::OK_200;
  3665. })
  3666. .Get("/streamed-chunked",
  3667. [&](const Request & /*req*/, Response &res) {
  3668. res.set_chunked_content_provider(
  3669. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3670. sink.os << "123";
  3671. sink.os << "456";
  3672. sink.os << "789";
  3673. sink.done();
  3674. return true;
  3675. });
  3676. })
  3677. .Get("/streamed-chunked-with-prohibited-trailer",
  3678. [&](const Request & /*req*/, Response &res) {
  3679. auto i = new int(0);
  3680. // Declare both a prohibited trailer (Content-Length) and an
  3681. // allowed one
  3682. res.set_header("Trailer", "Content-Length, X-Allowed");
  3683. res.set_chunked_content_provider(
  3684. "text/plain",
  3685. [i](size_t /*offset*/, DataSink &sink) {
  3686. switch (*i) {
  3687. case 0: sink.os << "123"; break;
  3688. case 1: sink.os << "456"; break;
  3689. case 2: sink.os << "789"; break;
  3690. case 3: {
  3691. sink.done_with_trailer(
  3692. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3693. } break;
  3694. }
  3695. (*i)++;
  3696. return true;
  3697. },
  3698. [i](bool success) {
  3699. EXPECT_TRUE(success);
  3700. delete i;
  3701. });
  3702. })
  3703. .Get("/streamed-chunked2",
  3704. [&](const Request & /*req*/, Response &res) {
  3705. auto i = new int(0);
  3706. res.set_chunked_content_provider(
  3707. "text/plain",
  3708. [i](size_t /*offset*/, DataSink &sink) {
  3709. switch (*i) {
  3710. case 0: sink.os << "123"; break;
  3711. case 1: sink.os << "456"; break;
  3712. case 2: sink.os << "789"; break;
  3713. case 3: sink.done(); break;
  3714. }
  3715. (*i)++;
  3716. return true;
  3717. },
  3718. [i](bool success) {
  3719. EXPECT_TRUE(success);
  3720. delete i;
  3721. });
  3722. })
  3723. .Get("/streamed-chunked-with-trailer",
  3724. [&](const Request & /*req*/, Response &res) {
  3725. auto i = new int(0);
  3726. res.set_header("Trailer", "Dummy1, Dummy2");
  3727. res.set_chunked_content_provider(
  3728. "text/plain",
  3729. [i](size_t /*offset*/, DataSink &sink) {
  3730. switch (*i) {
  3731. case 0: sink.os << "123"; break;
  3732. case 1: sink.os << "456"; break;
  3733. case 2: sink.os << "789"; break;
  3734. case 3: {
  3735. sink.done_with_trailer(
  3736. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3737. } break;
  3738. }
  3739. (*i)++;
  3740. return true;
  3741. },
  3742. [i](bool success) {
  3743. EXPECT_TRUE(success);
  3744. delete i;
  3745. });
  3746. })
  3747. .Get("/streamed",
  3748. [&](const Request & /*req*/, Response &res) {
  3749. res.set_content_provider(
  3750. 6, "text/plain",
  3751. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3752. sink.os << (offset < 3 ? "a" : "b");
  3753. return true;
  3754. });
  3755. })
  3756. .Get("/streamed-without-length",
  3757. [&](const Request & /*req*/, Response &res) {
  3758. auto data = new std::string("abcdefg");
  3759. res.set_content_provider(
  3760. "text/plain",
  3761. [data](size_t offset, DataSink &sink) {
  3762. if (offset < data->size()) {
  3763. sink.os << data->substr(offset);
  3764. }
  3765. sink.done();
  3766. return true;
  3767. },
  3768. [data](bool success) {
  3769. EXPECT_TRUE(success);
  3770. delete data;
  3771. });
  3772. })
  3773. .Get("/streamed-with-range",
  3774. [&](const Request &req, Response &res) {
  3775. auto data = new std::string("abcdefg");
  3776. res.set_content_provider(
  3777. data->size(), "text/plain",
  3778. [data](size_t offset, size_t length, DataSink &sink) {
  3779. size_t DATA_CHUNK_SIZE = 4;
  3780. const auto &d = *data;
  3781. auto out_len =
  3782. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3783. auto ret =
  3784. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3785. EXPECT_TRUE(ret);
  3786. return true;
  3787. },
  3788. [data, &req](bool success) {
  3789. EXPECT_EQ(success, !req.has_param("error"));
  3790. delete data;
  3791. });
  3792. })
  3793. .Get("/streamed-cancel",
  3794. [&](const Request & /*req*/, Response &res) {
  3795. res.set_content_provider(
  3796. size_t(-1), "text/plain",
  3797. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3798. sink.os << "data_chunk";
  3799. return true;
  3800. });
  3801. })
  3802. .Get("/regex-with-delimiter",
  3803. [&](const Request &req, Response & /*res*/) {
  3804. ASSERT_TRUE(req.has_param("key"));
  3805. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3806. })
  3807. .Get("/with-range",
  3808. [&](const Request & /*req*/, Response &res) {
  3809. res.set_content("abcdefg", "text/plain");
  3810. })
  3811. .Get("/test-start-time",
  3812. [&](const Request &req, Response & /*res*/) {
  3813. EXPECT_NE(req.start_time_,
  3814. std::chrono::steady_clock::time_point::min());
  3815. })
  3816. .Get("/with-range-customized-response",
  3817. [&](const Request & /*req*/, Response &res) {
  3818. res.status = StatusCode::BadRequest_400;
  3819. res.set_content(JSON_DATA, "application/json");
  3820. })
  3821. .Post("/chunked",
  3822. [&](const Request &req, Response & /*res*/) {
  3823. EXPECT_EQ(req.body, "dechunked post body");
  3824. })
  3825. .Post("/large-chunked",
  3826. [&](const Request &req, Response & /*res*/) {
  3827. std::string expected(6 * 30 * 1024u, 'a');
  3828. EXPECT_EQ(req.body, expected);
  3829. })
  3830. .Post("/multipart",
  3831. [&](const Request &req, Response & /*res*/) {
  3832. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3833. req.form.get_field_count("text2") +
  3834. req.form.get_field_count("file3") +
  3835. req.form.get_field_count("file4"));
  3836. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3837. req.form.get_file_count("file2"));
  3838. ASSERT_TRUE(!req.form.has_file("???"));
  3839. ASSERT_TRUE(!req.form.has_field("???"));
  3840. ASSERT_TRUE(req.body.empty());
  3841. {
  3842. const auto &text = req.form.get_field("text1");
  3843. EXPECT_EQ("text default", text);
  3844. }
  3845. {
  3846. const auto &text = req.form.get_field("text2");
  3847. EXPECT_EQ("aωb", text);
  3848. }
  3849. {
  3850. const auto &file = req.form.get_file("file1");
  3851. EXPECT_EQ("hello.txt", file.filename);
  3852. EXPECT_EQ("text/plain", file.content_type);
  3853. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3854. }
  3855. {
  3856. const auto &file = req.form.get_file("file2");
  3857. EXPECT_EQ("world.json", file.filename);
  3858. EXPECT_EQ("application/json", file.content_type);
  3859. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3860. }
  3861. {
  3862. const auto &text = req.form.get_field("file3");
  3863. EXPECT_EQ(0u, text.size());
  3864. }
  3865. {
  3866. const auto &text = req.form.get_field("file4");
  3867. EXPECT_EQ(0u, text.size());
  3868. }
  3869. })
  3870. .Post("/multipart/multi_file_values",
  3871. [&](const Request &req, Response & /*res*/) {
  3872. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3873. req.form.get_field_count("multi_text1"));
  3874. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3875. ASSERT_TRUE(!req.form.has_file("???"));
  3876. ASSERT_TRUE(!req.form.has_field("???"));
  3877. ASSERT_TRUE(req.body.empty());
  3878. {
  3879. const auto &text = req.form.get_field("text");
  3880. EXPECT_EQ("default text", text);
  3881. }
  3882. {
  3883. const auto &text1_values = req.form.get_fields("multi_text1");
  3884. EXPECT_EQ(2u, text1_values.size());
  3885. EXPECT_EQ("aaaaa", text1_values[0]);
  3886. EXPECT_EQ("bbbbb", text1_values[1]);
  3887. }
  3888. {
  3889. const auto &file1_values = req.form.get_files("multi_file1");
  3890. EXPECT_EQ(2u, file1_values.size());
  3891. auto file1 = file1_values[0];
  3892. EXPECT_EQ(file1.filename, "hello.txt");
  3893. EXPECT_EQ(file1.content_type, "text/plain");
  3894. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3895. auto file2 = file1_values[1];
  3896. EXPECT_EQ(file2.filename, "world.json");
  3897. EXPECT_EQ(file2.content_type, "application/json");
  3898. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3899. }
  3900. })
  3901. .Post("/empty",
  3902. [&](const Request &req, Response &res) {
  3903. EXPECT_EQ(req.body, "");
  3904. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3905. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3906. res.set_content("empty", "text/plain");
  3907. })
  3908. .Post("/empty-no-content-type",
  3909. [&](const Request &req, Response &res) {
  3910. EXPECT_EQ(req.body, "");
  3911. EXPECT_FALSE(req.has_header("Content-Type"));
  3912. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3913. res.set_content("empty-no-content-type", "text/plain");
  3914. })
  3915. .Post("/path-only",
  3916. [&](const Request &req, Response &res) {
  3917. EXPECT_EQ(req.body, "");
  3918. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3920. res.set_content("path-only", "text/plain");
  3921. })
  3922. .Post("/path-headers-only",
  3923. [&](const Request &req, Response &res) {
  3924. EXPECT_EQ(req.body, "");
  3925. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3926. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3927. EXPECT_EQ("world", req.get_header_value("hello"));
  3928. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3929. res.set_content("path-headers-only", "text/plain");
  3930. })
  3931. .Post("/post-large",
  3932. [&](const Request &req, Response &res) {
  3933. EXPECT_EQ(req.body, LARGE_DATA);
  3934. res.set_content(req.body, "text/plain");
  3935. })
  3936. .Post("/post-loopback",
  3937. [&](const Request &, Response &res,
  3938. ContentReader const &content_reader) {
  3939. std::string body;
  3940. content_reader([&](const char *data, size_t data_length) {
  3941. body.append(data, data_length);
  3942. return true;
  3943. });
  3944. res.set_content(body, "text/plain");
  3945. })
  3946. .Put("/put-loopback",
  3947. [&](const Request &, Response &res,
  3948. ContentReader const &content_reader) {
  3949. std::string body;
  3950. content_reader([&](const char *data, size_t data_length) {
  3951. body.append(data, data_length);
  3952. return true;
  3953. });
  3954. res.set_content(body, "text/plain");
  3955. })
  3956. .Patch("/patch-loopback",
  3957. [&](const Request &, Response &res,
  3958. ContentReader const &content_reader) {
  3959. std::string body;
  3960. content_reader([&](const char *data, size_t data_length) {
  3961. body.append(data, data_length);
  3962. return true;
  3963. });
  3964. res.set_content(body, "text/plain");
  3965. })
  3966. .Put("/empty-no-content-type",
  3967. [&](const Request &req, Response &res) {
  3968. EXPECT_EQ(req.body, "");
  3969. EXPECT_FALSE(req.has_header("Content-Type"));
  3970. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3971. res.set_content("empty-no-content-type", "text/plain");
  3972. })
  3973. .Put("/put",
  3974. [&](const Request &req, Response &res) {
  3975. EXPECT_EQ(req.body, "PUT");
  3976. res.set_content(req.body, "text/plain");
  3977. })
  3978. .Put("/put-large",
  3979. [&](const Request &req, Response &res) {
  3980. EXPECT_EQ(req.body, LARGE_DATA);
  3981. res.set_content(req.body, "text/plain");
  3982. })
  3983. .Patch("/patch",
  3984. [&](const Request &req, Response &res) {
  3985. EXPECT_EQ(req.body, "PATCH");
  3986. res.set_content(req.body, "text/plain");
  3987. })
  3988. .Delete("/delete",
  3989. [&](const Request & /*req*/, Response &res) {
  3990. res.set_content("DELETE", "text/plain");
  3991. })
  3992. .Delete("/delete-body",
  3993. [&](const Request &req, Response &res) {
  3994. EXPECT_EQ(req.body, "content");
  3995. res.set_content(req.body, "text/plain");
  3996. })
  3997. .Options(R"(\*)",
  3998. [&](const Request & /*req*/, Response &res) {
  3999. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4000. })
  4001. .Get("/request-target",
  4002. [&](const Request &req, Response & /*res*/) {
  4003. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4004. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4005. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4006. })
  4007. .Get("/long-query-value",
  4008. [&](const Request &req, Response & /*res*/) {
  4009. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4010. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4011. })
  4012. .Get("/too-long-query-value",
  4013. [&](const Request &req, Response & /*res*/) {
  4014. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4015. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4016. })
  4017. .Get("/array-param",
  4018. [&](const Request &req, Response & /*res*/) {
  4019. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4020. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4021. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4022. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4023. })
  4024. .Get("/array-param-values",
  4025. [&](const Request &req, Response & /*res*/) {
  4026. auto values = req.get_param_values("array");
  4027. EXPECT_EQ(3u, values.size());
  4028. EXPECT_EQ("value1", values[0]);
  4029. EXPECT_EQ("value2", values[1]);
  4030. EXPECT_EQ("value3", values[2]);
  4031. auto empty = req.get_param_values("nonexistent");
  4032. EXPECT_TRUE(empty.empty());
  4033. })
  4034. .Post("/validate-no-multiple-headers",
  4035. [&](const Request &req, Response & /*res*/) {
  4036. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4037. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4038. })
  4039. .Post("/content_receiver",
  4040. [&](const Request &req, Response &res,
  4041. const ContentReader &content_reader) {
  4042. if (req.is_multipart_form_data()) {
  4043. std::vector<FormData> items;
  4044. content_reader(
  4045. [&](const FormData &file) {
  4046. items.push_back(file);
  4047. return true;
  4048. },
  4049. [&](const char *data, size_t data_length) {
  4050. items.back().content.append(data, data_length);
  4051. return true;
  4052. });
  4053. EXPECT_EQ(5u, items.size());
  4054. {
  4055. const auto &file = get_file_value(items, "text1");
  4056. EXPECT_TRUE(file.filename.empty());
  4057. EXPECT_EQ("text default", file.content);
  4058. }
  4059. {
  4060. const auto &file = get_file_value(items, "text2");
  4061. EXPECT_TRUE(file.filename.empty());
  4062. EXPECT_EQ("aωb", file.content);
  4063. }
  4064. {
  4065. const auto &file = get_file_value(items, "file1");
  4066. EXPECT_EQ("hello.txt", file.filename);
  4067. EXPECT_EQ("text/plain", file.content_type);
  4068. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4069. }
  4070. {
  4071. const auto &file = get_file_value(items, "file2");
  4072. EXPECT_EQ("world.json", file.filename);
  4073. EXPECT_EQ("application/json", file.content_type);
  4074. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4075. }
  4076. {
  4077. const auto &file = get_file_value(items, "file3");
  4078. EXPECT_TRUE(file.filename.empty());
  4079. EXPECT_EQ("application/octet-stream", file.content_type);
  4080. EXPECT_EQ(0u, file.content.size());
  4081. }
  4082. } else {
  4083. std::string body;
  4084. content_reader([&](const char *data, size_t data_length) {
  4085. EXPECT_EQ(7U, data_length);
  4086. body.append(data, data_length);
  4087. return true;
  4088. });
  4089. EXPECT_EQ(body, "content");
  4090. res.set_content(body, "text/plain");
  4091. }
  4092. })
  4093. .Put("/content_receiver",
  4094. [&](const Request & /*req*/, Response &res,
  4095. const ContentReader &content_reader) {
  4096. std::string body;
  4097. content_reader([&](const char *data, size_t data_length) {
  4098. body.append(data, data_length);
  4099. return true;
  4100. });
  4101. EXPECT_EQ(body, "content");
  4102. res.set_content(body, "text/plain");
  4103. })
  4104. .Patch("/content_receiver",
  4105. [&](const Request & /*req*/, Response &res,
  4106. const ContentReader &content_reader) {
  4107. std::string body;
  4108. content_reader([&](const char *data, size_t data_length) {
  4109. body.append(data, data_length);
  4110. return true;
  4111. });
  4112. EXPECT_EQ(body, "content");
  4113. res.set_content(body, "text/plain");
  4114. })
  4115. .Post("/query-string-and-body",
  4116. [&](const Request &req, Response & /*res*/) {
  4117. ASSERT_TRUE(req.has_param("key"));
  4118. EXPECT_EQ(req.get_param_value("key"), "value");
  4119. EXPECT_EQ(req.body, "content");
  4120. })
  4121. .Get("/last-request",
  4122. [&](const Request &req, Response & /*res*/) {
  4123. EXPECT_EQ("close", req.get_header_value("Connection"));
  4124. })
  4125. .Get(R"(/redirect/(\d+))",
  4126. [&](const Request &req, Response &res) {
  4127. auto num = std::stoi(req.matches[1]) + 1;
  4128. std::string url = "/redirect/" + std::to_string(num);
  4129. res.set_redirect(url);
  4130. })
  4131. .Post("/binary",
  4132. [&](const Request &req, Response &res) {
  4133. EXPECT_EQ(4U, req.body.size());
  4134. EXPECT_EQ("application/octet-stream",
  4135. req.get_header_value("Content-Type"));
  4136. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4137. res.set_content(req.body, "application/octet-stream");
  4138. })
  4139. .Put("/binary",
  4140. [&](const Request &req, Response &res) {
  4141. EXPECT_EQ(4U, req.body.size());
  4142. EXPECT_EQ("application/octet-stream",
  4143. req.get_header_value("Content-Type"));
  4144. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4145. res.set_content(req.body, "application/octet-stream");
  4146. })
  4147. .Patch("/binary",
  4148. [&](const Request &req, Response &res) {
  4149. EXPECT_EQ(4U, req.body.size());
  4150. EXPECT_EQ("application/octet-stream",
  4151. req.get_header_value("Content-Type"));
  4152. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4153. res.set_content(req.body, "application/octet-stream");
  4154. })
  4155. .Delete("/binary",
  4156. [&](const Request &req, Response &res) {
  4157. EXPECT_EQ(4U, req.body.size());
  4158. EXPECT_EQ("application/octet-stream",
  4159. req.get_header_value("Content-Type"));
  4160. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4161. res.set_content(req.body, "application/octet-stream");
  4162. })
  4163. .Get("/issue1772",
  4164. [&](const Request & /*req*/, Response &res) {
  4165. res.status = 401;
  4166. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4167. })
  4168. .Delete("/issue609",
  4169. [](const httplib::Request &, httplib::Response &res,
  4170. const httplib::ContentReader &) {
  4171. res.set_content("ok", "text/plain");
  4172. })
  4173. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4174. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4175. .Get("/compress",
  4176. [&](const Request & /*req*/, Response &res) {
  4177. res.set_content(
  4178. "12345678901234567890123456789012345678901234567890123456789"
  4179. "01234567890123456789012345678901234567890",
  4180. "text/plain");
  4181. })
  4182. .Get("/compress-with-charset",
  4183. [&](const Request & /*req*/, Response &res) {
  4184. res.set_content(
  4185. "12345678901234567890123456789012345678901234567890123456789"
  4186. "01234567890123456789012345678901234567890",
  4187. "application/json; charset=utf-8");
  4188. })
  4189. .Get("/nocompress",
  4190. [&](const Request & /*req*/, Response &res) {
  4191. res.set_content(
  4192. "12345678901234567890123456789012345678901234567890123456789"
  4193. "01234567890123456789012345678901234567890",
  4194. "application/octet-stream");
  4195. })
  4196. .Post("/compress-multipart",
  4197. [&](const Request &req, Response & /*res*/) {
  4198. EXPECT_EQ(2u, req.form.fields.size());
  4199. ASSERT_TRUE(!req.form.has_field("???"));
  4200. {
  4201. const auto &text = req.form.get_field("key1");
  4202. EXPECT_EQ("test", text);
  4203. }
  4204. {
  4205. const auto &text = req.form.get_field("key2");
  4206. EXPECT_EQ("--abcdefg123", text);
  4207. }
  4208. })
  4209. #endif
  4210. ;
  4211. persons_["john"] = "programmer";
  4212. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4213. svr_.wait_until_ready();
  4214. }
  4215. virtual void TearDown() {
  4216. svr_.stop();
  4217. if (!request_threads_.empty()) {
  4218. std::this_thread::sleep_for(std::chrono::seconds(1));
  4219. for (auto &t : request_threads_) {
  4220. t.join();
  4221. }
  4222. }
  4223. t_.join();
  4224. }
  4225. map<string, string> persons_;
  4226. #ifdef CPPHTTPLIB_SSL_ENABLED
  4227. SSLClient cli_;
  4228. SSLServer svr_;
  4229. #else
  4230. Client cli_;
  4231. Server svr_;
  4232. #endif
  4233. thread t_;
  4234. std::vector<thread> request_threads_;
  4235. };
  4236. TEST_F(ServerTest, GetMethod200) {
  4237. auto res = cli_.Get("/hi");
  4238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4239. EXPECT_EQ("HTTP/1.1", res->version);
  4240. EXPECT_EQ(StatusCode::OK_200, res->status);
  4241. EXPECT_EQ("OK", res->reason);
  4242. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4243. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4244. EXPECT_EQ("Hello World!", res->body);
  4245. }
  4246. TEST_F(ServerTest, GetEmptyFile) {
  4247. auto res = cli_.Get("/empty_file");
  4248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4251. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4252. EXPECT_EQ("", res->body);
  4253. }
  4254. TEST_F(ServerTest, GetFileContent) {
  4255. auto res = cli_.Get("/file_content");
  4256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4257. EXPECT_EQ(StatusCode::OK_200, res->status);
  4258. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4259. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4260. EXPECT_EQ("test.html", res->body);
  4261. }
  4262. TEST_F(ServerTest, GetFileContentWithRange) {
  4263. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4265. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4266. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4267. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4268. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4269. EXPECT_EQ("est", res->body);
  4270. }
  4271. TEST_F(ServerTest, GetFileContentWithContentType) {
  4272. auto res = cli_.Get("/file_content_with_content_type");
  4273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4274. EXPECT_EQ(StatusCode::OK_200, res->status);
  4275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4276. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4277. EXPECT_EQ("file\n", res->body);
  4278. }
  4279. TEST_F(ServerTest, GetInvalidFileContent) {
  4280. auto res = cli_.Get("/invalid_file_content");
  4281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4283. }
  4284. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4285. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4287. EXPECT_EQ("HTTP/1.1", res->version);
  4288. EXPECT_EQ(StatusCode::OK_200, res->status);
  4289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4290. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4291. EXPECT_EQ("Hello World!", res->body);
  4292. }
  4293. TEST_F(ServerTest, GetMethod302) {
  4294. auto res = cli_.Get("/");
  4295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4296. EXPECT_EQ(StatusCode::Found_302, res->status);
  4297. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4298. }
  4299. TEST_F(ServerTest, GetMethod302Redirect) {
  4300. cli_.set_follow_location(true);
  4301. auto res = cli_.Get("/");
  4302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ("Hello World!", res->body);
  4305. EXPECT_EQ("/hi", res->location);
  4306. }
  4307. TEST_F(ServerTest, GetMethod404) {
  4308. auto res = cli_.Get("/invalid");
  4309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4310. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4311. }
  4312. TEST_F(ServerTest, HeadMethod200) {
  4313. auto res = cli_.Head("/hi");
  4314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4315. EXPECT_EQ(StatusCode::OK_200, res->status);
  4316. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4317. EXPECT_TRUE(res->body.empty());
  4318. }
  4319. TEST_F(ServerTest, HeadMethod200Static) {
  4320. auto res = cli_.Head("/mount/dir/index.html");
  4321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4322. EXPECT_EQ(StatusCode::OK_200, res->status);
  4323. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4324. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4325. EXPECT_TRUE(res->body.empty());
  4326. }
  4327. TEST_F(ServerTest, HeadMethod404) {
  4328. auto res = cli_.Head("/invalid");
  4329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4331. EXPECT_TRUE(res->body.empty());
  4332. }
  4333. TEST_F(ServerTest, GetMethodPersonJohn) {
  4334. auto res = cli_.Get("/person/john");
  4335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4338. EXPECT_EQ("programmer", res->body);
  4339. }
  4340. TEST_F(ServerTest, PostMethod1) {
  4341. auto res = cli_.Get("/person/john1");
  4342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4343. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4344. res = cli_.Post("/person", "name=john1&note=coder",
  4345. "application/x-www-form-urlencoded");
  4346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4347. ASSERT_EQ(StatusCode::OK_200, res->status);
  4348. res = cli_.Get("/person/john1");
  4349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4350. ASSERT_EQ(StatusCode::OK_200, res->status);
  4351. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4352. ASSERT_EQ("coder", res->body);
  4353. }
  4354. TEST_F(ServerTest, PostMethod2) {
  4355. auto res = cli_.Get("/person/john2");
  4356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4357. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4358. Params params;
  4359. params.emplace("name", "john2");
  4360. params.emplace("note", "coder");
  4361. res = cli_.Post("/person", params);
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. ASSERT_EQ(StatusCode::OK_200, res->status);
  4364. res = cli_.Get("/person/john2");
  4365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4366. ASSERT_EQ(StatusCode::OK_200, res->status);
  4367. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4368. ASSERT_EQ("coder", res->body);
  4369. }
  4370. TEST_F(ServerTest, PutMethod3) {
  4371. auto res = cli_.Get("/person/john3");
  4372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4373. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4374. Params params;
  4375. params.emplace("name", "john3");
  4376. params.emplace("note", "coder");
  4377. res = cli_.Put("/person", params);
  4378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4379. ASSERT_EQ(StatusCode::OK_200, res->status);
  4380. res = cli_.Get("/person/john3");
  4381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4382. ASSERT_EQ(StatusCode::OK_200, res->status);
  4383. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4384. ASSERT_EQ("coder", res->body);
  4385. }
  4386. TEST_F(ServerTest, DeleteMethod1) {
  4387. auto res = cli_.Get("/person/john4");
  4388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4389. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4390. Params params;
  4391. params.emplace("name", "john4");
  4392. params.emplace("note", "coder");
  4393. res = cli_.Post("/person", params);
  4394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4395. ASSERT_EQ(StatusCode::OK_200, res->status);
  4396. res = cli_.Get("/person/john4");
  4397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4398. ASSERT_EQ(StatusCode::OK_200, res->status);
  4399. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4400. ASSERT_EQ("coder", res->body);
  4401. Params delete_params;
  4402. delete_params.emplace("name", "john4");
  4403. res = cli_.Delete("/person", delete_params);
  4404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4405. ASSERT_EQ(StatusCode::OK_200, res->status);
  4406. ASSERT_EQ("DELETED", res->body);
  4407. res = cli_.Get("/person/john4");
  4408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4410. }
  4411. TEST_F(ServerTest, DeleteMethod2) {
  4412. auto res = cli_.Get("/person/john5");
  4413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4414. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4415. Params params;
  4416. params.emplace("name", "john5");
  4417. params.emplace("note", "developer");
  4418. res = cli_.Post("/person", params);
  4419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4420. ASSERT_EQ(StatusCode::OK_200, res->status);
  4421. res = cli_.Get("/person/john5");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. ASSERT_EQ(StatusCode::OK_200, res->status);
  4424. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4425. ASSERT_EQ("developer", res->body);
  4426. Params delete_params;
  4427. delete_params.emplace("name", "john5");
  4428. Headers headers;
  4429. headers.emplace("Custom-Header", "test-value");
  4430. res = cli_.Delete("/person", headers, delete_params);
  4431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4432. ASSERT_EQ(StatusCode::OK_200, res->status);
  4433. ASSERT_EQ("DELETED", res->body);
  4434. res = cli_.Get("/person/john5");
  4435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4436. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4437. }
  4438. TEST_F(ServerTest, DeleteMethod3) {
  4439. auto res = cli_.Get("/person/john6");
  4440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4441. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4442. Params params;
  4443. params.emplace("name", "john6");
  4444. params.emplace("note", "tester");
  4445. res = cli_.Post("/person", params);
  4446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4447. ASSERT_EQ(StatusCode::OK_200, res->status);
  4448. res = cli_.Get("/person/john6");
  4449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4450. ASSERT_EQ(StatusCode::OK_200, res->status);
  4451. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4452. ASSERT_EQ("tester", res->body);
  4453. Params delete_params;
  4454. delete_params.emplace("name", "john6");
  4455. Headers headers;
  4456. headers.emplace("Custom-Header", "test-value");
  4457. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4459. ASSERT_EQ(StatusCode::OK_200, res->status);
  4460. ASSERT_EQ("DELETED", res->body);
  4461. res = cli_.Get("/person/john6");
  4462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4463. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4464. }
  4465. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4466. Params params;
  4467. params.emplace("json", JSON_DATA);
  4468. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4470. ASSERT_EQ(StatusCode::OK_200, res->status);
  4471. ASSERT_EQ(JSON_DATA, res->body);
  4472. }
  4473. TEST_F(ServerTest, PostEmptyContent) {
  4474. auto res = cli_.Post("/empty", "", "text/plain");
  4475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4476. ASSERT_EQ(StatusCode::OK_200, res->status);
  4477. ASSERT_EQ("empty", res->body);
  4478. }
  4479. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4480. auto res = cli_.Post("/empty-no-content-type");
  4481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4482. ASSERT_EQ(StatusCode::OK_200, res->status);
  4483. ASSERT_EQ("empty-no-content-type", res->body);
  4484. }
  4485. TEST_F(ServerTest, PostPathOnly) {
  4486. auto res = cli_.Post("/path-only");
  4487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4488. ASSERT_EQ(StatusCode::OK_200, res->status);
  4489. ASSERT_EQ("path-only", res->body);
  4490. }
  4491. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4492. auto res = cli_.Post("/path-headers-only",
  4493. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4495. ASSERT_EQ(StatusCode::OK_200, res->status);
  4496. ASSERT_EQ("path-headers-only", res->body);
  4497. }
  4498. TEST_F(ServerTest, PostLarge) {
  4499. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4501. ASSERT_EQ(StatusCode::OK_200, res->status);
  4502. EXPECT_EQ(LARGE_DATA, res->body);
  4503. }
  4504. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4505. auto res = cli_.Put("/empty-no-content-type");
  4506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4507. ASSERT_EQ(StatusCode::OK_200, res->status);
  4508. ASSERT_EQ("empty-no-content-type", res->body);
  4509. }
  4510. TEST_F(ServerTest, GetMethodDir) {
  4511. auto res = cli_.Get("/dir/");
  4512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4513. EXPECT_EQ(StatusCode::OK_200, res->status);
  4514. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4515. auto body = R"(<html>
  4516. <head>
  4517. </head>
  4518. <body>
  4519. <a href="/dir/test.html">Test</a>
  4520. <a href="/hi">hi</a>
  4521. </body>
  4522. </html>
  4523. )";
  4524. EXPECT_EQ(body, res->body);
  4525. }
  4526. TEST_F(ServerTest, GetMethodDirTest) {
  4527. auto res = cli_.Get("/dir/test.html");
  4528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4529. EXPECT_EQ(StatusCode::OK_200, res->status);
  4530. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4531. EXPECT_EQ("test.html", res->body);
  4532. }
  4533. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4534. auto res = cli_.Get("/dir/../dir/test.html");
  4535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4538. EXPECT_EQ("test.html", res->body);
  4539. }
  4540. TEST_F(ServerTest, GetMethodInvalidPath) {
  4541. auto res = cli_.Get("/dir/../test.html");
  4542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4544. }
  4545. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4546. auto res = cli_.Get("/../www/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, GetMethodOutOfBaseDir2) {
  4551. auto res = cli_.Get("/dir/../../www/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, GetMethodDirMountTest) {
  4556. auto res = cli_.Get("/mount/dir/test.html");
  4557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4558. EXPECT_EQ(StatusCode::OK_200, res->status);
  4559. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4560. EXPECT_EQ("test.html", res->body);
  4561. }
  4562. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4563. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4567. EXPECT_EQ("test.html", res->body);
  4568. }
  4569. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4570. auto res = cli_.Get("/mount/dir/../test.html");
  4571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4573. }
  4574. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4575. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4578. }
  4579. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4580. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4582. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4583. }
  4584. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4585. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4588. }
  4589. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4590. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4592. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4593. }
  4594. TEST_F(ServerTest, PostMethod303) {
  4595. auto res = cli_.Post("/1", "body", "text/plain");
  4596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4597. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4598. EXPECT_EQ("/2", res->get_header_value("Location"));
  4599. }
  4600. TEST_F(ServerTest, PostMethod303Redirect) {
  4601. cli_.set_follow_location(true);
  4602. auto res = cli_.Post("/1", "body", "text/plain");
  4603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4604. EXPECT_EQ(StatusCode::OK_200, res->status);
  4605. EXPECT_EQ("redirected.", res->body);
  4606. EXPECT_EQ("/2", res->location);
  4607. }
  4608. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4609. auto res = cli_.Get("/dir/test.abcde");
  4610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4611. EXPECT_EQ(StatusCode::OK_200, res->status);
  4612. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4613. EXPECT_EQ("abcde", res->body);
  4614. }
  4615. TEST_F(ServerTest, StaticFileRange) {
  4616. auto res =
  4617. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4620. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4621. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4622. EXPECT_EQ(true, res->has_header("Content-Range"));
  4623. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4624. EXPECT_EQ(std::string("cd"), res->body);
  4625. }
  4626. TEST_F(ServerTest, StaticFileRanges) {
  4627. auto res = cli_.Get("/dir/test.abcde",
  4628. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4631. EXPECT_TRUE(
  4632. res->get_header_value("Content-Type")
  4633. .find(
  4634. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4635. 0);
  4636. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4637. }
  4638. TEST_F(ServerTest, StaticFileRangeHead) {
  4639. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4641. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4642. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4643. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4644. EXPECT_EQ(true, res->has_header("Content-Range"));
  4645. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4646. }
  4647. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4648. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4652. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4653. EXPECT_EQ(true, res->has_header("Content-Range"));
  4654. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4655. res->get_header_value("Content-Range"));
  4656. EXPECT_EQ("LAST\n", res->body);
  4657. }
  4658. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4659. auto res =
  4660. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4662. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4663. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4664. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4665. EXPECT_EQ(true, res->has_header("Content-Range"));
  4666. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4667. }
  4668. TEST_F(ServerTest, StaticFileBigFile) {
  4669. auto res = cli_.Get("/dir/1MB.txt");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. EXPECT_EQ(StatusCode::OK_200, res->status);
  4672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4673. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4674. }
  4675. TEST_F(ServerTest, InvalidBaseDirMount) {
  4676. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4677. }
  4678. TEST_F(ServerTest, Binary) {
  4679. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4680. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4681. "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. res = cli_.Put("/binary", binary.data(), binary.size(),
  4686. "application/octet-stream");
  4687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4688. ASSERT_EQ(StatusCode::OK_200, res->status);
  4689. ASSERT_EQ(4U, res->body.size());
  4690. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4691. "application/octet-stream");
  4692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4693. ASSERT_EQ(StatusCode::OK_200, res->status);
  4694. ASSERT_EQ(4U, res->body.size());
  4695. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4696. "application/octet-stream");
  4697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4698. ASSERT_EQ(StatusCode::OK_200, res->status);
  4699. ASSERT_EQ(4U, res->body.size());
  4700. }
  4701. TEST_F(ServerTest, BinaryString) {
  4702. auto binary = std::string("\x00\x01\x02\x03", 4);
  4703. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4705. ASSERT_EQ(StatusCode::OK_200, res->status);
  4706. ASSERT_EQ(4U, res->body.size());
  4707. res = cli_.Put("/binary", binary, "application/octet-stream");
  4708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4709. ASSERT_EQ(StatusCode::OK_200, res->status);
  4710. ASSERT_EQ(4U, res->body.size());
  4711. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4713. ASSERT_EQ(StatusCode::OK_200, res->status);
  4714. ASSERT_EQ(4U, res->body.size());
  4715. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4717. ASSERT_EQ(StatusCode::OK_200, res->status);
  4718. ASSERT_EQ(4U, res->body.size());
  4719. }
  4720. TEST_F(ServerTest, EmptyRequest) {
  4721. auto res = cli_.Get("");
  4722. ASSERT_TRUE(!res);
  4723. EXPECT_EQ(Error::Connection, res.error());
  4724. }
  4725. TEST_F(ServerTest, LongRequest) {
  4726. std::string request;
  4727. for (size_t i = 0; i < 545; i++) {
  4728. request += "/TooLongRequest";
  4729. }
  4730. request += "OK";
  4731. auto res = cli_.Get(request.c_str());
  4732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4733. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4734. }
  4735. TEST_F(ServerTest, TooLongRequest) {
  4736. std::string request;
  4737. for (size_t i = 0; i < 546; i++) {
  4738. request += "/TooLongRequest";
  4739. }
  4740. request += "_NG";
  4741. auto start = std::chrono::high_resolution_clock::now();
  4742. cli_.set_keep_alive(true);
  4743. auto res = cli_.Get(request.c_str());
  4744. auto end = std::chrono::high_resolution_clock::now();
  4745. auto elapsed =
  4746. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4747. .count();
  4748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4749. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4750. EXPECT_LE(elapsed, 1000);
  4751. EXPECT_EQ("close", res->get_header_value("Connection"));
  4752. EXPECT_FALSE(cli_.is_socket_open());
  4753. }
  4754. TEST_F(ServerTest, AlmostTooLongRequest) {
  4755. // test for #2046 - URI length check shouldn't include other content on req
  4756. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4757. // leading /, space, HTTP/1.1)
  4758. std::string request =
  4759. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4760. auto res = cli_.Get(request.c_str());
  4761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4762. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4763. }
  4764. TEST_F(ServerTest, LongHeader) {
  4765. Request req;
  4766. req.method = "GET";
  4767. req.path = "/hi";
  4768. std::string host_and_port;
  4769. host_and_port += HOST;
  4770. host_and_port += ":";
  4771. host_and_port += std::to_string(PORT);
  4772. req.headers.emplace("Host", host_and_port.c_str());
  4773. req.headers.emplace("Accept", "*/*");
  4774. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4775. req.headers.emplace(
  4776. "Header-Name",
  4777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4805. "@@@@@@@@@@@@@@@@");
  4806. auto res = std::make_shared<Response>();
  4807. auto error = Error::Success;
  4808. auto ret = cli_.send(req, *res, error);
  4809. ASSERT_TRUE(ret);
  4810. EXPECT_EQ(StatusCode::OK_200, res->status);
  4811. }
  4812. TEST_F(ServerTest, LongQueryValue) {
  4813. auto start = std::chrono::high_resolution_clock::now();
  4814. cli_.set_keep_alive(true);
  4815. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4816. auto end = std::chrono::high_resolution_clock::now();
  4817. auto elapsed =
  4818. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4819. .count();
  4820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4821. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4822. EXPECT_LE(elapsed, 1000);
  4823. EXPECT_EQ("close", res->get_header_value("Connection"));
  4824. EXPECT_FALSE(cli_.is_socket_open());
  4825. }
  4826. TEST_F(ServerTest, TooLongQueryValue) {
  4827. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4828. ASSERT_FALSE(res);
  4829. EXPECT_EQ(Error::Read, res.error());
  4830. }
  4831. TEST_F(ServerTest, TooLongHeader) {
  4832. Request req;
  4833. req.method = "GET";
  4834. req.path = "/hi";
  4835. std::string host_and_port;
  4836. host_and_port += HOST;
  4837. host_and_port += ":";
  4838. host_and_port += std::to_string(PORT);
  4839. req.headers.emplace("Host", host_and_port.c_str());
  4840. req.headers.emplace("Accept", "*/*");
  4841. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4842. req.headers.emplace(
  4843. "Header-Name",
  4844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4872. "@@@@@@@@@@@@@@@@@");
  4873. auto res = std::make_shared<Response>();
  4874. auto error = Error::Success;
  4875. auto ret = cli_.send(req, *res, error);
  4876. ASSERT_TRUE(ret);
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. }
  4879. TEST_F(ServerTest, HeaderCountAtLimit) {
  4880. // Test with headers just under the 100 limit
  4881. httplib::Headers headers;
  4882. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4883. // This should keep us just under the 100 header limit
  4884. for (int i = 0; i < 95; i++) {
  4885. std::string name = "X-Test-Header-" + std::to_string(i);
  4886. std::string value = "value" + std::to_string(i);
  4887. headers.emplace(name, value);
  4888. }
  4889. // This should work fine as we're under the limit
  4890. auto res = cli_.Get("/hi", headers);
  4891. EXPECT_TRUE(res);
  4892. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4893. }
  4894. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4895. // Test with many headers to exceed the 100 limit
  4896. httplib::Headers headers;
  4897. // Add 150 headers to definitely exceed the 100 limit
  4898. for (int i = 0; i < 150; i++) {
  4899. std::string name = "X-Test-Header-" + std::to_string(i);
  4900. std::string value = "value" + std::to_string(i);
  4901. headers.emplace(name, value);
  4902. }
  4903. // This should fail due to exceeding header count limit
  4904. cli_.set_keep_alive(true);
  4905. auto res = cli_.Get("/hi", headers);
  4906. // The server should respond with 400 Bad Request
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4909. EXPECT_EQ("close", res->get_header_value("Connection"));
  4910. EXPECT_FALSE(cli_.is_socket_open());
  4911. }
  4912. TEST_F(ServerTest, PercentEncoding) {
  4913. auto res = cli_.Get("/e%6edwith%");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. EXPECT_EQ(StatusCode::OK_200, res->status);
  4916. }
  4917. TEST_F(ServerTest, PercentEncodingUnicode) {
  4918. auto res = cli_.Get("/e%u006edwith%");
  4919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4920. EXPECT_EQ(StatusCode::OK_200, res->status);
  4921. }
  4922. TEST_F(ServerTest, InvalidPercentEncoding) {
  4923. auto res = cli_.Get("/%endwith%");
  4924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4926. }
  4927. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4928. auto res = cli_.Get("/%uendwith%");
  4929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4931. }
  4932. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4933. auto res = cli_.Get("/hello?aaa=bbb%");
  4934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4936. }
  4937. TEST_F(ServerTest, PlusSignEncoding) {
  4938. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ("a +b", res->body);
  4942. }
  4943. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4944. // This test simulates a potential DoS attack using many headers
  4945. // to verify our security fix prevents memory exhaustion
  4946. httplib::Headers attack_headers;
  4947. // Attempt to add many headers like an attacker would (200 headers to far
  4948. // exceed limit)
  4949. for (int i = 0; i < 200; i++) {
  4950. std::string name = "X-Attack-Header-" + std::to_string(i);
  4951. std::string value = "attack_payload_" + std::to_string(i);
  4952. attack_headers.emplace(name, value);
  4953. }
  4954. // Try to POST with excessive headers
  4955. cli_.set_keep_alive(true);
  4956. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4957. // Should either fail or return 400 Bad Request due to security limit
  4958. if (res) {
  4959. // If we get a response, it should be 400 Bad Request
  4960. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4961. EXPECT_EQ("close", res->get_header_value("Connection"));
  4962. }
  4963. EXPECT_FALSE(cli_.is_socket_open());
  4964. }
  4965. TEST_F(ServerTest, MultipartFormData) {
  4966. UploadFormDataItems items = {
  4967. {"text1", "text default", "", ""},
  4968. {"text2", "aωb", "", ""},
  4969. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4970. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4971. {"file3", "", "", "application/octet-stream"},
  4972. {"file4", "", "", " application/json tmp-string "}};
  4973. auto res = cli_.Post("/multipart", items);
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. }
  4977. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4978. UploadFormDataItems items = {
  4979. {"text", "default text", "", ""},
  4980. {"multi_text1", "aaaaa", "", ""},
  4981. {"multi_text1", "bbbbb", "", ""},
  4982. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4983. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4984. "application/json"},
  4985. };
  4986. auto res = cli_.Post("/multipart/multi_file_values", items);
  4987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4988. EXPECT_EQ(StatusCode::OK_200, res->status);
  4989. }
  4990. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4991. auto res = cli_.Get("/hi");
  4992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4993. EXPECT_EQ(StatusCode::OK_200, res->status);
  4994. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4995. EXPECT_EQ("Hello World!", res->body);
  4996. }
  4997. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4998. Request req;
  4999. req.method = "POST";
  5000. req.path = "/chunked";
  5001. std::string host_and_port;
  5002. host_and_port += HOST;
  5003. host_and_port += ":";
  5004. host_and_port += std::to_string(PORT);
  5005. req.headers.emplace("Host", host_and_port.c_str());
  5006. req.headers.emplace("Accept", "*/*");
  5007. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5008. req.headers.emplace("Content-Type", "text/plain");
  5009. req.headers.emplace("Content-Length", "0");
  5010. req.headers.emplace(
  5011. "Transfer-Encoding",
  5012. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5013. // Client does not chunk, so make a chunked body manually.
  5014. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5015. auto res = std::make_shared<Response>();
  5016. auto error = Error::Success;
  5017. auto ret = cli_.send(req, *res, error);
  5018. ASSERT_TRUE(ret);
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. }
  5021. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5022. // rather than treat them as valid lengths.
  5023. template <typename ClientT>
  5024. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5025. Request req;
  5026. req.method = "POST";
  5027. req.path = "/chunked";
  5028. std::string host_and_port;
  5029. host_and_port += HOST;
  5030. host_and_port += ":";
  5031. host_and_port += std::to_string(PORT);
  5032. req.headers.emplace("Host", host_and_port.c_str());
  5033. req.headers.emplace("Content-Length", "0");
  5034. req.headers.emplace("Transfer-Encoding", "chunked");
  5035. req.body = body;
  5036. auto res = std::make_shared<Response>();
  5037. auto error = Error::Success;
  5038. ASSERT_TRUE(cli.send(req, *res, error));
  5039. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5040. }
  5041. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5042. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5043. }
  5044. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5045. expect_chunked_body_rejected(
  5046. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5047. }
  5048. TEST_F(ServerTest, GetStreamed2) {
  5049. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5052. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5053. EXPECT_EQ(true, res->has_header("Content-Range"));
  5054. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5055. EXPECT_EQ(std::string("ab"), res->body);
  5056. }
  5057. TEST_F(ServerTest, GetStreamed) {
  5058. auto res = cli_.Get("/streamed");
  5059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5060. EXPECT_EQ(StatusCode::OK_200, res->status);
  5061. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5062. EXPECT_EQ(std::string("aaabbb"), res->body);
  5063. }
  5064. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5065. auto res = cli_.Get("/streamed-without-length",
  5066. Headers{make_range_header({{0, -1}})});
  5067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. EXPECT_EQ(false, res->has_header("Content-Length"));
  5070. EXPECT_EQ(false, res->has_header("Content-Range"));
  5071. EXPECT_EQ(std::string("abcdefg"), res->body);
  5072. }
  5073. TEST_F(ServerTest, GetStreamedWithRange1) {
  5074. auto res =
  5075. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5078. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5079. EXPECT_EQ(true, res->has_header("Content-Range"));
  5080. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5081. EXPECT_EQ(std::string("def"), res->body);
  5082. }
  5083. TEST_F(ServerTest, GetStreamedWithRange2) {
  5084. auto res =
  5085. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5087. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5088. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5089. EXPECT_EQ(true, res->has_header("Content-Range"));
  5090. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5091. EXPECT_EQ(std::string("bcdefg"), res->body);
  5092. }
  5093. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5094. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5097. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5098. EXPECT_EQ(true, res->has_header("Content-Range"));
  5099. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5100. EXPECT_EQ(std::string("efg"), res->body);
  5101. }
  5102. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5103. auto res =
  5104. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5106. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5107. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5108. EXPECT_EQ(false, res->has_header("Content-Range"));
  5109. EXPECT_EQ(0U, res->body.size());
  5110. }
  5111. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5112. auto res =
  5113. cli_.Get("/streamed-with-range",
  5114. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5115. "92233720368547758079223372036854775807"}});
  5116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5117. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5118. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5119. EXPECT_EQ(false, res->has_header("Content-Range"));
  5120. EXPECT_EQ(0U, res->body.size());
  5121. }
  5122. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5123. auto res = cli_.Get(
  5124. "/with-range",
  5125. Headers{{"Range",
  5126. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5127. {"Accept-Encoding", ""}});
  5128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5129. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5130. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5131. EXPECT_EQ(true, res->has_header("Content-Range"));
  5132. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5133. EXPECT_EQ(std::string("abcdefg"), res->body);
  5134. }
  5135. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5136. auto res = cli_.Get("/with-range", Headers{
  5137. {"Range", "bytes=0-"},
  5138. {"Accept-Encoding", ""},
  5139. });
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5142. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5143. EXPECT_EQ(true, res->has_header("Content-Range"));
  5144. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5145. EXPECT_EQ(std::string("abcdefg"), res->body);
  5146. }
  5147. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5148. auto res = cli_.Get("/streamed-with-range",
  5149. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5151. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5152. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5153. EXPECT_EQ(false, res->has_header("Content-Range"));
  5154. EXPECT_EQ(267U, res->body.size());
  5155. // Check that both range contents are present
  5156. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5157. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5158. // Check that Content-Range headers are present for both ranges
  5159. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5160. std::string::npos);
  5161. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5162. std::string::npos);
  5163. }
  5164. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5165. Ranges ranges;
  5166. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5167. ranges.emplace_back(0, -1);
  5168. }
  5169. auto res = cli_.Get("/streamed-with-range?error",
  5170. Headers{{make_range_header(ranges)}});
  5171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5172. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5173. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5174. EXPECT_EQ(false, res->has_header("Content-Range"));
  5175. EXPECT_EQ(0U, res->body.size());
  5176. }
  5177. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5178. auto res = cli_.Get("/streamed-with-range",
  5179. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5181. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5182. EXPECT_EQ(5U, res->body.size());
  5183. // Check that overlapping ranges are coalesced into a single range
  5184. EXPECT_EQ("bcdef", res->body);
  5185. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5186. // Should be single range, not multipart
  5187. EXPECT_TRUE(res->has_header("Content-Range"));
  5188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5189. }
  5190. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5191. auto res = cli_.Get("/streamed-with-range",
  5192. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5194. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5195. EXPECT_EQ(268U, res->body.size());
  5196. // Check that both range contents are present
  5197. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5198. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5199. // Check that Content-Range headers are present for both ranges
  5200. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5201. std::string::npos);
  5202. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5203. std::string::npos);
  5204. }
  5205. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5206. auto res = cli_.Get("/streamed-with-range",
  5207. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5210. EXPECT_EQ(269U, res->body.size());
  5211. // Check that both duplicate range contents are present
  5212. size_t first_abc = res->body.find("abc\r\n");
  5213. EXPECT_TRUE(first_abc != std::string::npos);
  5214. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5215. EXPECT_TRUE(second_abc != std::string::npos);
  5216. // Check that Content-Range headers are present for both ranges
  5217. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5218. EXPECT_TRUE(first_range != std::string::npos);
  5219. size_t second_range =
  5220. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5221. EXPECT_TRUE(second_range != std::string::npos);
  5222. }
  5223. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5224. auto res =
  5225. cli_.Get("/streamed-with-range?error",
  5226. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5228. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5229. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5230. EXPECT_EQ(false, res->has_header("Content-Range"));
  5231. EXPECT_EQ(0U, res->body.size());
  5232. }
  5233. TEST_F(ServerTest, GetStreamedEndless) {
  5234. uint64_t offset = 0;
  5235. auto res = cli_.Get("/streamed-cancel",
  5236. [&](const char * /*data*/, uint64_t data_length) {
  5237. if (offset < 100) {
  5238. offset += data_length;
  5239. return true;
  5240. }
  5241. return false;
  5242. });
  5243. ASSERT_TRUE(!res);
  5244. EXPECT_EQ(Error::Canceled, res.error());
  5245. }
  5246. TEST_F(ServerTest, ClientStop) {
  5247. std::atomic_size_t count{4};
  5248. std::vector<std::thread> threads;
  5249. for (auto i = count.load(); i != 0; --i) {
  5250. threads.emplace_back([&]() {
  5251. auto res = cli_.Get("/streamed-cancel",
  5252. [&](const char *, uint64_t) { return true; });
  5253. --count;
  5254. ASSERT_TRUE(!res);
  5255. EXPECT_TRUE(res.error() == Error::Canceled ||
  5256. res.error() == Error::Read || res.error() == Error::Write);
  5257. });
  5258. }
  5259. std::this_thread::sleep_for(std::chrono::seconds(2));
  5260. while (count != 0) {
  5261. cli_.stop();
  5262. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5263. }
  5264. for (auto &t : threads) {
  5265. t.join();
  5266. }
  5267. }
  5268. TEST_F(ServerTest, GetWithRange1) {
  5269. auto res = cli_.Get("/with-range", Headers{
  5270. make_range_header({{3, 5}}),
  5271. {"Accept-Encoding", ""},
  5272. });
  5273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5274. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5275. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5276. EXPECT_EQ(true, res->has_header("Content-Range"));
  5277. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5278. EXPECT_EQ(std::string("def"), res->body);
  5279. }
  5280. TEST_F(ServerTest, GetWithRange2) {
  5281. auto res = cli_.Get("/with-range", Headers{
  5282. make_range_header({{1, -1}}),
  5283. {"Accept-Encoding", ""},
  5284. });
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5287. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5288. EXPECT_EQ(true, res->has_header("Content-Range"));
  5289. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5290. EXPECT_EQ(std::string("bcdefg"), res->body);
  5291. }
  5292. TEST_F(ServerTest, GetWithRange3) {
  5293. auto res = cli_.Get("/with-range", Headers{
  5294. make_range_header({{0, 0}}),
  5295. {"Accept-Encoding", ""},
  5296. });
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5299. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5300. EXPECT_EQ(true, res->has_header("Content-Range"));
  5301. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5302. EXPECT_EQ(std::string("a"), res->body);
  5303. }
  5304. TEST_F(ServerTest, GetWithRange4) {
  5305. auto res = cli_.Get("/with-range", Headers{
  5306. make_range_header({{-1, 2}}),
  5307. {"Accept-Encoding", ""},
  5308. });
  5309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5310. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5311. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5312. EXPECT_EQ(true, res->has_header("Content-Range"));
  5313. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5314. EXPECT_EQ(std::string("fg"), res->body);
  5315. }
  5316. TEST_F(ServerTest, GetWithRange5) {
  5317. auto res = cli_.Get("/with-range", Headers{
  5318. make_range_header({{0, 5}}),
  5319. {"Accept-Encoding", ""},
  5320. });
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5323. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5324. EXPECT_EQ(true, res->has_header("Content-Range"));
  5325. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5326. EXPECT_EQ(std::string("abcdef"), res->body);
  5327. }
  5328. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5329. auto res =
  5330. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5333. }
  5334. TEST_F(ServerTest, GetWithRangeMultipart) {
  5335. auto res =
  5336. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5339. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ(false, res->has_header("Content-Range"));
  5341. EXPECT_EQ(267U, res->body.size());
  5342. }
  5343. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5344. auto res = cli_.Get("/with-range",
  5345. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5348. }
  5349. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5350. auto res = cli_.Get("/with-range-customized-response",
  5351. Headers{{make_range_header({{1, 2}})}});
  5352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5353. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5354. EXPECT_EQ(true, res->has_header("Content-Length"));
  5355. EXPECT_EQ(false, res->has_header("Content-Range"));
  5356. EXPECT_EQ(JSON_DATA, res->body);
  5357. }
  5358. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5359. auto res = cli_.Get("/with-range-customized-response",
  5360. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5363. EXPECT_EQ(true, res->has_header("Content-Length"));
  5364. EXPECT_EQ(false, res->has_header("Content-Range"));
  5365. EXPECT_EQ(JSON_DATA, res->body);
  5366. }
  5367. TEST_F(ServerTest, Issue1772) {
  5368. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5371. }
  5372. TEST_F(ServerTest, Issue609) {
  5373. auto res = cli_.Delete("/issue609");
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ(std::string("ok"), res->body);
  5377. }
  5378. TEST_F(ServerTest, GetStreamedChunked) {
  5379. auto res = cli_.Get("/streamed-chunked");
  5380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. EXPECT_EQ(std::string("123456789"), res->body);
  5383. }
  5384. TEST_F(ServerTest, GetStreamedChunked2) {
  5385. auto res = cli_.Get("/streamed-chunked2");
  5386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5387. EXPECT_EQ(StatusCode::OK_200, res->status);
  5388. EXPECT_EQ(std::string("123456789"), res->body);
  5389. }
  5390. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5391. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5393. EXPECT_EQ(StatusCode::OK_200, res->status);
  5394. EXPECT_EQ(std::string("123456789"), res->body);
  5395. EXPECT_TRUE(res->has_header("Trailer"));
  5396. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5397. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5398. // Trailers are now stored separately from headers (security fix)
  5399. EXPECT_EQ(2U, res->trailers.size());
  5400. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5401. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5402. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5403. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5404. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5405. // Verify trailers are NOT in headers (security verification)
  5406. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5407. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5408. }
  5409. TEST_F(ServerTest, LargeChunkedPost) {
  5410. Request req;
  5411. req.method = "POST";
  5412. req.path = "/large-chunked";
  5413. std::string host_and_port;
  5414. host_and_port += HOST;
  5415. host_and_port += ":";
  5416. host_and_port += std::to_string(PORT);
  5417. req.headers.emplace("Host", host_and_port.c_str());
  5418. req.headers.emplace("Accept", "*/*");
  5419. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5420. req.headers.emplace("Content-Type", "text/plain");
  5421. req.headers.emplace("Content-Length", "0");
  5422. req.headers.emplace("Transfer-Encoding", "chunked");
  5423. std::string long_string(30 * 1024u, 'a');
  5424. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5425. // Attempt to make a large enough post to exceed OS buffers, to test that
  5426. // the server handles short reads if the full chunk data isn't available.
  5427. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5428. auto res = std::make_shared<Response>();
  5429. auto error = Error::Success;
  5430. auto ret = cli_.send(req, *res, error);
  5431. ASSERT_TRUE(ret);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5435. auto res = cli_.Get("/remote_addr");
  5436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5439. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5440. }
  5441. TEST_F(ServerTest, GetMethodLocalAddr) {
  5442. auto res = cli_.Get("/local_addr");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::OK_200, res->status);
  5445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5446. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5447. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5448. }
  5449. TEST_F(ServerTest, HTTPResponseSplitting) {
  5450. auto res = cli_.Get("/http_response_splitting");
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. EXPECT_EQ(StatusCode::OK_200, res->status);
  5453. }
  5454. TEST_F(ServerTest, SlowRequest) {
  5455. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5456. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5457. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5458. }
  5459. #if 0
  5460. TEST_F(ServerTest, SlowPost) {
  5461. char buffer[64 * 1024];
  5462. memset(buffer, 0x42, sizeof(buffer));
  5463. auto res = cli_.Post(
  5464. "/slowpost", 64 * 1024 * 1024,
  5465. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5466. auto ret = sink.write(buffer, sizeof(buffer));
  5467. EXPECT_TRUE(ret);
  5468. return true;
  5469. },
  5470. "text/plain");
  5471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5472. EXPECT_EQ(StatusCode::OK_200, res->status);
  5473. }
  5474. TEST_F(ServerTest, SlowPostFail) {
  5475. char buffer[64 * 1024];
  5476. memset(buffer, 0x42, sizeof(buffer));
  5477. cli_.set_write_timeout(std::chrono::seconds(0));
  5478. auto res = cli_.Post(
  5479. "/slowpost", 64 * 1024 * 1024,
  5480. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5481. sink.write(buffer, sizeof(buffer));
  5482. return true;
  5483. },
  5484. "text/plain");
  5485. ASSERT_TRUE(!res);
  5486. EXPECT_EQ(Error::Write, res.error());
  5487. }
  5488. #endif
  5489. TEST_F(ServerTest, Put) {
  5490. auto res = cli_.Put("/put", "PUT", "text/plain");
  5491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("PUT", res->body);
  5494. }
  5495. TEST_F(ServerTest, PutWithContentProvider) {
  5496. auto res = cli_.Put(
  5497. "/put", 3,
  5498. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5499. sink.os << "PUT";
  5500. return true;
  5501. },
  5502. "text/plain");
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. EXPECT_EQ("PUT", res->body);
  5506. }
  5507. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5508. auto res = cli_.Post(
  5509. "/post", 42,
  5510. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5511. return false;
  5512. },
  5513. "text/plain");
  5514. ASSERT_TRUE(!res);
  5515. EXPECT_EQ(Error::Canceled, res.error());
  5516. }
  5517. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5518. auto res = cli_.Put(
  5519. "/put",
  5520. [](size_t /*offset*/, DataSink &sink) {
  5521. sink.os << "PUT";
  5522. sink.done();
  5523. return true;
  5524. },
  5525. "text/plain");
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("PUT", res->body);
  5529. }
  5530. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5531. auto res = cli_.Post(
  5532. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5533. "text/plain");
  5534. ASSERT_TRUE(!res);
  5535. EXPECT_EQ(Error::Canceled, res.error());
  5536. }
  5537. TEST_F(ServerTest, PostLoopBack) {
  5538. std::string body;
  5539. auto res = cli_.Post(
  5540. "/post-loopback", 9,
  5541. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5542. EXPECT_EQ(9u, length);
  5543. sink.write("123", 3);
  5544. sink.write("456", 3);
  5545. sink.write("789", 3);
  5546. return true;
  5547. },
  5548. "text/plain",
  5549. [&body](const char *data, size_t data_length) {
  5550. body.append(data, data_length);
  5551. return true;
  5552. });
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. EXPECT_EQ("123456789", body);
  5556. }
  5557. TEST_F(ServerTest, PutLoopBack) {
  5558. std::string body;
  5559. auto res = cli_.Put(
  5560. "/put-loopback", 9,
  5561. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5562. EXPECT_EQ(9u, length);
  5563. sink.write("123", 3);
  5564. sink.write("456", 3);
  5565. sink.write("789", 3);
  5566. return true;
  5567. },
  5568. "text/plain",
  5569. [&body](const char *data, size_t data_length) {
  5570. body.append(data, data_length);
  5571. return true;
  5572. });
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ(StatusCode::OK_200, res->status);
  5575. EXPECT_EQ("123456789", body);
  5576. }
  5577. TEST_F(ServerTest, PatchLoopBack) {
  5578. std::string body;
  5579. auto res = cli_.Patch(
  5580. "/patch-loopback", 9,
  5581. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5582. EXPECT_EQ(9u, length);
  5583. sink.write("123", 3);
  5584. sink.write("456", 3);
  5585. sink.write("789", 3);
  5586. return true;
  5587. },
  5588. "text/plain",
  5589. [&body](const char *data, size_t data_length) {
  5590. body.append(data, data_length);
  5591. return true;
  5592. });
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ(StatusCode::OK_200, res->status);
  5595. EXPECT_EQ("123456789", body);
  5596. }
  5597. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5598. std::string body;
  5599. auto res = cli_.Post(
  5600. "/post-loopback",
  5601. [](size_t /*offset*/, DataSink &sink) {
  5602. sink.write("123", 3);
  5603. sink.write("456", 3);
  5604. sink.write("789", 3);
  5605. sink.done();
  5606. return true;
  5607. },
  5608. "text/plain",
  5609. [&body](const char *data, size_t data_length) {
  5610. body.append(data, data_length);
  5611. return true;
  5612. });
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. EXPECT_EQ(StatusCode::OK_200, res->status);
  5615. EXPECT_EQ("123456789", body);
  5616. }
  5617. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5618. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5619. cli_.set_compress(true);
  5620. auto res = cli_.Put(
  5621. "/put", 3,
  5622. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5623. sink.os << "PUT";
  5624. return true;
  5625. },
  5626. "text/plain");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. EXPECT_EQ(StatusCode::OK_200, res->status);
  5629. EXPECT_EQ("PUT", res->body);
  5630. }
  5631. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5632. cli_.set_compress(true);
  5633. auto res = cli_.Post(
  5634. "/post", 42,
  5635. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5636. return false;
  5637. },
  5638. "text/plain");
  5639. ASSERT_TRUE(!res);
  5640. EXPECT_EQ(Error::Canceled, res.error());
  5641. }
  5642. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5643. cli_.set_compress(true);
  5644. auto res = cli_.Put(
  5645. "/put",
  5646. [](size_t /*offset*/, DataSink &sink) {
  5647. sink.os << "PUT";
  5648. sink.done();
  5649. return true;
  5650. },
  5651. "text/plain");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. EXPECT_EQ(StatusCode::OK_200, res->status);
  5654. EXPECT_EQ("PUT", res->body);
  5655. }
  5656. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5657. cli_.set_compress(true);
  5658. auto res = cli_.Post(
  5659. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5660. "text/plain");
  5661. ASSERT_TRUE(!res);
  5662. EXPECT_EQ(Error::Canceled, res.error());
  5663. }
  5664. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5665. cli_.set_compress(true);
  5666. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. EXPECT_EQ(LARGE_DATA, res->body);
  5670. }
  5671. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5672. #ifdef CPPHTTPLIB_SSL_ENABLED
  5673. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5674. Client cli(s.c_str());
  5675. cli.enable_server_certificate_verification(false);
  5676. #else
  5677. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5678. Client cli(s.c_str());
  5679. #endif
  5680. cli.set_compress(true);
  5681. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5683. EXPECT_EQ(StatusCode::OK_200, res->status);
  5684. EXPECT_EQ(LARGE_DATA, res->body);
  5685. // The compressed size should be less than a 10th of the original. May vary
  5686. // depending on the zlib library.
  5687. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5688. static_cast<uint64_t>(10 * 1024 * 1024));
  5689. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5690. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5691. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5692. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5693. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5694. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5695. #endif
  5696. }
  5697. TEST_F(ServerTest, PutContentWithDeflate) {
  5698. cli_.set_compress(false);
  5699. Headers headers;
  5700. headers.emplace("Content-Encoding", "deflate");
  5701. // PUT in deflate format:
  5702. auto res = cli_.Put("/put", headers,
  5703. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ("PUT", res->body);
  5707. }
  5708. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5709. Headers headers;
  5710. headers.emplace("Accept-Encoding", "gzip, deflate");
  5711. auto res = cli_.Get("/streamed-chunked", headers);
  5712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5713. EXPECT_EQ(StatusCode::OK_200, res->status);
  5714. EXPECT_EQ(std::string("123456789"), res->body);
  5715. }
  5716. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5717. Headers headers;
  5718. headers.emplace("Accept-Encoding", "gzip, deflate");
  5719. auto res = cli_.Get("/streamed-chunked2", headers);
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. EXPECT_EQ(StatusCode::OK_200, res->status);
  5722. EXPECT_EQ(std::string("123456789"), res->body);
  5723. }
  5724. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5725. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. }
  5729. TEST(GzipDecompressor, ChunkedDecompression) {
  5730. std::string data;
  5731. for (size_t i = 0; i < 32 * 1024; ++i) {
  5732. data.push_back(static_cast<char>('a' + i % 26));
  5733. }
  5734. std::string compressed_data;
  5735. {
  5736. httplib::detail::gzip_compressor compressor;
  5737. bool result = compressor.compress(
  5738. data.data(), data.size(),
  5739. /*last=*/true,
  5740. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5741. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5742. compressed_data_size);
  5743. return true;
  5744. });
  5745. ASSERT_TRUE(result);
  5746. }
  5747. std::string decompressed_data;
  5748. {
  5749. httplib::detail::gzip_decompressor decompressor;
  5750. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5751. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5752. size_t chunk_size = 130;
  5753. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5754. chunk_begin += chunk_size) {
  5755. size_t current_chunk_size =
  5756. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5757. bool result = decompressor.decompress(
  5758. compressed_data.data() + chunk_begin, current_chunk_size,
  5759. [&](const char *decompressed_data_chunk,
  5760. size_t decompressed_data_chunk_size) {
  5761. decompressed_data.insert(decompressed_data.size(),
  5762. decompressed_data_chunk,
  5763. decompressed_data_chunk_size);
  5764. return true;
  5765. });
  5766. ASSERT_TRUE(result);
  5767. }
  5768. }
  5769. ASSERT_EQ(data, decompressed_data);
  5770. }
  5771. TEST(GzipDecompressor, DeflateDecompression) {
  5772. std::string original_text = "Raw deflate without gzip";
  5773. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5774. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5775. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5776. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5777. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5778. std::string decompressed_data;
  5779. {
  5780. httplib::detail::gzip_decompressor decompressor;
  5781. bool result = decompressor.decompress(
  5782. compressed_data.data(), compressed_data.size(),
  5783. [&](const char *decompressed_data_chunk,
  5784. size_t decompressed_data_chunk_size) {
  5785. decompressed_data.insert(decompressed_data.size(),
  5786. decompressed_data_chunk,
  5787. decompressed_data_chunk_size);
  5788. return true;
  5789. });
  5790. ASSERT_TRUE(result);
  5791. }
  5792. ASSERT_EQ(original_text, decompressed_data);
  5793. }
  5794. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5795. std::string original_text = "Raw deflate without gzip";
  5796. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5797. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5798. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5799. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5800. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5801. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5802. std::string decompressed_data;
  5803. {
  5804. httplib::detail::gzip_decompressor decompressor;
  5805. bool result = decompressor.decompress(
  5806. compressed_data.data(), compressed_data.size(),
  5807. [&](const char *decompressed_data_chunk,
  5808. size_t decompressed_data_chunk_size) {
  5809. decompressed_data.insert(decompressed_data.size(),
  5810. decompressed_data_chunk,
  5811. decompressed_data_chunk_size);
  5812. return true;
  5813. });
  5814. ASSERT_TRUE(result);
  5815. }
  5816. ASSERT_EQ(original_text, decompressed_data);
  5817. }
  5818. #endif
  5819. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5820. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5821. Headers headers;
  5822. headers.emplace("Accept-Encoding", "br");
  5823. auto res = cli_.Get("/streamed-chunked", headers);
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::OK_200, res->status);
  5826. EXPECT_EQ(std::string("123456789"), res->body);
  5827. }
  5828. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5829. Headers headers;
  5830. headers.emplace("Accept-Encoding", "br");
  5831. auto res = cli_.Get("/streamed-chunked2", headers);
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::OK_200, res->status);
  5834. EXPECT_EQ(std::string("123456789"), res->body);
  5835. }
  5836. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5837. cli_.set_compress(true);
  5838. auto res = cli_.Put(
  5839. "/put", 3,
  5840. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5841. sink.os << "PUT";
  5842. return true;
  5843. },
  5844. "text/plain");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. EXPECT_EQ(StatusCode::OK_200, res->status);
  5847. EXPECT_EQ("PUT", res->body);
  5848. }
  5849. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5850. cli_.set_compress(true);
  5851. auto res = cli_.Put(
  5852. "/put",
  5853. [](size_t /*offset*/, DataSink &sink) {
  5854. sink.os << "PUT";
  5855. sink.done();
  5856. return true;
  5857. },
  5858. "text/plain");
  5859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5860. EXPECT_EQ(StatusCode::OK_200, res->status);
  5861. EXPECT_EQ("PUT", res->body);
  5862. }
  5863. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5864. cli_.set_compress(true);
  5865. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5867. EXPECT_EQ(StatusCode::OK_200, res->status);
  5868. EXPECT_EQ(LARGE_DATA, res->body);
  5869. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5870. }
  5871. #endif
  5872. TEST_F(ServerTest, Patch) {
  5873. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5875. EXPECT_EQ(StatusCode::OK_200, res->status);
  5876. EXPECT_EQ("PATCH", res->body);
  5877. }
  5878. TEST_F(ServerTest, Delete) {
  5879. auto res = cli_.Delete("/delete");
  5880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5881. EXPECT_EQ(StatusCode::OK_200, res->status);
  5882. EXPECT_EQ("DELETE", res->body);
  5883. }
  5884. TEST_F(ServerTest, DeleteContentReceiver) {
  5885. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. EXPECT_EQ(StatusCode::OK_200, res->status);
  5888. EXPECT_EQ("content", res->body);
  5889. }
  5890. TEST_F(ServerTest, Options) {
  5891. auto res = cli_.Options("*");
  5892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5893. EXPECT_EQ(StatusCode::OK_200, res->status);
  5894. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5895. EXPECT_TRUE(res->body.empty());
  5896. }
  5897. TEST_F(ServerTest, URL) {
  5898. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. }
  5902. TEST_F(ServerTest, ArrayParam) {
  5903. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5905. EXPECT_EQ(StatusCode::OK_200, res->status);
  5906. }
  5907. TEST_F(ServerTest, ArrayParamValues) {
  5908. auto res =
  5909. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::OK_200, res->status);
  5912. }
  5913. TEST_F(ServerTest, NoMultipleHeaders) {
  5914. Headers headers = {{"Content-Length", "5"}};
  5915. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5916. "text/plain");
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. }
  5920. TEST_F(ServerTest, PostContentReceiver) {
  5921. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. ASSERT_EQ(StatusCode::OK_200, res->status);
  5924. ASSERT_EQ("content", res->body);
  5925. }
  5926. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5927. UploadFormDataItems items = {
  5928. {"text1", "text default", "", ""},
  5929. {"text2", "aωb", "", ""},
  5930. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5931. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5932. {"file3", "", "", "application/octet-stream"},
  5933. };
  5934. auto res = cli_.Post("/content_receiver", items);
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. EXPECT_EQ(StatusCode::OK_200, res->status);
  5937. }
  5938. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5939. UploadFormDataItems items = {
  5940. {"text1", "text default", "", ""},
  5941. {"text2", "aωb", "", ""},
  5942. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5943. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5944. {"file3", "", "", "application/octet-stream"},
  5945. };
  5946. auto boundary = std::string("+++++");
  5947. std::string body;
  5948. for (const auto &item : items) {
  5949. body += "--" + boundary + "\r\n";
  5950. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5951. if (!item.filename.empty()) {
  5952. body += "; filename=\"" + item.filename + "\"";
  5953. }
  5954. body += "\r\n";
  5955. if (!item.content_type.empty()) {
  5956. body += "Content-Type: " + item.content_type + "\r\n";
  5957. }
  5958. body += "\r\n";
  5959. body += item.content + "\r\n";
  5960. }
  5961. body += "--" + boundary + "--\r\n";
  5962. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5963. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5965. EXPECT_EQ(StatusCode::OK_200, res->status);
  5966. }
  5967. TEST(MultipartFormDataTest, FieldEscaping) {
  5968. Server svr;
  5969. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5970. const ContentReader &content_reader) {
  5971. ASSERT_TRUE(req.is_multipart_form_data());
  5972. std::vector<FormData> received;
  5973. content_reader(
  5974. [&](const FormData &file) {
  5975. received.push_back(file);
  5976. return true;
  5977. },
  5978. [&](const char *data, size_t data_length) {
  5979. received.back().content.append(data, data_length);
  5980. return true;
  5981. });
  5982. // '"', CR and LF in names and filenames are escaped following the
  5983. // WHATWG HTML standard, so each part still parses as a single part
  5984. // with no injected headers. Content types get CR/LF escaped too,
  5985. // while '"' (legal there, e.g. quoted charset) is preserved.
  5986. ASSERT_EQ(4U, received.size());
  5987. EXPECT_EQ("na%22me", received[0].name);
  5988. EXPECT_EQ("quoted name", received[0].content);
  5989. EXPECT_EQ("file", received[1].name);
  5990. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5991. received[1].filename);
  5992. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5993. EXPECT_EQ("injected", received[1].content);
  5994. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5995. EXPECT_EQ("my%22file.txt", received[2].filename);
  5996. EXPECT_EQ("cr lf name", received[2].content);
  5997. EXPECT_EQ("typed", received[3].name);
  5998. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5999. received[3].content_type);
  6000. EXPECT_EQ("typed content", received[3].content);
  6001. });
  6002. auto port = svr.bind_to_any_port("localhost");
  6003. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6004. auto se = detail::scope_exit([&] {
  6005. svr.stop();
  6006. t.join();
  6007. ASSERT_FALSE(svr.is_running());
  6008. });
  6009. svr.wait_until_ready();
  6010. Client cli("localhost", port);
  6011. UploadFormDataItems items = {
  6012. {"na\"me", "quoted name", "", ""},
  6013. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6014. "application/octet-stream"},
  6015. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6016. {"typed", "typed content", "",
  6017. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6018. };
  6019. auto res = cli.Post("/post", items);
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. EXPECT_EQ(StatusCode::OK_200, res->status);
  6022. }
  6023. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6024. const UploadFormDataItems items = {
  6025. {"name1", "Content 1", "", ""},
  6026. {"name2", "Content 2", "file2.txt", "text/plain"},
  6027. };
  6028. Server svr;
  6029. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6030. const ContentReader &content_reader) {
  6031. ASSERT_TRUE(req.is_multipart_form_data());
  6032. std::vector<FormData> received;
  6033. content_reader(
  6034. [&](const FormData &file) {
  6035. received.push_back(file);
  6036. return true;
  6037. },
  6038. [&](const char *data, size_t data_length) {
  6039. received.back().content.append(data, data_length);
  6040. return true;
  6041. });
  6042. ASSERT_EQ(2U, received.size());
  6043. EXPECT_EQ("name1", received[0].name);
  6044. EXPECT_EQ("Content 1", received[0].content);
  6045. EXPECT_EQ("name2", received[1].name);
  6046. EXPECT_EQ("Content 2", received[1].content);
  6047. EXPECT_EQ("file2.txt", received[1].filename);
  6048. EXPECT_EQ("text/plain", received[1].content_type);
  6049. });
  6050. auto port = svr.bind_to_any_port("localhost");
  6051. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6052. auto se = detail::scope_exit([&] {
  6053. svr.stop();
  6054. t.join();
  6055. ASSERT_FALSE(svr.is_running());
  6056. });
  6057. svr.wait_until_ready();
  6058. Client cli("localhost", port);
  6059. // Whole-body serialization with a generated boundary
  6060. {
  6061. MultipartFormDataWriter writer;
  6062. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6063. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6064. writer.content_type());
  6065. auto body = writer.serialize(items);
  6066. EXPECT_EQ(body.size(), writer.content_length(items));
  6067. auto res = cli.Post("/post", body, writer.content_type());
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::OK_200, res->status);
  6070. }
  6071. // Per-part framing with a custom boundary via a content provider
  6072. {
  6073. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6074. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6075. MultipartFormDataWriter writer("custom-boundary_123");
  6076. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6077. std::string body;
  6078. for (const auto &item : items) {
  6079. body += writer.item_begin(item);
  6080. body += item.content;
  6081. body += MultipartFormDataWriter::item_end();
  6082. }
  6083. body += writer.finish();
  6084. EXPECT_EQ(body.size(), writer.content_length(items));
  6085. auto res = cli.Post(
  6086. "/post", body.size(),
  6087. [&](size_t offset, size_t length, DataSink &sink) {
  6088. sink.write(body.data() + offset, length);
  6089. return true;
  6090. },
  6091. writer.content_type());
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::OK_200, res->status);
  6094. }
  6095. }
  6096. TEST_F(ServerTest, PostContentReceiverGzip) {
  6097. cli_.set_compress(true);
  6098. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6100. ASSERT_EQ(StatusCode::OK_200, res->status);
  6101. ASSERT_EQ("content", res->body);
  6102. }
  6103. TEST_F(ServerTest, PutContentReceiver) {
  6104. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. ASSERT_EQ(StatusCode::OK_200, res->status);
  6107. ASSERT_EQ("content", res->body);
  6108. }
  6109. TEST_F(ServerTest, PatchContentReceiver) {
  6110. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. ASSERT_EQ(StatusCode::OK_200, res->status);
  6113. ASSERT_EQ("content", res->body);
  6114. }
  6115. template <typename ClientType>
  6116. void TestWithHeadersAndContentReceiver(
  6117. ClientType &cli,
  6118. std::function<Result(ClientType &, const std::string &, const Headers &,
  6119. const std::string &, const std::string &,
  6120. ContentReceiver, DownloadProgress)>
  6121. request_func) {
  6122. Headers headers;
  6123. headers.emplace("X-Custom-Header", "test-value");
  6124. std::string received_body;
  6125. auto res = request_func(
  6126. cli, "/content_receiver", headers, "content", "application/json",
  6127. [&](const char *data, size_t data_length) {
  6128. received_body.append(data, data_length);
  6129. return true;
  6130. },
  6131. nullptr);
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. EXPECT_EQ(StatusCode::OK_200, res->status);
  6134. EXPECT_EQ("content", received_body);
  6135. }
  6136. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6137. #ifdef CPPHTTPLIB_SSL_ENABLED
  6138. using ClientT = SSLClient;
  6139. #else
  6140. using ClientT = Client;
  6141. #endif
  6142. TestWithHeadersAndContentReceiver<ClientT>(
  6143. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6144. const std::string &body, const std::string &content_type,
  6145. ContentReceiver receiver, DownloadProgress progress) {
  6146. return cli.Post(path, headers, body, content_type, receiver, progress);
  6147. });
  6148. }
  6149. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6150. #ifdef CPPHTTPLIB_SSL_ENABLED
  6151. using ClientT = SSLClient;
  6152. #else
  6153. using ClientT = Client;
  6154. #endif
  6155. TestWithHeadersAndContentReceiver<ClientT>(
  6156. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6157. const std::string &body, const std::string &content_type,
  6158. ContentReceiver receiver, DownloadProgress progress) {
  6159. return cli.Put(path, headers, body, content_type, receiver, progress);
  6160. });
  6161. }
  6162. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6163. #ifdef CPPHTTPLIB_SSL_ENABLED
  6164. using ClientT = SSLClient;
  6165. #else
  6166. using ClientT = Client;
  6167. #endif
  6168. TestWithHeadersAndContentReceiver<ClientT>(
  6169. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6170. const std::string &body, const std::string &content_type,
  6171. ContentReceiver receiver, DownloadProgress progress) {
  6172. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6173. });
  6174. }
  6175. template <typename ClientType>
  6176. void TestWithHeadersAndContentReceiverWithProgress(
  6177. ClientType &cli,
  6178. std::function<Result(ClientType &, const std::string &, const Headers &,
  6179. const std::string &, const std::string &,
  6180. ContentReceiver, DownloadProgress)>
  6181. request_func) {
  6182. Headers headers;
  6183. headers.emplace("X-Test-Header", "progress-test");
  6184. std::string received_body;
  6185. auto progress_called = false;
  6186. auto res = request_func(
  6187. cli, "/content_receiver", headers, "content", "text/plain",
  6188. [&](const char *data, size_t data_length) {
  6189. received_body.append(data, data_length);
  6190. return true;
  6191. },
  6192. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6193. progress_called = true;
  6194. return true;
  6195. });
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. EXPECT_EQ(StatusCode::OK_200, res->status);
  6198. EXPECT_EQ("content", received_body);
  6199. EXPECT_TRUE(progress_called);
  6200. }
  6201. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6202. #ifdef CPPHTTPLIB_SSL_ENABLED
  6203. using ClientT = SSLClient;
  6204. #else
  6205. using ClientT = Client;
  6206. #endif
  6207. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6208. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6209. const std::string &body, const std::string &content_type,
  6210. ContentReceiver receiver, DownloadProgress progress) {
  6211. return cli.Post(path, headers, body, content_type, receiver, progress);
  6212. });
  6213. }
  6214. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6215. #ifdef CPPHTTPLIB_SSL_ENABLED
  6216. using ClientT = SSLClient;
  6217. #else
  6218. using ClientT = Client;
  6219. #endif
  6220. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6221. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6222. const std::string &body, const std::string &content_type,
  6223. ContentReceiver receiver, DownloadProgress progress) {
  6224. return cli.Put(path, headers, body, content_type, receiver, progress);
  6225. });
  6226. }
  6227. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6228. #ifdef CPPHTTPLIB_SSL_ENABLED
  6229. using ClientT = SSLClient;
  6230. #else
  6231. using ClientT = Client;
  6232. #endif
  6233. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6234. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6235. const std::string &body, const std::string &content_type,
  6236. ContentReceiver receiver, DownloadProgress progress) {
  6237. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6238. });
  6239. }
  6240. template <typename ClientType>
  6241. void TestWithHeadersAndContentReceiverError(
  6242. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6243. const Headers &, const std::string &,
  6244. const std::string &, ContentReceiver)>
  6245. request_func) {
  6246. Headers headers;
  6247. headers.emplace("X-Error-Test", "true");
  6248. std::string received_body;
  6249. auto receiver_failed = false;
  6250. auto res =
  6251. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6252. [&](const char *data, size_t data_length) {
  6253. received_body.append(data, data_length);
  6254. receiver_failed = true;
  6255. return false;
  6256. });
  6257. ASSERT_FALSE(res);
  6258. EXPECT_TRUE(receiver_failed);
  6259. }
  6260. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6261. #ifdef CPPHTTPLIB_SSL_ENABLED
  6262. using ClientT = SSLClient;
  6263. #else
  6264. using ClientT = Client;
  6265. #endif
  6266. TestWithHeadersAndContentReceiverError<ClientT>(
  6267. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6268. const std::string &body, const std::string &content_type,
  6269. ContentReceiver receiver) {
  6270. return cli.Post(path, headers, body, content_type, receiver);
  6271. });
  6272. }
  6273. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6274. #ifdef CPPHTTPLIB_SSL_ENABLED
  6275. using ClientT = SSLClient;
  6276. #else
  6277. using ClientT = Client;
  6278. #endif
  6279. TestWithHeadersAndContentReceiverError<ClientT>(
  6280. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6281. const std::string &body, const std::string &content_type,
  6282. ContentReceiver receiver) {
  6283. return cli.Put(path, headers, body, content_type, receiver);
  6284. });
  6285. }
  6286. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6287. #ifdef CPPHTTPLIB_SSL_ENABLED
  6288. using ClientT = SSLClient;
  6289. #else
  6290. using ClientT = Client;
  6291. #endif
  6292. TestWithHeadersAndContentReceiverError<ClientT>(
  6293. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6294. const std::string &body, const std::string &content_type,
  6295. ContentReceiver receiver) {
  6296. return cli.Patch(path, headers, body, content_type, receiver);
  6297. });
  6298. }
  6299. TEST_F(ServerTest, PostQueryStringAndBody) {
  6300. auto res =
  6301. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. ASSERT_EQ(StatusCode::OK_200, res->status);
  6304. }
  6305. TEST_F(ServerTest, HTTP2Magic) {
  6306. Request req;
  6307. req.method = "PRI";
  6308. req.path = "*";
  6309. req.body = "SM";
  6310. auto res = std::make_shared<Response>();
  6311. auto error = Error::Success;
  6312. auto ret = cli_.send(req, *res, error);
  6313. ASSERT_TRUE(ret);
  6314. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6315. }
  6316. TEST_F(ServerTest, KeepAlive) {
  6317. auto res = cli_.Get("/hi");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6321. EXPECT_EQ("Hello World!", res->body);
  6322. res = cli_.Get("/hi");
  6323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6324. EXPECT_EQ(StatusCode::OK_200, res->status);
  6325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6326. EXPECT_EQ("Hello World!", res->body);
  6327. res = cli_.Get("/hi");
  6328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6329. EXPECT_EQ(StatusCode::OK_200, res->status);
  6330. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6331. EXPECT_EQ("Hello World!", res->body);
  6332. res = cli_.Get("/not-exist");
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6335. res = cli_.Post("/empty", "", "text/plain");
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. EXPECT_EQ(StatusCode::OK_200, res->status);
  6338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6339. EXPECT_EQ("empty", res->body);
  6340. EXPECT_EQ("close", res->get_header_value("Connection"));
  6341. res = cli_.Post(
  6342. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6343. "text/plain");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6347. EXPECT_EQ("empty", res->body);
  6348. cli_.set_keep_alive(false);
  6349. res = cli_.Get("/last-request");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. EXPECT_EQ("close", res->get_header_value("Connection"));
  6353. }
  6354. TEST_F(ServerTest, TooManyRedirect) {
  6355. cli_.set_follow_location(true);
  6356. auto res = cli_.Get("/redirect/0");
  6357. ASSERT_TRUE(!res);
  6358. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6359. }
  6360. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6361. Request req;
  6362. req.method = "FOOBAR";
  6363. req.path = "/hi";
  6364. cli_.set_keep_alive(true);
  6365. auto res = cli_.send(req);
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6368. EXPECT_EQ("close", res->get_header_value("Connection"));
  6369. EXPECT_FALSE(cli_.is_socket_open());
  6370. }
  6371. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6373. TEST_F(ServerTest, Gzip) {
  6374. Headers headers;
  6375. headers.emplace("Accept-Encoding", "gzip, deflate");
  6376. auto res = cli_.Get("/compress", headers);
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6379. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6380. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6381. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6382. "7890123456789012345678901234567890",
  6383. res->body);
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. }
  6386. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6387. Headers headers;
  6388. headers.emplace("Accept-Encoding", "gzip, deflate");
  6389. auto res = cli_.Get("/compress-with-charset", headers);
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6392. EXPECT_EQ("application/json; charset=utf-8",
  6393. res->get_header_value("Content-Type"));
  6394. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6395. "7890123456789012345678901234567890",
  6396. res->body);
  6397. EXPECT_EQ(StatusCode::OK_200, res->status);
  6398. }
  6399. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6400. Headers headers;
  6401. headers.emplace("Accept-Encoding", "");
  6402. auto res = cli_.Get("/compress", headers);
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6406. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6407. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6408. "7890123456789012345678901234567890",
  6409. res->body);
  6410. EXPECT_EQ(StatusCode::OK_200, res->status);
  6411. }
  6412. TEST_F(ServerTest, GzipWithContentReceiver) {
  6413. Headers headers;
  6414. headers.emplace("Accept-Encoding", "gzip, deflate");
  6415. std::string body;
  6416. auto res = cli_.Get("/compress", headers,
  6417. [&](const char *data, uint64_t data_length) {
  6418. EXPECT_EQ(100U, data_length);
  6419. body.append(data, data_length);
  6420. return true;
  6421. });
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6425. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6426. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6427. "7890123456789012345678901234567890",
  6428. body);
  6429. EXPECT_EQ(StatusCode::OK_200, res->status);
  6430. }
  6431. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6432. Headers headers;
  6433. headers.emplace("Accept-Encoding", "gzip, deflate");
  6434. cli_.set_decompress(false);
  6435. auto res = cli_.Get("/compress", headers);
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6438. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6439. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6440. EXPECT_EQ(33U, res->body.size());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. }
  6443. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6444. Headers headers;
  6445. headers.emplace("Accept-Encoding", "");
  6446. std::string body;
  6447. auto res = cli_.Get("/compress", headers,
  6448. [&](const char *data, uint64_t data_length) {
  6449. EXPECT_EQ(100U, data_length);
  6450. body.append(data, data_length);
  6451. return true;
  6452. });
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6456. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6457. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6458. "7890123456789012345678901234567890",
  6459. body);
  6460. EXPECT_EQ(StatusCode::OK_200, res->status);
  6461. }
  6462. TEST_F(ServerTest, NoGzip) {
  6463. Headers headers;
  6464. headers.emplace("Accept-Encoding", "gzip, deflate");
  6465. auto res = cli_.Get("/nocompress", headers);
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6468. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6469. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6471. "7890123456789012345678901234567890",
  6472. res->body);
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. }
  6475. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6476. Headers headers;
  6477. headers.emplace("Accept-Encoding", "gzip, deflate");
  6478. std::string body;
  6479. auto res = cli_.Get("/nocompress", headers,
  6480. [&](const char *data, uint64_t data_length) {
  6481. EXPECT_EQ(100U, data_length);
  6482. body.append(data, data_length);
  6483. return true;
  6484. });
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6487. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6488. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6489. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6490. "7890123456789012345678901234567890",
  6491. body);
  6492. EXPECT_EQ(StatusCode::OK_200, res->status);
  6493. }
  6494. TEST_F(ServerTest, MultipartFormDataGzip) {
  6495. UploadFormDataItems items = {
  6496. {"key1", "test", "", ""},
  6497. {"key2", "--abcdefg123", "", ""},
  6498. };
  6499. cli_.set_compress(true);
  6500. auto res = cli_.Post("/compress-multipart", items);
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. EXPECT_EQ(StatusCode::OK_200, res->status);
  6503. }
  6504. #endif
  6505. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6506. TEST_F(ServerTest, Brotli) {
  6507. Headers headers;
  6508. headers.emplace("Accept-Encoding", "br");
  6509. auto res = cli_.Get("/compress", headers);
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6513. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6514. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6515. "7890123456789012345678901234567890",
  6516. res->body);
  6517. EXPECT_EQ(StatusCode::OK_200, res->status);
  6518. }
  6519. #endif
  6520. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6521. TEST_F(ServerTest, Zstd) {
  6522. Headers headers;
  6523. headers.emplace("Accept-Encoding", "zstd");
  6524. auto res = cli_.Get("/compress", headers);
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6527. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6528. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6529. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6530. "7890123456789012345678901234567890",
  6531. res->body);
  6532. EXPECT_EQ(StatusCode::OK_200, res->status);
  6533. }
  6534. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6535. Headers headers;
  6536. headers.emplace("Accept-Encoding", "");
  6537. auto res = cli_.Get("/compress", headers);
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6540. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6541. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6542. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6543. "7890123456789012345678901234567890",
  6544. res->body);
  6545. EXPECT_EQ(StatusCode::OK_200, res->status);
  6546. }
  6547. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6548. Headers headers;
  6549. headers.emplace("Accept-Encoding", "zstd");
  6550. std::string body;
  6551. auto res = cli_.Get("/compress", headers,
  6552. [&](const char *data, uint64_t data_length) {
  6553. EXPECT_EQ(100U, data_length);
  6554. body.append(data, data_length);
  6555. return true;
  6556. });
  6557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6558. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6559. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6560. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6561. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6562. "7890123456789012345678901234567890",
  6563. body);
  6564. EXPECT_EQ(StatusCode::OK_200, res->status);
  6565. }
  6566. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6567. Headers headers;
  6568. headers.emplace("Accept-Encoding", "zstd");
  6569. cli_.set_decompress(false);
  6570. auto res = cli_.Get("/compress", headers);
  6571. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6572. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6573. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6574. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6577. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6578. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6579. EXPECT_EQ(StatusCode::OK_200, res->status);
  6580. ASSERT_EQ(26U, res->body.size());
  6581. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6582. 0);
  6583. }
  6584. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6585. Headers headers;
  6586. headers.emplace("Accept-Encoding", "");
  6587. std::string body;
  6588. auto res = cli_.Get("/compress", headers,
  6589. [&](const char *data, uint64_t data_length) {
  6590. EXPECT_EQ(100U, data_length);
  6591. body.append(data, data_length);
  6592. return true;
  6593. });
  6594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6595. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6597. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6598. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6599. "7890123456789012345678901234567890",
  6600. body);
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. }
  6603. TEST_F(ServerTest, NoZstd) {
  6604. Headers headers;
  6605. headers.emplace("Accept-Encoding", "zstd");
  6606. auto res = cli_.Get("/nocompress", headers);
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6609. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6610. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6611. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6612. "7890123456789012345678901234567890",
  6613. res->body);
  6614. EXPECT_EQ(StatusCode::OK_200, res->status);
  6615. }
  6616. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6617. Headers headers;
  6618. headers.emplace("Accept-Encoding", "zstd");
  6619. std::string body;
  6620. auto res = cli_.Get("/nocompress", headers,
  6621. [&](const char *data, uint64_t data_length) {
  6622. EXPECT_EQ(100U, data_length);
  6623. body.append(data, data_length);
  6624. return true;
  6625. });
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6628. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6629. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6630. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6631. "7890123456789012345678901234567890",
  6632. body);
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. }
  6635. // TODO: How to enable zstd ??
  6636. TEST_F(ServerTest, MultipartFormDataZstd) {
  6637. UploadFormDataItems items = {
  6638. {"key1", "test", "", ""},
  6639. {"key2", "--abcdefg123", "", ""},
  6640. };
  6641. Headers headers;
  6642. headers.emplace("Accept-Encoding", "zstd");
  6643. cli_.set_compress(true);
  6644. auto res = cli_.Post("/compress-multipart", headers, items);
  6645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. }
  6648. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6649. Headers headers;
  6650. headers.emplace("Accept-Encoding", "zstd");
  6651. cli_.set_compress(true);
  6652. auto res = cli_.Put(
  6653. "/put", headers, 3,
  6654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6655. sink.os << "PUT";
  6656. return true;
  6657. },
  6658. "text/plain");
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. EXPECT_EQ("PUT", res->body);
  6662. }
  6663. // Pre-compression logging tests
  6664. TEST_F(ServerTest, PreCompressionLogging) {
  6665. // Test data for compression (matches the actual /compress endpoint content)
  6666. const std::string test_content =
  6667. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6668. "3456789012345678901234567890";
  6669. // Variables to capture logging data
  6670. std::string pre_compression_body;
  6671. std::string pre_compression_content_type;
  6672. std::string pre_compression_content_encoding;
  6673. std::string post_compression_body;
  6674. std::string post_compression_content_type;
  6675. std::string post_compression_content_encoding;
  6676. // Set up pre-compression logger
  6677. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6678. const Response &res) {
  6679. pre_compression_body = res.body;
  6680. pre_compression_content_type = res.get_header_value("Content-Type");
  6681. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6682. });
  6683. // Set up post-compression logger
  6684. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6685. post_compression_body = res.body;
  6686. post_compression_content_type = res.get_header_value("Content-Type");
  6687. post_compression_content_encoding =
  6688. res.get_header_value("Content-Encoding");
  6689. });
  6690. // Test with gzip compression
  6691. Headers headers;
  6692. headers.emplace("Accept-Encoding", "gzip");
  6693. auto res = cli_.Get("/compress", headers);
  6694. // Verify response was compressed
  6695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6696. EXPECT_EQ(StatusCode::OK_200, res->status);
  6697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6698. // Verify pre-compression logger captured uncompressed content
  6699. EXPECT_EQ(test_content, pre_compression_body);
  6700. EXPECT_EQ("text/plain", pre_compression_content_type);
  6701. EXPECT_TRUE(pre_compression_content_encoding
  6702. .empty()); // No encoding header before compression
  6703. // Verify post-compression logger captured compressed content
  6704. EXPECT_NE(test_content,
  6705. post_compression_body); // Should be different after compression
  6706. EXPECT_EQ("text/plain", post_compression_content_type);
  6707. EXPECT_EQ("gzip", post_compression_content_encoding);
  6708. // Verify compressed content is smaller
  6709. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6710. }
  6711. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6712. const std::string test_content =
  6713. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6714. "3456789012345678901234567890";
  6715. std::string pre_compression_body;
  6716. std::string post_compression_body;
  6717. svr_.set_pre_compression_logger(
  6718. [&](const Request & /*req*/, const Response &res) {
  6719. pre_compression_body = res.body;
  6720. });
  6721. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6722. post_compression_body = res.body;
  6723. });
  6724. Headers headers;
  6725. headers.emplace("Accept-Encoding", "br");
  6726. auto res = cli_.Get("/compress", headers);
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6730. // Verify pre-compression content is uncompressed
  6731. EXPECT_EQ(test_content, pre_compression_body);
  6732. // Verify post-compression content is compressed
  6733. EXPECT_NE(test_content, post_compression_body);
  6734. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6735. }
  6736. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6737. const std::string test_content =
  6738. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6739. "3456789012345678901234567890";
  6740. std::string pre_compression_body;
  6741. std::string post_compression_body;
  6742. svr_.set_pre_compression_logger(
  6743. [&](const Request & /*req*/, const Response &res) {
  6744. pre_compression_body = res.body;
  6745. });
  6746. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6747. post_compression_body = res.body;
  6748. });
  6749. // Request without compression (use /nocompress endpoint)
  6750. Headers headers;
  6751. auto res = cli_.Get("/nocompress", headers);
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. EXPECT_EQ(StatusCode::OK_200, res->status);
  6754. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6755. // Pre-compression logger should not be called when no compression is applied
  6756. EXPECT_TRUE(
  6757. pre_compression_body.empty()); // Pre-compression logger not called
  6758. EXPECT_EQ(
  6759. test_content,
  6760. post_compression_body); // Post-compression logger captures final content
  6761. }
  6762. TEST_F(ServerTest, LoggerSeesContentLength) {
  6763. size_t logged_content_length = 0;
  6764. std::string logged_content_length_header;
  6765. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6766. logged_content_length = res.content_length_;
  6767. logged_content_length_header = res.get_header_value("Content-Length");
  6768. });
  6769. auto res = cli_.Get("/nocompress");
  6770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6771. EXPECT_EQ(StatusCode::OK_200, res->status);
  6772. EXPECT_EQ(res->body.size(), logged_content_length);
  6773. EXPECT_EQ(std::to_string(logged_content_length),
  6774. logged_content_length_header);
  6775. }
  6776. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6777. const std::string test_content =
  6778. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6779. "3456789012345678901234567890";
  6780. std::string pre_compression_body;
  6781. bool pre_logger_called = false;
  6782. // Set only pre-compression logger
  6783. svr_.set_pre_compression_logger(
  6784. [&](const Request & /*req*/, const Response &res) {
  6785. pre_compression_body = res.body;
  6786. pre_logger_called = true;
  6787. });
  6788. Headers headers;
  6789. headers.emplace("Accept-Encoding", "gzip");
  6790. auto res = cli_.Get("/compress", headers);
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6794. // Verify pre-compression logger was called
  6795. EXPECT_TRUE(pre_logger_called);
  6796. EXPECT_EQ(test_content, pre_compression_body);
  6797. }
  6798. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6799. {
  6800. // Test with Expect: 100-continue header - success case
  6801. // Server returns 100 Continue, client sends body, server returns 200 OK
  6802. Request req;
  6803. req.method = "POST";
  6804. req.path = "/post-large";
  6805. req.set_header("Expect", "100-continue");
  6806. req.body = LARGE_DATA;
  6807. Response res;
  6808. auto error = Error::Success;
  6809. cli_.set_keep_alive(true);
  6810. auto ret = cli_.send(req, res, error);
  6811. EXPECT_TRUE(ret);
  6812. EXPECT_EQ(StatusCode::OK_200, res.status);
  6813. EXPECT_EQ(LARGE_DATA, res.body);
  6814. }
  6815. {
  6816. // Test with Expect: 100-continue header - error case
  6817. // Client should not send the body when server returns an error
  6818. Request req;
  6819. req.method = "POST";
  6820. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6821. req.set_header("Expect", "100-continue");
  6822. req.body = LARGE_DATA;
  6823. Response res;
  6824. auto error = Error::Success;
  6825. auto start = std::chrono::high_resolution_clock::now();
  6826. cli_.set_keep_alive(true);
  6827. auto ret = cli_.send(req, res, error);
  6828. auto end = std::chrono::high_resolution_clock::now();
  6829. auto elapsed =
  6830. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6831. .count();
  6832. // With Expect: 100-continue, request completes successfully but with error
  6833. EXPECT_TRUE(ret);
  6834. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6835. EXPECT_EQ("close", res.get_header_value("Connection"));
  6836. EXPECT_FALSE(cli_.is_socket_open());
  6837. EXPECT_LE(elapsed, 2000);
  6838. }
  6839. {
  6840. // Send an extra GET request to ensure error recovery without hanging
  6841. Request req;
  6842. req.method = "GET";
  6843. req.path = "/hi";
  6844. auto start = std::chrono::high_resolution_clock::now();
  6845. auto res = cli_.send(req);
  6846. auto end = std::chrono::high_resolution_clock::now();
  6847. auto elapsed =
  6848. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6849. .count();
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. EXPECT_EQ("Hello World!", res->body);
  6853. EXPECT_LE(elapsed, 500);
  6854. }
  6855. }
  6856. TEST(ZstdDecompressor, ChunkedDecompression) {
  6857. std::string data;
  6858. for (size_t i = 0; i < 32 * 1024; ++i) {
  6859. data.push_back(static_cast<char>('a' + i % 26));
  6860. }
  6861. std::string compressed_data;
  6862. {
  6863. httplib::detail::zstd_compressor compressor;
  6864. bool result = compressor.compress(
  6865. data.data(), data.size(),
  6866. /*last=*/true,
  6867. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6868. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6869. compressed_data_size);
  6870. return true;
  6871. });
  6872. ASSERT_TRUE(result);
  6873. }
  6874. std::string decompressed_data;
  6875. {
  6876. httplib::detail::zstd_decompressor decompressor;
  6877. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6878. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6879. size_t chunk_size = 130;
  6880. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6881. chunk_begin += chunk_size) {
  6882. size_t current_chunk_size =
  6883. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6884. bool result = decompressor.decompress(
  6885. compressed_data.data() + chunk_begin, current_chunk_size,
  6886. [&](const char *decompressed_data_chunk,
  6887. size_t decompressed_data_chunk_size) {
  6888. decompressed_data.insert(decompressed_data.size(),
  6889. decompressed_data_chunk,
  6890. decompressed_data_chunk_size);
  6891. return true;
  6892. });
  6893. ASSERT_TRUE(result);
  6894. }
  6895. }
  6896. ASSERT_EQ(data, decompressed_data);
  6897. }
  6898. TEST(ZstdDecompressor, Decompress) {
  6899. std::string original_text = "Compressed with ZSTD";
  6900. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6901. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6902. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6903. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6904. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6905. std::string decompressed_data;
  6906. {
  6907. httplib::detail::zstd_decompressor decompressor;
  6908. bool result = decompressor.decompress(
  6909. compressed_data.data(), compressed_data.size(),
  6910. [&](const char *decompressed_data_chunk,
  6911. size_t decompressed_data_chunk_size) {
  6912. decompressed_data.insert(decompressed_data.size(),
  6913. decompressed_data_chunk,
  6914. decompressed_data_chunk_size);
  6915. return true;
  6916. });
  6917. ASSERT_TRUE(result);
  6918. }
  6919. ASSERT_EQ(original_text, decompressed_data);
  6920. }
  6921. #endif
  6922. // Sends a raw request to a server listening at HOST:PORT.
  6923. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6924. std::string *resp = nullptr) {
  6925. auto error = Error::Success;
  6926. auto client_sock = detail::create_client_socket(
  6927. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6928. /*connection_timeout_sec=*/5, 0,
  6929. /*read_timeout_sec=*/5, 0,
  6930. /*write_timeout_sec=*/5, 0, std::string(), error);
  6931. if (client_sock == INVALID_SOCKET) { return false; }
  6932. auto ret = detail::process_client_socket(
  6933. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6934. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6935. if (req.size() !=
  6936. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6937. return false;
  6938. }
  6939. char buf[512];
  6940. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6941. while (line_reader.getline()) {
  6942. if (resp) { *resp += line_reader.ptr(); }
  6943. }
  6944. return true;
  6945. });
  6946. detail::close_socket(client_sock);
  6947. return ret;
  6948. }
  6949. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6950. Server svr;
  6951. std::string header_value;
  6952. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6953. header_value = req.get_header_value("foo");
  6954. res.set_content("ok", "text/plain");
  6955. });
  6956. thread t = thread([&] { svr.listen(HOST, PORT); });
  6957. auto se = detail::scope_exit([&] {
  6958. svr.stop();
  6959. t.join();
  6960. ASSERT_FALSE(svr.is_running());
  6961. });
  6962. svr.wait_until_ready();
  6963. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6964. // like characters are not treated the same - use vertical tab and escape.
  6965. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6966. "foo: \t \v bar \x1B\t \r\n"
  6967. "Connection: close\r\n"
  6968. "\r\n";
  6969. std::string res;
  6970. ASSERT_TRUE(send_request(5, req, &res));
  6971. EXPECT_EQ(header_value, "");
  6972. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6973. }
  6974. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6975. Server svr;
  6976. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6977. auto i = new int(0);
  6978. res.set_header("Trailer", "X-Safe, X-Reflected");
  6979. res.set_chunked_content_provider(
  6980. "text/plain",
  6981. [i](size_t /*offset*/, DataSink &sink) {
  6982. if (*i == 0) {
  6983. sink.os << "body";
  6984. } else {
  6985. Headers trailer;
  6986. // A valid trailer that must survive.
  6987. trailer.emplace("X-Safe", "safe");
  6988. // Attacker-controlled value carrying CR/LF (response splitting).
  6989. trailer.emplace("X-Reflected",
  6990. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6991. // Attacker-controlled name carrying CR/LF.
  6992. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6993. sink.done_with_trailer(trailer);
  6994. }
  6995. (*i)++;
  6996. return true;
  6997. },
  6998. [i](bool /*success*/) { delete i; });
  6999. });
  7000. thread t = thread([&] { svr.listen(HOST, PORT); });
  7001. auto se = detail::scope_exit([&] {
  7002. svr.stop();
  7003. t.join();
  7004. ASSERT_FALSE(svr.is_running());
  7005. });
  7006. svr.wait_until_ready();
  7007. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7008. "Host: " + HOST +
  7009. "\r\n"
  7010. "Connection: close\r\n"
  7011. "\r\n";
  7012. std::string res;
  7013. ASSERT_TRUE(send_request(5, req, &res));
  7014. // The injected fields must not appear anywhere in the raw response.
  7015. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7016. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7017. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7018. // Invalid trailers are dropped entirely, matching set_header().
  7019. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7020. // The valid trailer still passes through.
  7021. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7022. }
  7023. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7024. Server svr;
  7025. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7026. // res.headers is a public field an application can populate directly,
  7027. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7028. // A valid header that must survive.
  7029. res.headers.emplace("X-Safe", "safe");
  7030. // Attacker-controlled value carrying CR/LF (response splitting).
  7031. res.headers.emplace("X-Reflected",
  7032. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7033. // Attacker-controlled name carrying CR/LF.
  7034. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7035. res.set_content("body", "text/plain");
  7036. });
  7037. thread t = thread([&] { svr.listen(HOST, PORT); });
  7038. auto se = detail::scope_exit([&] {
  7039. svr.stop();
  7040. t.join();
  7041. ASSERT_FALSE(svr.is_running());
  7042. });
  7043. svr.wait_until_ready();
  7044. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7045. "Host: " + HOST +
  7046. "\r\n"
  7047. "Connection: close\r\n"
  7048. "\r\n";
  7049. std::string res;
  7050. ASSERT_TRUE(send_request(5, req, &res));
  7051. // The injected fields must not appear anywhere in the raw response.
  7052. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7053. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7054. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7055. // Invalid headers are dropped entirely, matching set_header().
  7056. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7057. // The valid header still passes through.
  7058. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7059. }
  7060. // Forward declaration: in split builds split.py strips `inline` and moves the
  7061. // definition into httplib.cc, so detail::write_request_line is not visible from
  7062. // the public httplib.h. Re-declaring it here lets the tests link against the
  7063. // symbol in both header-only and split builds.
  7064. namespace httplib {
  7065. namespace detail {
  7066. ssize_t write_request_line(Stream &strm, const std::string &method,
  7067. const std::string &path);
  7068. } // namespace detail
  7069. } // namespace httplib
  7070. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7071. // A well-formed target is written verbatim.
  7072. {
  7073. detail::BufferStream strm;
  7074. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7075. EXPECT_GT(n, 0);
  7076. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7077. }
  7078. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7079. // otherwise it splits the request line and injects a header or a whole
  7080. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7081. // when path encoding is disabled.
  7082. const std::string evil_targets[] = {
  7083. "/a\r\nInjected: pwned",
  7084. "/a\rInjected",
  7085. "/a\nInjected",
  7086. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7087. };
  7088. for (const auto &evil : evil_targets) {
  7089. detail::BufferStream strm;
  7090. auto n = detail::write_request_line(strm, "GET", evil);
  7091. EXPECT_LT(n, 0);
  7092. EXPECT_TRUE(strm.get_buffer().empty());
  7093. }
  7094. }
  7095. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7096. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7097. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7098. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7099. // client must fail cleanly with Error::Write instead of putting a
  7100. // request-line-less, header-injecting request on the wire.
  7101. Server svr;
  7102. svr.Get("/a", [](const Request &, Response &res) {
  7103. res.set_content("ok", "text/plain");
  7104. });
  7105. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7106. auto se = detail::scope_exit([&] {
  7107. svr.stop();
  7108. thread.join();
  7109. ASSERT_FALSE(svr.is_running());
  7110. });
  7111. svr.wait_until_ready();
  7112. {
  7113. Client cli(HOST, PORT);
  7114. cli.set_path_encode(false);
  7115. // The request is rejected before anything is written, so the connection
  7116. // stays silent and the subsequent response read would otherwise block for
  7117. // the full default read timeout. Shorten it -- the assertion is on the
  7118. // error, not the timeout.
  7119. cli.set_read_timeout(1, 0);
  7120. auto res = cli.Get("/a\r\nInjected: pwned");
  7121. EXPECT_FALSE(res);
  7122. EXPECT_EQ(Error::Write, res.error());
  7123. }
  7124. }
  7125. // Sends a raw request and verifies that there isn't a crash or exception.
  7126. static void test_raw_request(const std::string &req,
  7127. std::string *out = nullptr) {
  7128. Server svr;
  7129. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7130. res.set_content("ok", "text/plain");
  7131. });
  7132. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7133. res.set_content("ok", "text/plain");
  7134. });
  7135. svr.Get("/header_field_value_check",
  7136. [&](const Request & /*req*/, Response &res) {
  7137. res.set_content("ok", "text/plain");
  7138. });
  7139. // Server read timeout must be longer than the client read timeout for the
  7140. // bug to reproduce, probably to force the server to process a request
  7141. // without a trailing blank line.
  7142. const time_t client_read_timeout_sec = 1;
  7143. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7144. bool listen_thread_ok = false;
  7145. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7146. auto se = detail::scope_exit([&] {
  7147. svr.stop();
  7148. t.join();
  7149. ASSERT_FALSE(svr.is_running());
  7150. EXPECT_TRUE(listen_thread_ok);
  7151. });
  7152. svr.wait_until_ready();
  7153. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7154. }
  7155. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7156. // A certain header line causes an exception if the header property is parsed
  7157. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7158. test_raw_request(
  7159. "GET /hi HTTP/1.1\r\n"
  7160. " : "
  7161. " "
  7162. " ");
  7163. }
  7164. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7165. // A certain header line causes an exception if the header property *name* is
  7166. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7167. // greedy matcher and requires backtracking when there are a lot of ":"
  7168. // characters.
  7169. // This occurs with libc++ but not libstdc++.
  7170. test_raw_request(
  7171. "GET /hi HTTP/1.1\r\n"
  7172. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7173. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7174. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7175. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7176. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7177. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7178. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7179. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7180. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7181. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7182. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7183. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7184. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7185. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7186. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7187. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7188. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7189. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7190. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7191. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7192. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7193. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7194. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7195. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7196. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7197. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7198. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7199. "&&&%%%");
  7200. }
  7201. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7202. // Make sure this doesn't crash the server.
  7203. // In a previous version of the header line regex, the "\r" rendered the line
  7204. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7205. // a new position where the leading white space ended and the field value
  7206. // began.
  7207. // The crash occurs with libc++ but not libstdc++.
  7208. test_raw_request("GET /hi HTTP/1.1\r\n"
  7209. "a:" +
  7210. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7211. "\r\n"
  7212. "\r\n");
  7213. }
  7214. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7215. std::string out;
  7216. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7217. "Content-Type: text/plain\r\n"
  7218. "Transfer-Encoding: chunked\r\n"
  7219. "\r\n"
  7220. "nothex\r\n",
  7221. &out);
  7222. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7223. }
  7224. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7225. std::string out;
  7226. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7227. "Content-Type: text/plain\r\n"
  7228. "Transfer-Encoding: chunked\r\n"
  7229. "\r\n"
  7230. "3\r\n"
  7231. "xyz\r\n"
  7232. "NaN\r\n",
  7233. &out);
  7234. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7235. }
  7236. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7237. std::string out;
  7238. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7239. "Content-Type: text/plain\r\n"
  7240. "Transfer-Encoding: chunked\r\n"
  7241. "\r\n"
  7242. // Length is too large for 64 bits.
  7243. "1ffffffffffffffff\r\n"
  7244. "xyz\r\n",
  7245. &out);
  7246. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7247. }
  7248. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7249. test_raw_request("GET /hi HTTP/1.1\r\n"
  7250. "Content-Type: text/plain\r\n\r");
  7251. }
  7252. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7253. std::string out;
  7254. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7255. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7256. }
  7257. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7258. Server svr;
  7259. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7260. EXPECT_TRUE(!req.remote_addr.empty());
  7261. });
  7262. thread t = thread([&] { svr.listen(HOST, PORT); });
  7263. auto se = detail::scope_exit([&] {
  7264. svr.stop();
  7265. t.join();
  7266. ASSERT_FALSE(svr.is_running());
  7267. });
  7268. svr.wait_until_ready();
  7269. // Send an invalid request line to trigger Bad Request
  7270. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7271. std::string out;
  7272. ASSERT_TRUE(send_request(5, bad_req, &out));
  7273. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7274. }
  7275. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7276. std::string out;
  7277. std::string request(
  7278. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7279. test_raw_request(request, &out);
  7280. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7281. }
  7282. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7283. std::string out;
  7284. std::string request(
  7285. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7286. test_raw_request(request, &out);
  7287. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7288. }
  7289. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7290. std::string out;
  7291. std::string request(
  7292. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7293. test_raw_request(request, &out);
  7294. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7295. }
  7296. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7297. std::string out;
  7298. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7299. "Test: \r\n\r\n",
  7300. &out);
  7301. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7302. }
  7303. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7304. Server svr;
  7305. std::string x_custom;
  7306. std::string cookie;
  7307. std::string xff;
  7308. std::string x_unicode;
  7309. std::string x_iis;
  7310. svr.Get("/check", [&](const Request &req, Response &res) {
  7311. x_custom = req.get_header_value("X-Custom");
  7312. cookie = req.get_header_value("Cookie");
  7313. xff = req.get_header_value("X-Forwarded-For");
  7314. x_unicode = req.get_header_value("X-Unicode");
  7315. x_iis = req.get_header_value("X-IIS");
  7316. res.set_content("ok", "text/plain");
  7317. });
  7318. thread t = thread([&] { svr.listen(HOST, PORT); });
  7319. auto se = detail::scope_exit([&] {
  7320. svr.stop();
  7321. t.join();
  7322. ASSERT_FALSE(svr.is_running());
  7323. });
  7324. svr.wait_until_ready();
  7325. const std::string req = "GET /check HTTP/1.1\r\n"
  7326. "Host: localhost\r\n"
  7327. "X-Custom: a%0D%0AInjected: b\r\n"
  7328. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7329. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7330. "X-Unicode: %E3%81%82\r\n"
  7331. "X-IIS: %u00E9\r\n"
  7332. "Connection: close\r\n"
  7333. "\r\n";
  7334. std::string res;
  7335. ASSERT_TRUE(send_request(5, req, &res));
  7336. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7337. // Every value must be returned verbatim (wire form), with no decoding.
  7338. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7339. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7340. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7341. EXPECT_EQ("%E3%81%82", x_unicode);
  7342. EXPECT_EQ("%u00E9", x_iis);
  7343. }
  7344. // Applications that previously relied on automatic percent-decoding can
  7345. // reproduce the old behavior by explicitly calling decode_path_component()
  7346. // or, for RFC 3986 conformance, decode_uri_component().
  7347. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7348. Server svr;
  7349. std::string decoded;
  7350. svr.Get("/check", [&](const Request &req, Response &res) {
  7351. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7352. res.set_content("ok", "text/plain");
  7353. });
  7354. thread t = thread([&] { svr.listen(HOST, PORT); });
  7355. auto se = detail::scope_exit([&] {
  7356. svr.stop();
  7357. t.join();
  7358. ASSERT_FALSE(svr.is_running());
  7359. });
  7360. svr.wait_until_ready();
  7361. const std::string req = "GET /check HTTP/1.1\r\n"
  7362. "Host: localhost\r\n"
  7363. "X-Custom: hello%20world\r\n"
  7364. "Connection: close\r\n"
  7365. "\r\n";
  7366. std::string res;
  7367. ASSERT_TRUE(send_request(5, req, &res));
  7368. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7369. EXPECT_EQ("hello world", decoded);
  7370. }
  7371. // Regression test for #2033. Browsers send Referer values that include
  7372. // percent-encoded characters such as %0A inside the URL. Decoding the
  7373. // header value would either trip the post-decode CR/LF/NUL guard (the
  7374. // original bug, returning 400) or, after that guard was relaxed, silently
  7375. // store a literal LF — both unacceptable. The wire form must round-trip.
  7376. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7377. Server svr;
  7378. std::string referer;
  7379. svr.Get("/check", [&](const Request &req, Response &res) {
  7380. referer = req.get_header_value("Referer");
  7381. res.set_content("ok", "text/plain");
  7382. });
  7383. thread t = thread([&] { svr.listen(HOST, PORT); });
  7384. auto se = detail::scope_exit([&] {
  7385. svr.stop();
  7386. t.join();
  7387. ASSERT_FALSE(svr.is_running());
  7388. });
  7389. svr.wait_until_ready();
  7390. const std::string req = "GET /check HTTP/1.1\r\n"
  7391. "Host: localhost\r\n"
  7392. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7393. "Connection: close\r\n"
  7394. "\r\n";
  7395. std::string res;
  7396. ASSERT_TRUE(send_request(5, req, &res));
  7397. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7398. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7399. }
  7400. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7401. Server svr;
  7402. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7403. res.set_header("Cache-Control", "no-cache");
  7404. res.set_chunked_content_provider(
  7405. "text/event-stream", [](size_t offset, DataSink &sink) {
  7406. std::string s = "data:";
  7407. s += std::to_string(offset);
  7408. s += "\n\n";
  7409. auto ret = sink.write(s.data(), s.size());
  7410. EXPECT_TRUE(ret);
  7411. std::this_thread::sleep_for(std::chrono::seconds(1));
  7412. return true;
  7413. });
  7414. });
  7415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7416. svr.wait_until_ready();
  7417. Client client(HOST, PORT);
  7418. const Headers headers = {{"Accept", "text/event-stream"}};
  7419. auto get_thread = std::thread([&client, &headers]() {
  7420. auto res = client.Get(
  7421. "/events", headers,
  7422. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7423. });
  7424. auto se = detail::scope_exit([&] {
  7425. svr.stop();
  7426. get_thread.join();
  7427. listen_thread.join();
  7428. ASSERT_FALSE(svr.is_running());
  7429. });
  7430. // Give GET time to get a few messages.
  7431. std::this_thread::sleep_for(std::chrono::seconds(2));
  7432. }
  7433. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7434. httplib::Server svr;
  7435. svr.Post("/hi",
  7436. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7437. res.status = StatusCode::OK_200;
  7438. });
  7439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7440. svr.wait_until_ready();
  7441. Client cli(HOST, PORT);
  7442. auto res = cli.Post("/hi", "data", "text/plain");
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. svr.stop();
  7446. thread.join();
  7447. ASSERT_FALSE(svr.is_running());
  7448. res = cli.Post("/hi", "data", "text/plain");
  7449. ASSERT_FALSE(res);
  7450. }
  7451. TEST(ServerStopTest, ListenFailure) {
  7452. Server svr;
  7453. auto t = thread([&]() {
  7454. auto ret = svr.listen("????", PORT);
  7455. EXPECT_FALSE(ret);
  7456. });
  7457. svr.wait_until_ready();
  7458. svr.stop();
  7459. t.join();
  7460. }
  7461. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7462. TEST(ServerStopTest, Decommision) {
  7463. Server svr;
  7464. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7465. for (int i = 0; i < 4; i++) {
  7466. auto is_even = !(i % 2);
  7467. std::thread t{[&] {
  7468. try {
  7469. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7470. if (is_even) {
  7471. throw std::runtime_error("Some thing that happens to go wrong.");
  7472. }
  7473. svr.listen(HOST, PORT);
  7474. } catch (...) { svr.decommission(); }
  7475. }};
  7476. svr.wait_until_ready();
  7477. // Server is up
  7478. {
  7479. Client cli(HOST, PORT);
  7480. auto res = cli.Get("/hi");
  7481. if (is_even) {
  7482. EXPECT_FALSE(res);
  7483. } else {
  7484. EXPECT_TRUE(res);
  7485. EXPECT_EQ("hi...", res->body);
  7486. }
  7487. }
  7488. svr.stop();
  7489. t.join();
  7490. // Server is down...
  7491. {
  7492. Client cli(HOST, PORT);
  7493. auto res = cli.Get("/hi");
  7494. EXPECT_FALSE(res);
  7495. }
  7496. }
  7497. }
  7498. #endif
  7499. // Helper function for string body upload progress tests
  7500. template <typename SetupHandler, typename ClientCall>
  7501. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7502. ClientCall &&client_call,
  7503. const string &body) {
  7504. Server svr;
  7505. setup_handler(svr);
  7506. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7507. auto se = detail::scope_exit([&] {
  7508. svr.stop();
  7509. t.join();
  7510. });
  7511. svr.wait_until_ready();
  7512. Client cli(HOST, PORT);
  7513. vector<uint64_t> progress_values;
  7514. bool progress_called = false;
  7515. auto res =
  7516. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7517. progress_values.push_back(current);
  7518. progress_called = true;
  7519. return true;
  7520. });
  7521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7522. EXPECT_EQ(200, res->status);
  7523. EXPECT_TRUE(progress_called);
  7524. }
  7525. TEST(UploadProgressTest, PostStringBodyBasic) {
  7526. TestStringBodyUploadProgress(
  7527. [](Server &svr) {
  7528. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7529. res.set_content("received", "text/plain");
  7530. });
  7531. },
  7532. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7533. return cli.Post("/test", body, "text/plain", progress_callback);
  7534. },
  7535. "test data for upload progress");
  7536. }
  7537. TEST(UploadProgressTest, PutStringBodyBasic) {
  7538. TestStringBodyUploadProgress(
  7539. [](Server &svr) {
  7540. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7541. res.set_content("put received", "text/plain");
  7542. });
  7543. },
  7544. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7545. return cli.Put("/test", body, "text/plain", progress_callback);
  7546. },
  7547. "put test data for upload progress");
  7548. }
  7549. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7550. TestStringBodyUploadProgress(
  7551. [](Server &svr) {
  7552. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7553. res.set_content("patch received", "text/plain");
  7554. });
  7555. },
  7556. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7557. return cli.Patch("/test", body, "text/plain", progress_callback);
  7558. },
  7559. "patch test data for upload progress");
  7560. }
  7561. // Helper function for content provider upload progress tests
  7562. template <typename SetupHandler, typename ClientCall>
  7563. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7564. ClientCall &&client_call) {
  7565. Server svr;
  7566. setup_handler(svr);
  7567. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7568. auto se = detail::scope_exit([&] {
  7569. svr.stop();
  7570. t.join();
  7571. });
  7572. svr.wait_until_ready();
  7573. Client cli(HOST, PORT);
  7574. vector<uint64_t> progress_values;
  7575. auto res =
  7576. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7577. progress_values.push_back(current);
  7578. return true;
  7579. });
  7580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7581. EXPECT_EQ(200, res->status);
  7582. EXPECT_FALSE(progress_values.empty());
  7583. }
  7584. TEST(UploadProgressTest, PostContentProviderProgress) {
  7585. TestContentProviderUploadProgress(
  7586. [](Server &svr) {
  7587. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7588. res.set_content("provider received", "text/plain");
  7589. });
  7590. },
  7591. [](Client &cli, UploadProgress progress_callback) {
  7592. return cli.Post(
  7593. "/test", 10,
  7594. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7595. sink.os << "test data";
  7596. return true;
  7597. },
  7598. "text/plain", progress_callback);
  7599. });
  7600. }
  7601. // Helper function for multipart upload progress tests
  7602. template <typename SetupHandler, typename ClientCall>
  7603. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7604. ClientCall &&client_call,
  7605. const string &endpoint) {
  7606. Server svr;
  7607. setup_handler(svr);
  7608. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7609. auto se = detail::scope_exit([&] {
  7610. svr.stop();
  7611. t.join();
  7612. });
  7613. svr.wait_until_ready();
  7614. Client cli(HOST, PORT);
  7615. vector<uint64_t> progress_values;
  7616. UploadFormDataItems items = {
  7617. {"field1", "value1", "", ""},
  7618. {"field2", "longer value for progress tracking test", "", ""},
  7619. {"file1", "file content data for upload progress", "test.txt",
  7620. "text/plain"}};
  7621. auto res = client_call(cli, endpoint, items,
  7622. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7623. progress_values.push_back(current);
  7624. return true;
  7625. });
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ(200, res->status);
  7628. EXPECT_FALSE(progress_values.empty());
  7629. }
  7630. TEST(UploadProgressTest, PostMultipartProgress) {
  7631. TestMultipartUploadProgress(
  7632. [](Server &svr) {
  7633. svr.Post("/multipart", [](const Request &req, Response &res) {
  7634. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7635. res.set_content("multipart received", "text/plain");
  7636. });
  7637. },
  7638. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7639. UploadProgress progress_callback) {
  7640. return cli.Post(endpoint, items, progress_callback);
  7641. },
  7642. "/multipart");
  7643. }
  7644. // Helper function for basic download progress tests
  7645. template <typename SetupHandler, typename ClientCall>
  7646. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7647. ClientCall &&client_call, const string &endpoint,
  7648. size_t expected_content_size) {
  7649. Server svr;
  7650. setup_handler(svr);
  7651. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7652. auto se = detail::scope_exit([&] {
  7653. svr.stop();
  7654. t.join();
  7655. });
  7656. svr.wait_until_ready();
  7657. Client cli(HOST, PORT);
  7658. vector<uint64_t> progress_values;
  7659. auto res = client_call(cli, endpoint,
  7660. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7661. progress_values.push_back(current);
  7662. return true;
  7663. });
  7664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7665. EXPECT_EQ(200, res->status);
  7666. EXPECT_FALSE(progress_values.empty());
  7667. EXPECT_EQ(expected_content_size, res->body.size());
  7668. }
  7669. TEST(DownloadProgressTest, GetBasic) {
  7670. TestBasicDownloadProgress(
  7671. [](Server &svr) {
  7672. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7673. string content(1000, 'D');
  7674. res.set_content(content, "text/plain");
  7675. });
  7676. },
  7677. [](Client &cli, const string &endpoint,
  7678. DownloadProgress progress_callback) {
  7679. return cli.Get(endpoint, progress_callback);
  7680. },
  7681. "/download", 1000u);
  7682. }
  7683. // Helper function for content receiver download progress tests
  7684. template <typename SetupHandler, typename ClientCall>
  7685. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7686. ClientCall &&client_call,
  7687. const string &endpoint,
  7688. size_t expected_content_size) {
  7689. Server svr;
  7690. setup_handler(svr);
  7691. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7692. auto se = detail::scope_exit([&] {
  7693. svr.stop();
  7694. t.join();
  7695. });
  7696. svr.wait_until_ready();
  7697. Client cli(HOST, PORT);
  7698. vector<uint64_t> progress_values;
  7699. string received_body;
  7700. auto res = client_call(
  7701. cli, endpoint,
  7702. [&](const char *data, size_t data_length) -> bool {
  7703. received_body.append(data, data_length);
  7704. return true;
  7705. },
  7706. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7707. progress_values.push_back(current);
  7708. return true;
  7709. });
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(200, res->status);
  7712. EXPECT_FALSE(progress_values.empty());
  7713. EXPECT_EQ(expected_content_size, received_body.size());
  7714. EXPECT_TRUE(res->body.empty());
  7715. }
  7716. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7717. TestContentReceiverDownloadProgress(
  7718. [](Server &svr) {
  7719. svr.Get("/download-receiver",
  7720. [](const Request & /*req*/, Response &res) {
  7721. string content(2000, 'R');
  7722. res.set_content(content, "text/plain");
  7723. });
  7724. },
  7725. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7726. DownloadProgress progress_callback) {
  7727. return cli.Get(endpoint, content_receiver, progress_callback);
  7728. },
  7729. "/download-receiver", 2000u);
  7730. }
  7731. TEST(StreamingTest, NoContentLengthStreaming) {
  7732. Server svr;
  7733. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7734. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7735. if (offset < 6) {
  7736. sink.os << (offset < 3 ? "a" : "b");
  7737. } else {
  7738. sink.done();
  7739. }
  7740. return true;
  7741. });
  7742. });
  7743. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7744. auto listen_se = detail::scope_exit([&] {
  7745. svr.stop();
  7746. listen_thread.join();
  7747. ASSERT_FALSE(svr.is_running());
  7748. });
  7749. svr.wait_until_ready();
  7750. Client client(HOST, PORT);
  7751. auto get_thread = std::thread([&client]() {
  7752. std::string s;
  7753. auto res =
  7754. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7755. s += std::string(data, len);
  7756. return true;
  7757. });
  7758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. EXPECT_EQ("aaabbb", s);
  7761. });
  7762. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7763. // Give GET time to get a few messages.
  7764. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7765. }
  7766. TEST(MountTest, Unmount) {
  7767. Server svr;
  7768. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7769. auto se = detail::scope_exit([&] {
  7770. svr.stop();
  7771. listen_thread.join();
  7772. ASSERT_FALSE(svr.is_running());
  7773. });
  7774. svr.wait_until_ready();
  7775. Client cli("localhost", PORT);
  7776. svr.set_mount_point("/mount2", "./www2");
  7777. auto res = cli.Get("/");
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7780. res = cli.Get("/mount2/dir/test.html");
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. svr.set_mount_point("/", "./www");
  7784. res = cli.Get("/dir/");
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::OK_200, res->status);
  7787. svr.remove_mount_point("/");
  7788. res = cli.Get("/dir/");
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7791. svr.remove_mount_point("/mount2");
  7792. res = cli.Get("/mount2/dir/test.html");
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7795. }
  7796. TEST(MountTest, Redicect) {
  7797. Server svr;
  7798. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7799. auto se = detail::scope_exit([&] {
  7800. svr.stop();
  7801. listen_thread.join();
  7802. ASSERT_FALSE(svr.is_running());
  7803. });
  7804. svr.set_mount_point("/", "./www");
  7805. svr.wait_until_ready();
  7806. Client cli("localhost", PORT);
  7807. auto res = cli.Get("/dir/");
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::OK_200, res->status);
  7810. res = cli.Get("/dir");
  7811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7812. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7813. res = cli.Get("/file");
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. res = cli.Get("/file/");
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7819. cli.set_follow_location(true);
  7820. res = cli.Get("/dir");
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. }
  7824. TEST(MountTest, MultibytesPathName) {
  7825. Server svr;
  7826. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7827. auto se = detail::scope_exit([&] {
  7828. svr.stop();
  7829. listen_thread.join();
  7830. ASSERT_FALSE(svr.is_running());
  7831. });
  7832. svr.set_mount_point("/", "./www");
  7833. svr.wait_until_ready();
  7834. Client cli("localhost", PORT);
  7835. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7839. }
  7840. #ifdef _WIN32
  7841. // Issue #2435: mmap::open() must succeed even when another handle holds
  7842. // the file open for writing (e.g. an active log file).
  7843. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7844. const char *path = "mmap_concurrent_writer_test.txt";
  7845. const char *content = "hello";
  7846. {
  7847. std::ofstream f(path, std::ios::binary);
  7848. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7849. }
  7850. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7851. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7852. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7853. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7854. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7855. detail::mmap m(path);
  7856. ASSERT_TRUE(m.is_open());
  7857. EXPECT_EQ(strlen(content), m.size());
  7858. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7859. }
  7860. #endif
  7861. TEST(KeepAliveTest, ReadTimeout) {
  7862. Server svr;
  7863. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7864. std::this_thread::sleep_for(std::chrono::seconds(2));
  7865. res.set_content("a", "text/plain");
  7866. });
  7867. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7868. res.set_content("b", "text/plain");
  7869. });
  7870. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7871. auto se = detail::scope_exit([&] {
  7872. svr.stop();
  7873. listen_thread.join();
  7874. ASSERT_FALSE(svr.is_running());
  7875. });
  7876. svr.wait_until_ready();
  7877. Client cli("localhost", PORT);
  7878. cli.set_keep_alive(true);
  7879. cli.set_read_timeout(std::chrono::seconds(1));
  7880. auto resa = cli.Get("/a");
  7881. ASSERT_FALSE(resa);
  7882. EXPECT_EQ(Error::Read, resa.error());
  7883. auto resb = cli.Get("/b");
  7884. ASSERT_TRUE(resb);
  7885. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7886. EXPECT_EQ("b", resb->body);
  7887. }
  7888. TEST(KeepAliveTest, MaxCount) {
  7889. size_t keep_alive_max_count = 3;
  7890. Server svr;
  7891. svr.set_keep_alive_max_count(keep_alive_max_count);
  7892. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7893. res.set_content("Hello World!", "text/plain");
  7894. });
  7895. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7896. auto se = detail::scope_exit([&] {
  7897. svr.stop();
  7898. listen_thread.join();
  7899. ASSERT_FALSE(svr.is_running());
  7900. });
  7901. svr.wait_until_ready();
  7902. Client cli(HOST, PORT);
  7903. cli.set_keep_alive(true);
  7904. for (size_t i = 0; i < 5; i++) {
  7905. auto result = cli.Get("/hi");
  7906. ASSERT_TRUE(result);
  7907. EXPECT_EQ(StatusCode::OK_200, result->status);
  7908. if (i == keep_alive_max_count - 1) {
  7909. EXPECT_EQ("close", result->get_header_value("Connection"));
  7910. } else {
  7911. EXPECT_FALSE(result->has_header("Connection"));
  7912. }
  7913. }
  7914. }
  7915. TEST(KeepAliveTest, Issue1041) {
  7916. Server svr;
  7917. svr.set_keep_alive_timeout(3);
  7918. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7919. res.set_content("Hello World!", "text/plain");
  7920. });
  7921. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7922. auto se = detail::scope_exit([&] {
  7923. svr.stop();
  7924. listen_thread.join();
  7925. ASSERT_FALSE(svr.is_running());
  7926. });
  7927. svr.wait_until_ready();
  7928. Client cli(HOST, PORT);
  7929. cli.set_keep_alive(true);
  7930. auto result = cli.Get("/hi");
  7931. ASSERT_TRUE(result);
  7932. EXPECT_EQ(StatusCode::OK_200, result->status);
  7933. std::this_thread::sleep_for(std::chrono::seconds(5));
  7934. result = cli.Get("/hi");
  7935. ASSERT_TRUE(result);
  7936. EXPECT_EQ(StatusCode::OK_200, result->status);
  7937. }
  7938. TEST(KeepAliveTest, Issue1959) {
  7939. Server svr;
  7940. svr.set_keep_alive_timeout(5);
  7941. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7942. res.set_content("a", "text/plain");
  7943. });
  7944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7945. auto se = detail::scope_exit([&] {
  7946. if (!svr.is_running()) return;
  7947. svr.stop();
  7948. listen_thread.join();
  7949. ASSERT_FALSE(svr.is_running());
  7950. });
  7951. svr.wait_until_ready();
  7952. Client cli("localhost", PORT);
  7953. cli.set_keep_alive(true);
  7954. using namespace std::chrono;
  7955. auto start = steady_clock::now();
  7956. cli.Get("/a");
  7957. svr.stop();
  7958. listen_thread.join();
  7959. auto end = steady_clock::now();
  7960. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7961. EXPECT_LT(elapsed, 5000);
  7962. }
  7963. #ifdef CPPHTTPLIB_SSL_ENABLED
  7964. TEST(KeepAliveTest, SSLClientReconnection) {
  7965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7966. ASSERT_TRUE(svr.is_valid());
  7967. svr.set_keep_alive_timeout(1);
  7968. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7969. res.set_content("Hello World!", "text/plain");
  7970. });
  7971. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7972. auto se = detail::scope_exit([&] {
  7973. svr.stop();
  7974. listen_thread.join();
  7975. ASSERT_FALSE(svr.is_running());
  7976. });
  7977. svr.wait_until_ready();
  7978. SSLClient cli(HOST, PORT);
  7979. cli.enable_server_certificate_verification(false);
  7980. cli.set_keep_alive(true);
  7981. auto result = cli.Get("/hi");
  7982. ASSERT_TRUE(result);
  7983. EXPECT_EQ(StatusCode::OK_200, result->status);
  7984. result = cli.Get("/hi");
  7985. ASSERT_TRUE(result);
  7986. EXPECT_EQ(StatusCode::OK_200, result->status);
  7987. std::this_thread::sleep_for(std::chrono::seconds(2));
  7988. // Recoonect
  7989. result = cli.Get("/hi");
  7990. ASSERT_TRUE(result);
  7991. EXPECT_EQ(StatusCode::OK_200, result->status);
  7992. result = cli.Get("/hi");
  7993. ASSERT_TRUE(result);
  7994. EXPECT_EQ(StatusCode::OK_200, result->status);
  7995. }
  7996. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7998. ASSERT_TRUE(svr.is_valid());
  7999. svr.set_keep_alive_timeout(1);
  8000. std::string content = "reconnect";
  8001. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8002. res.set_content("Hello World!", "text/plain");
  8003. });
  8004. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8005. auto se = detail::scope_exit([&] {
  8006. svr.stop();
  8007. listen_thread.join();
  8008. ASSERT_FALSE(svr.is_running());
  8009. });
  8010. svr.wait_until_ready();
  8011. SSLClient cli(HOST, PORT);
  8012. cli.enable_server_certificate_verification(false);
  8013. cli.set_keep_alive(true);
  8014. auto result = cli.Post(
  8015. "/hi", content.size(),
  8016. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8017. sink.write(content.c_str(), content.size());
  8018. return true;
  8019. },
  8020. "text/plain");
  8021. ASSERT_TRUE(result);
  8022. EXPECT_EQ(200, result->status);
  8023. std::this_thread::sleep_for(std::chrono::seconds(2));
  8024. // Recoonect
  8025. result = cli.Post(
  8026. "/hi", content.size(),
  8027. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8028. sink.write(content.c_str(), content.size());
  8029. return true;
  8030. },
  8031. "text/plain");
  8032. ASSERT_TRUE(result);
  8033. EXPECT_EQ(200, result->status);
  8034. result = cli.Post(
  8035. "/hi", content.size(),
  8036. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8037. sink.write(content.c_str(), content.size());
  8038. return true;
  8039. },
  8040. "text/plain");
  8041. ASSERT_TRUE(result);
  8042. EXPECT_EQ(200, result->status);
  8043. }
  8044. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8045. using namespace httplib::tls;
  8046. {
  8047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8048. ASSERT_TRUE(svr.is_valid());
  8049. svr.Get("/sni", [&](const Request &req, Response &res) {
  8050. std::string expected = req.sni();
  8051. EXPECT_EQ(expected, req.get_param_value("expected"));
  8052. res.set_content("ok", "text/plain");
  8053. });
  8054. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8055. auto se = detail::scope_exit([&] {
  8056. svr.stop();
  8057. listen_thread.join();
  8058. ASSERT_FALSE(svr.is_running());
  8059. });
  8060. svr.wait_until_ready();
  8061. {
  8062. SSLClient cli("localhost", PORT);
  8063. cli.enable_server_certificate_verification(false);
  8064. auto res = cli.Get("/sni?expected=localhost");
  8065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8066. }
  8067. {
  8068. SSLClient cli("::1", PORT);
  8069. cli.enable_server_certificate_verification(false);
  8070. auto res = cli.Get("/sni?expected=");
  8071. // NOTE: This may fail if the server is listening on IPv4 only
  8072. // (e.g., when localhost resolves to 127.0.0.1 only)
  8073. if (res) {
  8074. EXPECT_EQ(StatusCode::OK_200, res->status);
  8075. } else {
  8076. EXPECT_EQ(Error::Connection, res.error());
  8077. }
  8078. }
  8079. }
  8080. }
  8081. #endif
  8082. TEST(ClientProblemDetectionTest, ContentProvider) {
  8083. Server svr;
  8084. size_t content_length = 1024 * 1024;
  8085. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8086. res.set_content_provider(
  8087. content_length, "text/plain",
  8088. [&](size_t offset, size_t length, DataSink &sink) {
  8089. auto out_len = std::min(length, static_cast<size_t>(1024));
  8090. std::string out(out_len, '@');
  8091. sink.write(out.data(), out_len);
  8092. return offset < 4096;
  8093. },
  8094. [](bool success) { ASSERT_FALSE(success); });
  8095. });
  8096. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8097. res.set_content_provider(
  8098. 0, "text/plain",
  8099. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8100. EXPECT_TRUE(false);
  8101. return true;
  8102. },
  8103. [](bool success) { ASSERT_FALSE(success); });
  8104. });
  8105. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8106. auto se = detail::scope_exit([&] {
  8107. svr.stop();
  8108. listen_thread.join();
  8109. ASSERT_FALSE(svr.is_running());
  8110. });
  8111. svr.wait_until_ready();
  8112. Client cli("localhost", PORT);
  8113. {
  8114. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8115. size_t /*data_length*/) { return false; });
  8116. ASSERT_FALSE(res);
  8117. }
  8118. {
  8119. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8120. size_t /*data_length*/) { return false; });
  8121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8122. }
  8123. }
  8124. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8125. Server svr;
  8126. svr.set_error_handler([](Request const &, Response &res) -> void {
  8127. res.set_chunked_content_provider(
  8128. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8129. sink.os << "hello";
  8130. sink.os << "world";
  8131. sink.done();
  8132. return true;
  8133. });
  8134. });
  8135. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8136. auto se = detail::scope_exit([&] {
  8137. svr.stop();
  8138. listen_thread.join();
  8139. ASSERT_FALSE(svr.is_running());
  8140. });
  8141. svr.wait_until_ready();
  8142. Client cli("localhost", PORT);
  8143. auto res = cli.Get("/");
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8146. EXPECT_EQ("helloworld", res->body);
  8147. }
  8148. TEST(LongPollingTest, ClientCloseDetection) {
  8149. Server svr;
  8150. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8151. res.set_chunked_content_provider(
  8152. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8153. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8154. sink.os << "hello";
  8155. auto count = 10;
  8156. while (count > 0 && sink.is_writable()) {
  8157. this_thread::sleep_for(chrono::milliseconds(10));
  8158. count--;
  8159. }
  8160. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8161. return true;
  8162. });
  8163. });
  8164. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8165. auto se = detail::scope_exit([&] {
  8166. svr.stop();
  8167. listen_thread.join();
  8168. ASSERT_FALSE(svr.is_running());
  8169. });
  8170. svr.wait_until_ready();
  8171. Client cli("localhost", PORT);
  8172. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8173. EXPECT_EQ("hello", string(data, data_length));
  8174. return false; // close the socket immediately.
  8175. });
  8176. ASSERT_FALSE(res);
  8177. }
  8178. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8179. Server svr;
  8180. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8181. res.set_chunked_content_provider(
  8182. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8183. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8184. sink.os << "hello";
  8185. EXPECT_TRUE(sink.os.good());
  8186. // Wait for the client to close the connection
  8187. auto count = 10;
  8188. while (count > 0 && sink.is_writable()) {
  8189. this_thread::sleep_for(chrono::milliseconds(10));
  8190. count--;
  8191. }
  8192. // After client disconnect, write repeatedly until the socket
  8193. // write actually fails (small writes may be absorbed by the
  8194. // kernel buffer)
  8195. std::string chunk(1024, 'x');
  8196. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8197. sink.os << chunk;
  8198. }
  8199. EXPECT_TRUE(sink.os.fail());
  8200. return true;
  8201. });
  8202. });
  8203. auto port = svr.bind_to_any_port("localhost");
  8204. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8205. auto se = detail::scope_exit([&] {
  8206. svr.stop();
  8207. listen_thread.join();
  8208. ASSERT_FALSE(svr.is_running());
  8209. });
  8210. svr.wait_until_ready();
  8211. Client cli("localhost", port);
  8212. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8213. EXPECT_EQ("hello", string(data, data_length));
  8214. return false; // close the socket immediately.
  8215. });
  8216. ASSERT_FALSE(res);
  8217. }
  8218. TEST(GetWithParametersTest, GetWithParameters) {
  8219. Server svr;
  8220. svr.Get("/", [&](const Request &req, Response &) {
  8221. EXPECT_EQ("world", req.get_param_value("hello"));
  8222. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8223. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8224. });
  8225. svr.Get("/params", [&](const Request &req, Response &) {
  8226. EXPECT_EQ("world", req.get_param_value("hello"));
  8227. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8228. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8229. });
  8230. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8231. EXPECT_EQ("resource-id", req.matches[1]);
  8232. EXPECT_EQ("foo", req.get_param_value("param1"));
  8233. EXPECT_EQ("bar", req.get_param_value("param2"));
  8234. });
  8235. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8236. EXPECT_EQ("user-id", req.path_params.at("id"));
  8237. EXPECT_EQ("foo", req.get_param_value("param1"));
  8238. EXPECT_EQ("bar", req.get_param_value("param2"));
  8239. });
  8240. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8241. auto se = detail::scope_exit([&] {
  8242. svr.stop();
  8243. listen_thread.join();
  8244. ASSERT_FALSE(svr.is_running());
  8245. });
  8246. svr.wait_until_ready();
  8247. {
  8248. Client cli(HOST, PORT);
  8249. Params params;
  8250. params.emplace("hello", "world");
  8251. params.emplace("hello2", "world2");
  8252. params.emplace("hello3", "world3");
  8253. auto res = cli.Get("/", params, Headers{});
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::OK_200, res->status);
  8256. }
  8257. {
  8258. Client cli(HOST, PORT);
  8259. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. }
  8263. {
  8264. Client cli(HOST, PORT);
  8265. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::OK_200, res->status);
  8268. }
  8269. {
  8270. Client cli(HOST, PORT);
  8271. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. }
  8275. }
  8276. TEST(GetWithParametersTest, GetWithParameters2) {
  8277. Server svr;
  8278. svr.Get("/", [&](const Request &req, Response &res) {
  8279. auto text = req.get_param_value("hello");
  8280. res.set_content(text, "text/plain");
  8281. });
  8282. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8283. auto se = detail::scope_exit([&] {
  8284. svr.stop();
  8285. listen_thread.join();
  8286. ASSERT_FALSE(svr.is_running());
  8287. });
  8288. svr.wait_until_ready();
  8289. Client cli("localhost", PORT);
  8290. Params params;
  8291. params.emplace("hello", "world");
  8292. std::string body;
  8293. auto res = cli.Get("/", params, Headers{},
  8294. [&](const char *data, size_t data_length) {
  8295. body.append(data, data_length);
  8296. return true;
  8297. });
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::OK_200, res->status);
  8300. EXPECT_EQ("world", body);
  8301. }
  8302. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8303. Server svr;
  8304. svr.Get("/search", [&](const Request &req, Response &res) {
  8305. auto q = req.get_param_value("q");
  8306. res.set_content(q, "text/plain");
  8307. });
  8308. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8309. auto se = detail::scope_exit([&] {
  8310. svr.stop();
  8311. listen_thread.join();
  8312. ASSERT_FALSE(svr.is_running());
  8313. });
  8314. svr.wait_until_ready();
  8315. Client cli("localhost", PORT);
  8316. // Verify that Get(path, params) works without requiring Headers argument
  8317. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8319. EXPECT_EQ(StatusCode::OK_200, res->status);
  8320. EXPECT_EQ("cpp-httplib", res->body);
  8321. }
  8322. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8323. auto host = "httpbingo.org";
  8324. auto path = std::string{"/range/32"};
  8325. #ifdef CPPHTTPLIB_SSL_ENABLED
  8326. SSLClient cli(host);
  8327. #else
  8328. Client cli(host);
  8329. #endif
  8330. cli.set_default_headers({make_range_header({{1, 10}})});
  8331. cli.set_connection_timeout(5);
  8332. {
  8333. auto res = cli.Get(path);
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ("bcdefghijk", res->body);
  8336. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8337. }
  8338. {
  8339. auto res = cli.Get(path);
  8340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8341. EXPECT_EQ("bcdefghijk", res->body);
  8342. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8343. }
  8344. }
  8345. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8346. Server svr;
  8347. svr.set_default_headers({{"Hello", "World"}});
  8348. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8349. res.set_content("ok", "text/plain");
  8350. });
  8351. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8352. auto se = detail::scope_exit([&] {
  8353. svr.stop();
  8354. listen_thread.join();
  8355. ASSERT_FALSE(svr.is_running());
  8356. });
  8357. svr.wait_until_ready();
  8358. Client cli("localhost", PORT);
  8359. auto res = cli.Get("/");
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(StatusCode::OK_200, res->status);
  8362. EXPECT_EQ("ok", res->body);
  8363. EXPECT_EQ("World", res->get_header_value("Hello"));
  8364. }
  8365. #ifdef CPPHTTPLIB_SSL_ENABLED
  8366. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8368. ASSERT_TRUE(svr.is_valid());
  8369. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8370. std::this_thread::sleep_for(std::chrono::seconds(2));
  8371. res.set_content("a", "text/plain");
  8372. });
  8373. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8374. res.set_content("b", "text/plain");
  8375. });
  8376. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8377. auto se = detail::scope_exit([&] {
  8378. svr.stop();
  8379. listen_thread.join();
  8380. ASSERT_FALSE(svr.is_running());
  8381. });
  8382. svr.wait_until_ready();
  8383. SSLClient cli("localhost", PORT);
  8384. cli.enable_server_certificate_verification(false);
  8385. cli.set_keep_alive(true);
  8386. cli.set_read_timeout(std::chrono::seconds(1));
  8387. auto resa = cli.Get("/a");
  8388. ASSERT_TRUE(!resa);
  8389. EXPECT_EQ(Error::Read, resa.error());
  8390. auto resb = cli.Get("/b");
  8391. ASSERT_TRUE(resb);
  8392. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8393. EXPECT_EQ("b", resb->body);
  8394. }
  8395. #endif
  8396. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8397. protected:
  8398. ServerTestWithAI_PASSIVE()
  8399. : cli_(HOST, PORT)
  8400. #ifdef CPPHTTPLIB_SSL_ENABLED
  8401. ,
  8402. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8403. #endif
  8404. {
  8405. #ifdef CPPHTTPLIB_SSL_ENABLED
  8406. cli_.enable_server_certificate_verification(false);
  8407. #endif
  8408. }
  8409. virtual void SetUp() {
  8410. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8411. res.set_content("Hello World!", "text/plain");
  8412. });
  8413. t_ = thread(
  8414. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8415. svr_.wait_until_ready();
  8416. }
  8417. virtual void TearDown() {
  8418. svr_.stop();
  8419. t_.join();
  8420. }
  8421. #ifdef CPPHTTPLIB_SSL_ENABLED
  8422. SSLClient cli_;
  8423. SSLServer svr_;
  8424. #else
  8425. Client cli_;
  8426. Server svr_;
  8427. #endif
  8428. thread t_;
  8429. };
  8430. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8431. auto res = cli_.Get("/hi");
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. EXPECT_EQ(StatusCode::OK_200, res->status);
  8434. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8435. EXPECT_EQ("Hello World!", res->body);
  8436. }
  8437. class ServerUpDownTest : public ::testing::Test {
  8438. protected:
  8439. ServerUpDownTest() : cli_(HOST, PORT) {}
  8440. virtual void SetUp() {
  8441. t_ = thread([&]() {
  8442. svr_.bind_to_any_port(HOST);
  8443. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8444. ASSERT_TRUE(svr_.listen_after_bind());
  8445. });
  8446. svr_.wait_until_ready();
  8447. }
  8448. virtual void TearDown() {
  8449. svr_.stop();
  8450. t_.join();
  8451. }
  8452. Client cli_;
  8453. Server svr_;
  8454. thread t_;
  8455. };
  8456. TEST_F(ServerUpDownTest, QuickStartStop) {
  8457. // Should not crash, especially when run with
  8458. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8459. }
  8460. class PayloadMaxLengthTest : public ::testing::Test {
  8461. protected:
  8462. PayloadMaxLengthTest()
  8463. : cli_(HOST, PORT)
  8464. #ifdef CPPHTTPLIB_SSL_ENABLED
  8465. ,
  8466. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8467. #endif
  8468. {
  8469. #ifdef CPPHTTPLIB_SSL_ENABLED
  8470. cli_.enable_server_certificate_verification(false);
  8471. #endif
  8472. }
  8473. virtual void SetUp() {
  8474. svr_.set_payload_max_length(8);
  8475. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8476. res.set_content("test", "text/plain");
  8477. });
  8478. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8479. svr_.wait_until_ready();
  8480. }
  8481. virtual void TearDown() {
  8482. svr_.stop();
  8483. t_.join();
  8484. }
  8485. #ifdef CPPHTTPLIB_SSL_ENABLED
  8486. SSLClient cli_;
  8487. SSLServer svr_;
  8488. #else
  8489. Client cli_;
  8490. Server svr_;
  8491. #endif
  8492. thread t_;
  8493. };
  8494. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8495. auto res = cli_.Post("/test", "123456789", "text/plain");
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8498. res = cli_.Post("/test", "12345678", "text/plain");
  8499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8500. EXPECT_EQ(StatusCode::OK_200, res->status);
  8501. }
  8502. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8503. // Test chunked encoding with payload exceeding the 8-byte limit
  8504. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8505. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8508. }
  8509. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8510. // Test chunked encoding with payload within the 8-byte limit
  8511. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8512. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8517. // Test using send_request to send chunked data exceeding payload limit
  8518. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8519. "Host: " +
  8520. std::string(HOST) + ":" + std::to_string(PORT) +
  8521. "\r\n"
  8522. "Transfer-Encoding: chunked\r\n"
  8523. "Connection: close\r\n"
  8524. "\r\n"
  8525. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8526. "0123456789\r\n"
  8527. "0\r\n" // End chunk
  8528. "\r\n";
  8529. std::string response;
  8530. bool result = send_request(1, chunked_request, &response);
  8531. if (!result) {
  8532. // If send_request fails, it might be because the server closed the
  8533. // connection due to payload limit enforcement, which is acceptable
  8534. SUCCEED()
  8535. << "Server rejected oversized chunked request (connection closed)";
  8536. } else {
  8537. // If we got a response, check if it's an error response or connection was
  8538. // closed early Short response length indicates connection was closed due to
  8539. // payload limit
  8540. if (response.length() <= 10) {
  8541. SUCCEED() << "Server closed connection for oversized chunked request";
  8542. } else {
  8543. // Check for error status codes
  8544. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8545. response.find("Payload Too Large") != std::string::npos ||
  8546. response.find("400") != std::string::npos);
  8547. }
  8548. }
  8549. }
  8550. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8551. // Test request without Content-Length header exceeding payload limit
  8552. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8553. "Host: " +
  8554. std::string(HOST) + ":" +
  8555. std::to_string(PORT) +
  8556. "\r\n"
  8557. "Connection: close\r\n"
  8558. "\r\n";
  8559. // Add payload exceeding the 8-byte limit
  8560. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8561. request_without_content_length += large_payload;
  8562. std::string response;
  8563. bool result = send_request(1, request_without_content_length, &response);
  8564. if (!result) {
  8565. // If send_request fails, server likely closed connection due to payload
  8566. // limit
  8567. SUCCEED() << "Server rejected oversized request without Content-Length "
  8568. "(connection closed)";
  8569. } else {
  8570. // Check if server responded with error or closed connection early
  8571. if (response.length() <= 10) {
  8572. SUCCEED() << "Server closed connection for oversized request without "
  8573. "Content-Length";
  8574. } else {
  8575. // Check for error status codes
  8576. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8577. response.find("Payload Too Large") != std::string::npos ||
  8578. response.find("400") != std::string::npos);
  8579. }
  8580. }
  8581. }
  8582. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8583. // Test request without Content-Length header within payload limit
  8584. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8585. "Host: " +
  8586. std::string(HOST) + ":" +
  8587. std::to_string(PORT) +
  8588. "\r\n"
  8589. "Connection: close\r\n"
  8590. "\r\n";
  8591. // Add payload within the 8-byte limit
  8592. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8593. request_without_content_length += small_payload;
  8594. std::string response;
  8595. bool result = send_request(1, request_without_content_length, &response);
  8596. // For requests without Content-Length, the server may have different behavior
  8597. // The key is that it should not reject due to payload limit for small
  8598. // payloads
  8599. if (result) {
  8600. // Check for any HTTP response (success or error, but not connection closed)
  8601. if (response.length() > 10) {
  8602. SUCCEED()
  8603. << "Server processed request without Content-Length within limit";
  8604. } else {
  8605. // Short response might indicate connection closed, which is acceptable
  8606. SUCCEED() << "Server closed connection for request without "
  8607. "Content-Length (acceptable behavior)";
  8608. }
  8609. } else {
  8610. // Connection failure might be due to protocol requirements
  8611. SUCCEED() << "Connection issue with request without Content-Length "
  8612. "(environment-specific)";
  8613. }
  8614. }
  8615. class LargePayloadMaxLengthTest : public ::testing::Test {
  8616. protected:
  8617. LargePayloadMaxLengthTest()
  8618. : cli_(HOST, PORT)
  8619. #ifdef CPPHTTPLIB_SSL_ENABLED
  8620. ,
  8621. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8622. #endif
  8623. {
  8624. #ifdef CPPHTTPLIB_SSL_ENABLED
  8625. cli_.enable_server_certificate_verification(false);
  8626. #endif
  8627. }
  8628. virtual void SetUp() {
  8629. // Set 10MB payload limit
  8630. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8631. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8632. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8633. res.set_content("Large payload test", "text/plain");
  8634. });
  8635. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8636. svr_.wait_until_ready();
  8637. }
  8638. virtual void TearDown() {
  8639. svr_.stop();
  8640. t_.join();
  8641. }
  8642. #ifdef CPPHTTPLIB_SSL_ENABLED
  8643. SSLClient cli_;
  8644. SSLServer svr_;
  8645. #else
  8646. Client cli_;
  8647. Server svr_;
  8648. #endif
  8649. thread t_;
  8650. };
  8651. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8652. // Test chunked encoding with payload within 10MB limit
  8653. std::string medium_payload(5 * 1024 * 1024,
  8654. 'A'); // 5MB payload, within 10MB limit
  8655. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8657. EXPECT_EQ(StatusCode::OK_200, res->status);
  8658. }
  8659. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8660. // Test chunked encoding with payload exceeding 10MB limit
  8661. std::string large_payload(12 * 1024 * 1024,
  8662. 'B'); // 12MB payload, exceeds 10MB limit
  8663. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8664. // Server may either return 413 or close the connection
  8665. if (res) {
  8666. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8667. } else {
  8668. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8669. }
  8670. }
  8671. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8672. // Test request without Content-Length header within 10MB limit
  8673. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8674. "Host: " +
  8675. std::string(HOST) + ":" +
  8676. std::to_string(PORT) +
  8677. "\r\n"
  8678. "Connection: close\r\n"
  8679. "\r\n";
  8680. // Add 1MB payload (within 10MB limit)
  8681. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8682. request_without_content_length += medium_payload;
  8683. std::string response;
  8684. bool result = send_request(5, request_without_content_length, &response);
  8685. if (result) {
  8686. // Should get a proper HTTP response for payloads within limit
  8687. if (response.length() > 10) {
  8688. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8689. "10MB limit";
  8690. } else {
  8691. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8692. "Content-Length)";
  8693. }
  8694. } else {
  8695. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8696. }
  8697. }
  8698. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8699. // Test request without Content-Length header exceeding 10MB limit
  8700. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8701. "Host: " +
  8702. std::string(HOST) + ":" +
  8703. std::to_string(PORT) +
  8704. "\r\n"
  8705. "Connection: close\r\n"
  8706. "\r\n";
  8707. // Add 12MB payload (exceeds 10MB limit)
  8708. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8709. request_without_content_length += large_payload;
  8710. std::string response;
  8711. bool result = send_request(10, request_without_content_length, &response);
  8712. if (!result) {
  8713. // Server should close connection due to payload limit
  8714. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8715. "(connection closed)";
  8716. } else {
  8717. // Check for error response
  8718. if (response.length() <= 10) {
  8719. SUCCEED()
  8720. << "Server closed connection for 12MB request exceeding 10MB limit";
  8721. } else {
  8722. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8723. response.find("Payload Too Large") != std::string::npos ||
  8724. response.find("400") != std::string::npos);
  8725. }
  8726. }
  8727. }
  8728. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8729. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8730. // path.
  8731. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8732. Server svr;
  8733. const size_t LIMIT = 64 * 1024; // 64KB
  8734. svr.set_payload_max_length(LIMIT);
  8735. size_t total = 0;
  8736. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8737. const ContentReader &content_reader) {
  8738. content_reader([&](const char * /*data*/, size_t len) {
  8739. total += len;
  8740. return true;
  8741. });
  8742. res.status = 200;
  8743. res.set_content("stream_ok", "text/plain");
  8744. });
  8745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8746. auto se = detail::scope_exit([&] {
  8747. svr.stop();
  8748. thread.join();
  8749. ASSERT_FALSE(svr.is_running());
  8750. });
  8751. svr.wait_until_ready();
  8752. // Prepare 256KB raw data and gzip-compress it
  8753. std::string raw(256 * 1024, 'A');
  8754. std::string gz;
  8755. {
  8756. z_stream zs{};
  8757. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8758. Z_DEFAULT_STRATEGY);
  8759. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8760. zs.avail_in = static_cast<uInt>(raw.size());
  8761. char outbuf[4096];
  8762. int ret;
  8763. do {
  8764. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8765. zs.avail_out = sizeof(outbuf);
  8766. ret = deflate(&zs, Z_FINISH);
  8767. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8768. } while (ret != Z_STREAM_END);
  8769. deflateEnd(&zs);
  8770. }
  8771. Client cli(HOST, PORT);
  8772. cli.set_connection_timeout(std::chrono::seconds(5));
  8773. Headers headers = {{"Content-Encoding", "gzip"}};
  8774. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8775. "application/octet-stream");
  8776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8777. // Server must reject oversized decompressed payloads with 413.
  8778. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8779. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8780. EXPECT_LE(total, LIMIT);
  8781. }
  8782. #endif
  8783. // Regression test for DoS vulnerability: a malicious server sending a response
  8784. // without Content-Length header must not cause unbounded memory consumption on
  8785. // the client side. The client should stop reading after a reasonable limit,
  8786. // similar to the server-side set_payload_max_length protection.
  8787. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8788. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8789. #ifndef _WIN32
  8790. signal(SIGPIPE, SIG_IGN);
  8791. #endif
  8792. auto server_thread = std::thread([] {
  8793. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8794. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8795. default_socket_options(srv);
  8796. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8797. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8798. sockaddr_in addr{};
  8799. addr.sin_family = AF_INET;
  8800. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8801. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8802. int opt = 1;
  8803. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8804. #ifdef _WIN32
  8805. reinterpret_cast<const char *>(&opt),
  8806. #else
  8807. &opt,
  8808. #endif
  8809. sizeof(opt));
  8810. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8811. ::listen(srv, 1);
  8812. sockaddr_in cli_addr{};
  8813. socklen_t cli_len = sizeof(cli_addr);
  8814. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8815. if (cli != INVALID_SOCKET) {
  8816. char buf[4096];
  8817. ::recv(cli, buf, sizeof(buf), 0);
  8818. // Malicious response: no Content-Length, no chunked encoding
  8819. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8820. "Connection: close\r\n"
  8821. "\r\n";
  8822. ::send(cli,
  8823. #ifdef _WIN32
  8824. static_cast<const char *>(response_header.c_str()),
  8825. static_cast<int>(response_header.size()),
  8826. #else
  8827. response_header.c_str(), response_header.size(),
  8828. #endif
  8829. 0);
  8830. // Send 10MB of data
  8831. std::string chunk(64 * 1024, 'A');
  8832. size_t total_sent = 0;
  8833. while (total_sent < MALICIOUS_DATA_SIZE) {
  8834. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8835. auto sent = ::send(cli,
  8836. #ifdef _WIN32
  8837. static_cast<const char *>(chunk.c_str()),
  8838. static_cast<int>(to_send),
  8839. #else
  8840. chunk.c_str(), to_send,
  8841. #endif
  8842. 0);
  8843. if (sent <= 0) break;
  8844. total_sent += static_cast<size_t>(sent);
  8845. }
  8846. detail::close_socket(cli);
  8847. }
  8848. detail::close_socket(srv);
  8849. });
  8850. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8851. size_t total_read = 0;
  8852. {
  8853. Client cli("127.0.0.1", PORT + 2);
  8854. cli.set_read_timeout(5, 0);
  8855. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8856. auto stream = cli.open_stream("GET", "/malicious");
  8857. ASSERT_TRUE(stream.is_valid());
  8858. char buffer[64 * 1024];
  8859. ssize_t n;
  8860. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8861. total_read += static_cast<size_t>(n);
  8862. }
  8863. } // StreamHandle and Client destroyed here, closing the socket
  8864. server_thread.join();
  8865. // With set_payload_max_length, the client must stop reading before consuming
  8866. // all 10MB. The read loop should be cut off at or near the configured limit.
  8867. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8868. << "Client read " << total_read << " bytes, exceeding the configured "
  8869. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8870. }
  8871. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8872. // the entire response body without truncation.
  8873. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8874. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8875. #ifndef _WIN32
  8876. signal(SIGPIPE, SIG_IGN);
  8877. #endif
  8878. auto server_thread = std::thread([] {
  8879. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8880. default_socket_options(srv);
  8881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8882. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8883. sockaddr_in addr{};
  8884. addr.sin_family = AF_INET;
  8885. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8886. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8887. int opt = 1;
  8888. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8889. #ifdef _WIN32
  8890. reinterpret_cast<const char *>(&opt),
  8891. #else
  8892. &opt,
  8893. #endif
  8894. sizeof(opt));
  8895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8896. ::listen(srv, 1);
  8897. sockaddr_in cli_addr{};
  8898. socklen_t cli_len = sizeof(cli_addr);
  8899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8900. if (cli != INVALID_SOCKET) {
  8901. char buf[4096];
  8902. ::recv(cli, buf, sizeof(buf), 0);
  8903. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8904. "Connection: close\r\n"
  8905. "\r\n";
  8906. ::send(cli,
  8907. #ifdef _WIN32
  8908. static_cast<const char *>(response_header.c_str()),
  8909. static_cast<int>(response_header.size()),
  8910. #else
  8911. response_header.c_str(), response_header.size(),
  8912. #endif
  8913. 0);
  8914. std::string chunk(64 * 1024, 'A');
  8915. size_t total_sent = 0;
  8916. while (total_sent < DATA_SIZE) {
  8917. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8918. auto sent = ::send(cli,
  8919. #ifdef _WIN32
  8920. static_cast<const char *>(chunk.c_str()),
  8921. static_cast<int>(to_send),
  8922. #else
  8923. chunk.c_str(), to_send,
  8924. #endif
  8925. 0);
  8926. if (sent <= 0) break;
  8927. total_sent += static_cast<size_t>(sent);
  8928. }
  8929. #ifdef _WIN32
  8930. ::shutdown(cli, SD_SEND);
  8931. #else
  8932. ::shutdown(cli, SHUT_WR);
  8933. #endif
  8934. // Drain until the client closes its end, ensuring all data is delivered
  8935. char drain[1024];
  8936. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8937. detail::close_socket(cli);
  8938. }
  8939. detail::close_socket(srv);
  8940. });
  8941. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8942. size_t total_read = 0;
  8943. {
  8944. Client cli("127.0.0.1", PORT + 2);
  8945. cli.set_read_timeout(5, 0);
  8946. cli.set_payload_max_length(0); // 0 means no limit
  8947. auto stream = cli.open_stream("GET", "/data");
  8948. ASSERT_TRUE(stream.is_valid());
  8949. char buffer[64 * 1024];
  8950. ssize_t n;
  8951. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8952. total_read += static_cast<size_t>(n);
  8953. }
  8954. }
  8955. server_thread.join();
  8956. EXPECT_EQ(total_read, DATA_SIZE)
  8957. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8958. << " bytes without truncation, but only read " << total_read << " bytes.";
  8959. }
  8960. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8961. // enormous Content-Length must not cause the client to pre-allocate a huge
  8962. // response body buffer. The reservation is capped at payload_max_length_, and
  8963. // the read itself fails when the body exceeds the limit.
  8964. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8965. #ifndef _WIN32
  8966. signal(SIGPIPE, SIG_IGN);
  8967. #endif
  8968. auto server_thread = std::thread([] {
  8969. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8970. default_socket_options(srv);
  8971. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8972. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8973. sockaddr_in addr{};
  8974. addr.sin_family = AF_INET;
  8975. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8976. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8977. int opt = 1;
  8978. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8979. #ifdef _WIN32
  8980. reinterpret_cast<const char *>(&opt),
  8981. #else
  8982. &opt,
  8983. #endif
  8984. sizeof(opt));
  8985. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8986. ::listen(srv, 1);
  8987. sockaddr_in cli_addr{};
  8988. socklen_t cli_len = sizeof(cli_addr);
  8989. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8990. if (cli != INVALID_SOCKET) {
  8991. char buf[4096];
  8992. ::recv(cli, buf, sizeof(buf), 0);
  8993. // Malicious response: claim a 20GB body but send only a tiny payload.
  8994. std::string response = "HTTP/1.1 200 OK\r\n"
  8995. "Content-Length: 20000000000\r\n"
  8996. "\r\n"
  8997. "abc";
  8998. ::send(cli,
  8999. #ifdef _WIN32
  9000. static_cast<const char *>(response.c_str()),
  9001. static_cast<int>(response.size()),
  9002. #else
  9003. response.c_str(), response.size(),
  9004. #endif
  9005. 0);
  9006. detail::close_socket(cli);
  9007. }
  9008. detail::close_socket(srv);
  9009. });
  9010. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9011. {
  9012. Client cli("127.0.0.1", PORT + 2);
  9013. cli.set_read_timeout(5, 0);
  9014. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9015. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9016. // (server claims more bytes than payload_max_length permits), but it must
  9017. // not exhaust memory before getting there.
  9018. auto res = cli.Get("/malicious");
  9019. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9020. }
  9021. server_thread.join();
  9022. }
  9023. // Verify that content_receiver bypasses the default payload_max_length,
  9024. // allowing streaming downloads larger than 100MB without requiring an explicit
  9025. // set_payload_max_length call.
  9026. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9027. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9028. #ifndef _WIN32
  9029. signal(SIGPIPE, SIG_IGN);
  9030. #endif
  9031. auto server_thread = std::thread([] {
  9032. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9033. default_socket_options(srv);
  9034. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9035. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9036. sockaddr_in addr{};
  9037. addr.sin_family = AF_INET;
  9038. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9039. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9040. int opt = 1;
  9041. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9042. #ifdef _WIN32
  9043. reinterpret_cast<const char *>(&opt),
  9044. #else
  9045. &opt,
  9046. #endif
  9047. sizeof(opt));
  9048. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9049. ::listen(srv, 1);
  9050. sockaddr_in cli_addr{};
  9051. socklen_t cli_len = sizeof(cli_addr);
  9052. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9053. if (cli != INVALID_SOCKET) {
  9054. char buf[4096];
  9055. ::recv(cli, buf, sizeof(buf), 0);
  9056. // Response with Content-Length larger than default 100MB limit
  9057. auto content_length = std::to_string(DATA_SIZE);
  9058. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9059. "Content-Length: " +
  9060. content_length +
  9061. "\r\n"
  9062. "Connection: close\r\n"
  9063. "\r\n";
  9064. ::send(cli,
  9065. #ifdef _WIN32
  9066. static_cast<const char *>(response_header.c_str()),
  9067. static_cast<int>(response_header.size()),
  9068. #else
  9069. response_header.c_str(), response_header.size(),
  9070. #endif
  9071. 0);
  9072. std::string chunk(64 * 1024, 'A');
  9073. size_t total_sent = 0;
  9074. while (total_sent < DATA_SIZE) {
  9075. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9076. auto sent = ::send(cli,
  9077. #ifdef _WIN32
  9078. static_cast<const char *>(chunk.c_str()),
  9079. static_cast<int>(to_send),
  9080. #else
  9081. chunk.c_str(), to_send,
  9082. #endif
  9083. 0);
  9084. if (sent <= 0) break;
  9085. total_sent += static_cast<size_t>(sent);
  9086. }
  9087. detail::close_socket(cli);
  9088. }
  9089. detail::close_socket(srv);
  9090. });
  9091. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9092. size_t total_received = 0;
  9093. {
  9094. Client cli("127.0.0.1", PORT + 2);
  9095. cli.set_read_timeout(10, 0);
  9096. // Do NOT call set_payload_max_length — use the default 100MB limit
  9097. auto res =
  9098. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9099. total_received += data_length;
  9100. return true;
  9101. });
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ(StatusCode::OK_200, res->status);
  9104. }
  9105. server_thread.join();
  9106. EXPECT_EQ(total_received, DATA_SIZE)
  9107. << "With content_receiver, the client should read all " << DATA_SIZE
  9108. << " bytes despite the default 100MB payload_max_length, but only read "
  9109. << total_received << " bytes.";
  9110. }
  9111. // Verify that an explicit set_payload_max_length smaller than the response is
  9112. // enforced even when a content_receiver is used.
  9113. TEST(ClientVulnerabilityTest,
  9114. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9115. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9116. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9117. #ifndef _WIN32
  9118. signal(SIGPIPE, SIG_IGN);
  9119. #endif
  9120. auto server_thread = std::thread([] {
  9121. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9122. default_socket_options(srv);
  9123. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9124. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9125. sockaddr_in addr{};
  9126. addr.sin_family = AF_INET;
  9127. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9128. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9129. int opt = 1;
  9130. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9131. #ifdef _WIN32
  9132. reinterpret_cast<const char *>(&opt),
  9133. #else
  9134. &opt,
  9135. #endif
  9136. sizeof(opt));
  9137. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9138. ::listen(srv, 1);
  9139. sockaddr_in cli_addr{};
  9140. socklen_t cli_len = sizeof(cli_addr);
  9141. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9142. if (cli != INVALID_SOCKET) {
  9143. char buf[4096];
  9144. ::recv(cli, buf, sizeof(buf), 0);
  9145. auto content_length = std::to_string(DATA_SIZE);
  9146. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9147. "Content-Length: " +
  9148. content_length +
  9149. "\r\n"
  9150. "Connection: close\r\n"
  9151. "\r\n";
  9152. ::send(cli,
  9153. #ifdef _WIN32
  9154. static_cast<const char *>(response_header.c_str()),
  9155. static_cast<int>(response_header.size()),
  9156. #else
  9157. response_header.c_str(), response_header.size(),
  9158. #endif
  9159. 0);
  9160. std::string chunk(64 * 1024, 'A');
  9161. size_t total_sent = 0;
  9162. while (total_sent < DATA_SIZE) {
  9163. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9164. auto sent = ::send(cli,
  9165. #ifdef _WIN32
  9166. static_cast<const char *>(chunk.c_str()),
  9167. static_cast<int>(to_send),
  9168. #else
  9169. chunk.c_str(), to_send,
  9170. #endif
  9171. 0);
  9172. if (sent <= 0) break;
  9173. total_sent += static_cast<size_t>(sent);
  9174. }
  9175. detail::close_socket(cli);
  9176. }
  9177. detail::close_socket(srv);
  9178. });
  9179. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9180. size_t total_received = 0;
  9181. {
  9182. Client cli("127.0.0.1", PORT + 2);
  9183. cli.set_read_timeout(10, 0);
  9184. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9185. auto res =
  9186. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9187. total_received += data_length;
  9188. return true;
  9189. });
  9190. // Should fail because 200MB exceeds the explicit 150MB limit
  9191. EXPECT_FALSE(res);
  9192. }
  9193. server_thread.join();
  9194. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9195. << "Client with content_receiver should respect the explicit "
  9196. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9197. << total_received << " bytes.";
  9198. }
  9199. // Verify that an explicit set_payload_max_length larger than the response
  9200. // allows the content_receiver to read all data successfully.
  9201. TEST(ClientVulnerabilityTest,
  9202. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9203. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9204. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9205. #ifndef _WIN32
  9206. signal(SIGPIPE, SIG_IGN);
  9207. #endif
  9208. auto server_thread = std::thread([] {
  9209. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9210. default_socket_options(srv);
  9211. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9212. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9213. sockaddr_in addr{};
  9214. addr.sin_family = AF_INET;
  9215. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9216. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9217. int opt = 1;
  9218. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9219. #ifdef _WIN32
  9220. reinterpret_cast<const char *>(&opt),
  9221. #else
  9222. &opt,
  9223. #endif
  9224. sizeof(opt));
  9225. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9226. ::listen(srv, 1);
  9227. sockaddr_in cli_addr{};
  9228. socklen_t cli_len = sizeof(cli_addr);
  9229. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9230. if (cli != INVALID_SOCKET) {
  9231. char buf[4096];
  9232. ::recv(cli, buf, sizeof(buf), 0);
  9233. auto content_length = std::to_string(DATA_SIZE);
  9234. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9235. "Content-Length: " +
  9236. content_length +
  9237. "\r\n"
  9238. "Connection: close\r\n"
  9239. "\r\n";
  9240. ::send(cli,
  9241. #ifdef _WIN32
  9242. static_cast<const char *>(response_header.c_str()),
  9243. static_cast<int>(response_header.size()),
  9244. #else
  9245. response_header.c_str(), response_header.size(),
  9246. #endif
  9247. 0);
  9248. std::string chunk(64 * 1024, 'A');
  9249. size_t total_sent = 0;
  9250. while (total_sent < DATA_SIZE) {
  9251. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9252. auto sent = ::send(cli,
  9253. #ifdef _WIN32
  9254. static_cast<const char *>(chunk.c_str()),
  9255. static_cast<int>(to_send),
  9256. #else
  9257. chunk.c_str(), to_send,
  9258. #endif
  9259. 0);
  9260. if (sent <= 0) break;
  9261. total_sent += static_cast<size_t>(sent);
  9262. }
  9263. #ifdef _WIN32
  9264. ::shutdown(cli, SD_SEND);
  9265. #else
  9266. ::shutdown(cli, SHUT_WR);
  9267. #endif
  9268. char drain[1024];
  9269. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9270. detail::close_socket(cli);
  9271. }
  9272. detail::close_socket(srv);
  9273. });
  9274. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9275. size_t total_received = 0;
  9276. {
  9277. Client cli("127.0.0.1", PORT + 2);
  9278. cli.set_read_timeout(10, 0);
  9279. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9280. auto res =
  9281. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9282. total_received += data_length;
  9283. return true;
  9284. });
  9285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9286. EXPECT_EQ(StatusCode::OK_200, res->status);
  9287. }
  9288. server_thread.join();
  9289. EXPECT_EQ(total_received, DATA_SIZE)
  9290. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9291. << " bytes (larger than " << DATA_SIZE
  9292. << " bytes response), content_receiver should read all data, but only "
  9293. "read "
  9294. << total_received << " bytes.";
  9295. }
  9296. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9297. // Regression test for "zip bomb" attack on the client side: a malicious server
  9298. // sends a small gzip-compressed response that decompresses to a huge payload.
  9299. // The client must enforce payload_max_length on the decompressed size.
  9300. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9301. constexpr size_t DECOMPRESSED_SIZE =
  9302. 10 * 1024 * 1024; // 10MB after decompression
  9303. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9304. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9305. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9306. std::string compressed;
  9307. {
  9308. httplib::detail::gzip_compressor compressor;
  9309. bool ok =
  9310. compressor.compress(uncompressed.data(), uncompressed.size(),
  9311. /*last=*/true, [&](const char *buf, size_t len) {
  9312. compressed.append(buf, len);
  9313. return true;
  9314. });
  9315. ASSERT_TRUE(ok);
  9316. }
  9317. // Sanity: compressed data should be much smaller than the decompressed size
  9318. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9319. #ifndef _WIN32
  9320. signal(SIGPIPE, SIG_IGN);
  9321. #endif
  9322. // Set up the listening socket in the main thread so the server is guaranteed
  9323. // to be ready before the client connects (eliminates race condition).
  9324. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9325. default_socket_options(srv);
  9326. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9327. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9328. sockaddr_in addr{};
  9329. addr.sin_family = AF_INET;
  9330. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9331. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9332. int opt = 1;
  9333. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9334. #ifdef _WIN32
  9335. reinterpret_cast<const char *>(&opt),
  9336. #else
  9337. &opt,
  9338. #endif
  9339. sizeof(opt));
  9340. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9341. ASSERT_EQ(0, ::listen(srv, 1));
  9342. auto server_thread = std::thread([&compressed, srv] {
  9343. sockaddr_in cli_addr{};
  9344. socklen_t cli_len = sizeof(cli_addr);
  9345. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9346. if (cli != INVALID_SOCKET) {
  9347. // Read the full HTTP request (until \r\n\r\n)
  9348. char buf[4096];
  9349. size_t total = 0;
  9350. while (total < sizeof(buf)) {
  9351. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9352. if (n <= 0) break;
  9353. total += static_cast<size_t>(n);
  9354. // Check for end of headers
  9355. if (total >= 4) {
  9356. std::string req(buf, total);
  9357. if (req.find("\r\n\r\n") != std::string::npos) break;
  9358. }
  9359. }
  9360. // Malicious response: gzip-compressed body, no Content-Length
  9361. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9362. "Content-Encoding: gzip\r\n"
  9363. "Connection: close\r\n"
  9364. "\r\n";
  9365. ::send(cli,
  9366. #ifdef _WIN32
  9367. static_cast<const char *>(response_header.c_str()),
  9368. static_cast<int>(response_header.size()),
  9369. #else
  9370. response_header.c_str(), response_header.size(),
  9371. #endif
  9372. 0);
  9373. // Send the compressed payload (small on the wire, huge when decompressed)
  9374. size_t total_sent = 0;
  9375. while (total_sent < compressed.size()) {
  9376. auto to_send = std::min(compressed.size() - total_sent,
  9377. static_cast<size_t>(64 * 1024));
  9378. auto sent =
  9379. ::send(cli,
  9380. #ifdef _WIN32
  9381. static_cast<const char *>(compressed.c_str() + total_sent),
  9382. static_cast<int>(to_send),
  9383. #else
  9384. compressed.c_str() + total_sent, to_send,
  9385. #endif
  9386. 0);
  9387. if (sent <= 0) break;
  9388. total_sent += static_cast<size_t>(sent);
  9389. }
  9390. detail::close_socket(cli);
  9391. }
  9392. });
  9393. auto se = detail::scope_exit([&] {
  9394. detail::close_socket(srv);
  9395. server_thread.join();
  9396. });
  9397. size_t total_decompressed = 0;
  9398. {
  9399. Client cli("127.0.0.1", PORT + 3);
  9400. cli.set_read_timeout(5, 0);
  9401. cli.set_decompress(true);
  9402. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9403. auto stream = cli.open_stream("GET", "/zipbomb");
  9404. ASSERT_TRUE(stream.is_valid());
  9405. char buffer[64 * 1024];
  9406. ssize_t n;
  9407. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9408. total_decompressed += static_cast<size_t>(n);
  9409. }
  9410. }
  9411. // The decompressed size must be capped by payload_max_length. Without
  9412. // protection, the client would decompress the full 10MB from a tiny
  9413. // compressed payload, enabling a zip bomb DoS attack.
  9414. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9415. << "Client decompressed " << total_decompressed
  9416. << " bytes from a gzip response. The decompressed size should be "
  9417. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9418. }
  9419. #endif
  9420. TEST(HostAndPortPropertiesTest, NoSSL) {
  9421. httplib::Client cli("www.google.com", 1234);
  9422. ASSERT_EQ("www.google.com", cli.host());
  9423. ASSERT_EQ(1234, cli.port());
  9424. }
  9425. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9426. httplib::Client cli("www.google.com:1234");
  9427. ASSERT_EQ("www.google.com", cli.host());
  9428. ASSERT_EQ(1234, cli.port());
  9429. }
  9430. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9431. // Port number that overflows int — should not crash, client becomes invalid
  9432. httplib::Client cli("http://www.google.com:99999999999999999999");
  9433. ASSERT_FALSE(cli.is_valid());
  9434. }
  9435. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9436. // Port 99999 exceeds valid range (1-65535) — should not crash
  9437. httplib::Client cli("http://www.google.com:99999");
  9438. ASSERT_FALSE(cli.is_valid());
  9439. }
  9440. #ifdef CPPHTTPLIB_SSL_ENABLED
  9441. TEST(HostAndPortPropertiesTest, SSL) {
  9442. httplib::SSLClient cli("www.google.com");
  9443. ASSERT_EQ("www.google.com", cli.host());
  9444. ASSERT_EQ(443, cli.port());
  9445. }
  9446. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9447. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9448. std::string cert;
  9449. read_file(CA_CERT_FILE, cert);
  9450. httplib::SSLClient httplib_client("www.google.com");
  9451. // Load CA store first time
  9452. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9453. // Load CA store second time (update)
  9454. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9455. // Verify client is still valid and can make connections
  9456. httplib_client.enable_server_certificate_verification(true);
  9457. auto res = httplib_client.Get("/");
  9458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9459. // Google may return 200 or 301 depending on various factors
  9460. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9461. res->status == StatusCode::MovedPermanently_301);
  9462. }
  9463. TEST(SSLClientTest, ServerNameIndication_Online) {
  9464. auto host = "httpbingo.org";
  9465. auto path = std::string{"/get"};
  9466. SSLClient cli(host, 443);
  9467. auto res = cli.Get(path);
  9468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9469. ASSERT_EQ(StatusCode::OK_200, res->status);
  9470. }
  9471. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9472. // Use a site that will cause SSL verification failure due to self-signed cert
  9473. SSLClient cli("self-signed.badssl.com", 443);
  9474. cli.enable_server_certificate_verification(true);
  9475. auto res = cli.Get("/");
  9476. ASSERT_TRUE(!res);
  9477. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9478. // Verify backend error is captured for SSLServerVerification
  9479. // This occurs when certificate verification fails
  9480. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9481. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9482. EXPECT_NE(0UL, res.ssl_backend_error());
  9483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9484. // For OpenSSL, ssl_error is 0 for verification errors
  9485. EXPECT_EQ(0, res.ssl_error());
  9486. #if !defined(_WIN32) || \
  9487. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9488. // On non-Windows or when Windows Schannel is disabled, the error comes
  9489. // from OpenSSL's verification
  9490. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9491. res.ssl_backend_error());
  9492. #endif
  9493. #endif
  9494. }
  9495. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9496. // Use a site where hostname doesn't match the certificate
  9497. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9498. SSLClient cli("wrong.host.badssl.com", 443);
  9499. cli.enable_server_certificate_verification(true);
  9500. cli.enable_server_hostname_verification(true);
  9501. auto res = cli.Get("/");
  9502. ASSERT_TRUE(!res);
  9503. // The error type depends on when hostname verification occurs:
  9504. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9505. // - Mbed TLS: SSLServerVerification (during handshake)
  9506. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9507. res.error() == Error::SSLServerVerification);
  9508. // Verify backend error is captured for hostname verification failure
  9509. EXPECT_NE(0UL, res.ssl_backend_error());
  9510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9511. // For OpenSSL, ssl_error is 0 for verification errors
  9512. EXPECT_EQ(0, res.ssl_error());
  9513. #if !defined(_WIN32) || \
  9514. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9515. // On non-Windows or when Windows Schannel is disabled, the error comes
  9516. // from OpenSSL's hostname verification
  9517. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9518. res.ssl_backend_error());
  9519. #endif
  9520. #endif
  9521. }
  9522. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9523. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9524. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9525. SSLClient cli("www.google.com", 443);
  9526. cli.enable_server_certificate_verification(true);
  9527. auto res = cli.Get("/");
  9528. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9529. }
  9530. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9531. SSLClient cli("www.google.com", 443);
  9532. cli.enable_server_certificate_verification(true);
  9533. cli.enable_windows_certificate_verification(false);
  9534. auto res = cli.Get("/");
  9535. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9536. }
  9537. #endif
  9538. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9539. Client cli("https://google.com");
  9540. auto res = cli.Get("/");
  9541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9542. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9543. }
  9544. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9545. SSLClient cli("google.com");
  9546. cli.set_ca_cert_path(CA_CERT_FILE);
  9547. auto res = cli.Get("/");
  9548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9549. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9550. }
  9551. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9552. SSLClient cli("google.com");
  9553. cli.enable_server_certificate_verification(true);
  9554. cli.set_ca_cert_path("hello");
  9555. auto res = cli.Get("/");
  9556. ASSERT_TRUE(!res);
  9557. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9558. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9559. // should be set
  9560. EXPECT_EQ(0, res.ssl_error());
  9561. // Verify backend error is captured for SSLLoadingCerts
  9562. // This error occurs when loading CA certificates fails
  9563. EXPECT_NE(0UL, res.ssl_backend_error());
  9564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9565. // OpenSSL specific error codes:
  9566. // > openssl errstr 0x80000002
  9567. // error:80000002:system library::No such file or directory
  9568. // > openssl errstr 0xA000126
  9569. // error:0A000126:SSL routines::unexpected eof while reading
  9570. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9571. res.ssl_backend_error() == 0xA000126);
  9572. #endif
  9573. }
  9574. TEST(SSLClientTest, ServerCertificateVerification4) {
  9575. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9576. ASSERT_TRUE(svr.is_valid());
  9577. svr.Get("/test", [&](const Request &, Response &res) {
  9578. res.set_content("test", "text/plain");
  9579. svr.stop();
  9580. ASSERT_TRUE(true);
  9581. });
  9582. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9583. auto se = detail::scope_exit([&] {
  9584. t.join();
  9585. ASSERT_FALSE(svr.is_running());
  9586. });
  9587. svr.wait_until_ready();
  9588. SSLClient cli("127.0.0.1", PORT);
  9589. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9590. cli.enable_server_certificate_verification(true);
  9591. cli.set_connection_timeout(30);
  9592. auto res = cli.Get("/test");
  9593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9594. ASSERT_EQ(StatusCode::OK_200, res->status);
  9595. }
  9596. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9597. std::string cert;
  9598. read_file(CA_CERT_FILE, cert);
  9599. SSLClient cli("google.com");
  9600. cli.load_ca_cert_store(cert.data(), cert.size());
  9601. const auto res = cli.Get("/");
  9602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9603. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9604. }
  9605. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9606. // clang-format off
  9607. static constexpr char cert[] =
  9608. "GlobalSign Root CA\n"
  9609. "==================\n"
  9610. "-----BEGIN CERTIFICATE-----\n"
  9611. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9612. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9613. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9614. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9615. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9616. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9617. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9618. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9619. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9620. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9621. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9622. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9623. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9624. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9625. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9626. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9627. "-----END CERTIFICATE-----\n";
  9628. // clang-format on
  9629. SSLClient cli("google.com");
  9630. cli.load_ca_cert_store(cert, sizeof(cert));
  9631. const auto res = cli.Get("/");
  9632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9633. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9634. }
  9635. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9636. SSLClient cli("www.youtube.com");
  9637. cli.set_ca_cert_path(CA_CERT_FILE);
  9638. cli.enable_server_certificate_verification(true);
  9639. cli.set_follow_location(true);
  9640. auto res = cli.Get("/");
  9641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9642. ASSERT_EQ(StatusCode::OK_200, res->status);
  9643. }
  9644. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9645. SSLClient cli("wWw.YouTube.Com");
  9646. cli.set_ca_cert_path(CA_CERT_FILE);
  9647. cli.enable_server_certificate_verification(true);
  9648. cli.enable_server_hostname_verification(true);
  9649. cli.set_follow_location(true);
  9650. auto res = cli.Get("/");
  9651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9652. ASSERT_EQ(StatusCode::OK_200, res->status);
  9653. }
  9654. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9655. SSLClient cli("gOoGlE.COm");
  9656. cli.enable_server_certificate_verification(true);
  9657. cli.enable_server_hostname_verification(true);
  9658. cli.set_follow_location(true);
  9659. auto res = cli.Get("/");
  9660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9661. ASSERT_EQ(StatusCode::OK_200, res->status);
  9662. }
  9663. TEST(SSLClientTest, Issue2004_Online) {
  9664. Client client("https://google.com");
  9665. client.set_follow_location(true);
  9666. auto res = client.Get("/");
  9667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9668. ASSERT_EQ(StatusCode::OK_200, res->status);
  9669. auto body = res->body;
  9670. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9671. }
  9672. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9673. // Create SSLClient with invalid cert/key to make is_valid() return false
  9674. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9675. "nonexistent_key.pem");
  9676. // is_valid() should be false due to cert loading failure
  9677. ASSERT_FALSE(cli.is_valid());
  9678. auto res = cli.Get("/");
  9679. ASSERT_FALSE(res);
  9680. EXPECT_EQ(Error::SSLConnection, res.error());
  9681. }
  9682. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9683. // Test for Issue #2251: SSL error not properly reported when client cert
  9684. // and key paths are swapped or mismatched
  9685. // This simulates the scenario where user accidentally swaps the cert and key
  9686. // files
  9687. // Using client cert file as private key and vice versa (completely wrong)
  9688. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9689. // Should fail validation due to cert/key mismatch
  9690. ASSERT_FALSE(cli.is_valid());
  9691. // Attempt to make a request should fail with proper error
  9692. auto res = cli.Get("/");
  9693. ASSERT_FALSE(res);
  9694. EXPECT_EQ(Error::SSLConnection, res.error());
  9695. // SSL error should be recorded in the Result object (this is the key fix for
  9696. // Issue #2251)
  9697. auto backend_error = res.ssl_backend_error();
  9698. EXPECT_NE(0u, backend_error);
  9699. }
  9700. // Tests cert/key mismatch detection at the TLS context level
  9701. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9702. // Test that using mismatched cert/key causes connection failure.
  9703. // We verify this at the SSLClient level rather than through internal
  9704. // TLS API functions.
  9705. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9706. cli.enable_server_certificate_verification(false);
  9707. cli.set_connection_timeout(2);
  9708. // The mismatch should cause a connection or handshake error
  9709. auto res = cli.Get("/test");
  9710. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9711. // Either way, the request should fail
  9712. EXPECT_FALSE(res);
  9713. }
  9714. #endif
  9715. #if 0
  9716. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9717. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9718. ASSERT_TRUE(cli != nullptr);
  9719. cli->set_address_family(AF_INET6);
  9720. cli->set_interface("en0");
  9721. auto res = cli->Get("/get");
  9722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9723. ASSERT_EQ(StatusCode::OK_200, res->status);
  9724. }
  9725. #endif
  9726. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9727. #ifdef CPPHTTPLIB_SSL_ENABLED
  9728. void ClientCertPresent(
  9729. const std::string &client_cert_file,
  9730. const std::string &client_private_key_file,
  9731. const std::string &client_encrypted_private_key_pass = std::string()) {
  9732. using namespace httplib::tls;
  9733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9734. CLIENT_CA_CERT_DIR);
  9735. ASSERT_TRUE(svr.is_valid());
  9736. svr.Get("/test", [&](const Request &req, Response &res) {
  9737. res.set_content("test", "text/plain");
  9738. auto cert = req.peer_cert();
  9739. ASSERT_TRUE(static_cast<bool>(cert));
  9740. std::string common_name = cert.subject_cn();
  9741. EXPECT_EQ("Common Name", common_name);
  9742. });
  9743. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9744. auto se = detail::scope_exit([&] {
  9745. svr.stop();
  9746. t.join();
  9747. ASSERT_FALSE(svr.is_running());
  9748. });
  9749. svr.wait_until_ready();
  9750. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9751. client_encrypted_private_key_pass);
  9752. cli.enable_server_certificate_verification(false);
  9753. cli.set_connection_timeout(30);
  9754. auto res = cli.Get("/test");
  9755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9756. ASSERT_EQ(StatusCode::OK_200, res->status);
  9757. }
  9758. TEST(SSLClientServerTest, ClientCertPresent) {
  9759. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9760. }
  9761. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9762. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9763. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9764. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9765. }
  9766. // PEM memory-based constructor tests (works with all TLS backends)
  9767. void PemMemoryClientCertPresent(
  9768. const std::string &client_cert_file,
  9769. const std::string &client_private_key_file,
  9770. const std::string &client_encrypted_private_key_pass = std::string()) {
  9771. // Read PEM files into memory
  9772. std::string server_cert_pem, server_key_pem;
  9773. std::string client_ca_pem;
  9774. std::string client_cert_pem, client_key_pem;
  9775. read_file(SERVER_CERT_FILE, server_cert_pem);
  9776. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9777. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9778. read_file(client_cert_file, client_cert_pem);
  9779. read_file(client_private_key_file, client_key_pem);
  9780. // Create server with PEM memory
  9781. SSLServer::PemMemory server_pem = {
  9782. server_cert_pem.c_str(),
  9783. server_cert_pem.size(),
  9784. server_key_pem.c_str(),
  9785. server_key_pem.size(),
  9786. client_ca_pem.c_str(),
  9787. client_ca_pem.size(),
  9788. nullptr // no password for server key
  9789. };
  9790. SSLServer svr(server_pem);
  9791. ASSERT_TRUE(svr.is_valid());
  9792. svr.Get("/test", [&](const Request &, Response &res) {
  9793. res.set_content("test", "text/plain");
  9794. });
  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. // Create client with PEM memory
  9803. const char *password = client_encrypted_private_key_pass.empty()
  9804. ? nullptr
  9805. : client_encrypted_private_key_pass.c_str();
  9806. SSLClient::PemMemory client_pem = {
  9807. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9808. client_key_pem.size(), password};
  9809. SSLClient cli(HOST, PORT, client_pem);
  9810. cli.enable_server_certificate_verification(false);
  9811. cli.set_connection_timeout(30);
  9812. auto res = cli.Get("/test");
  9813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9814. ASSERT_EQ(StatusCode::OK_200, res->status);
  9815. }
  9816. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9817. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9818. }
  9819. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9820. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9821. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9822. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9823. }
  9824. TEST(SSLClientServerTest, ClientCertMissing) {
  9825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9826. CLIENT_CA_CERT_DIR);
  9827. ASSERT_TRUE(svr.is_valid());
  9828. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9829. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9830. auto se = detail::scope_exit([&] {
  9831. svr.stop();
  9832. t.join();
  9833. ASSERT_FALSE(svr.is_running());
  9834. });
  9835. svr.wait_until_ready();
  9836. SSLClient cli(HOST, PORT);
  9837. cli.set_connection_timeout(30);
  9838. auto res = cli.Get("/test");
  9839. ASSERT_TRUE(!res);
  9840. // When client cert is missing and server requires it, connection fails
  9841. // Error type depends on backend implementation
  9842. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9843. res.error() == Error::SSLConnection);
  9844. // Verify backend error is captured
  9845. // Note: This test may have different error codes depending on the exact
  9846. // verification failure
  9847. EXPECT_NE(0UL, res.ssl_backend_error());
  9848. }
  9849. TEST(SSLClientServerTest, TrustDirOptional) {
  9850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9851. ASSERT_TRUE(svr.is_valid());
  9852. svr.Get("/test", [&](const Request &, Response &res) {
  9853. res.set_content("test", "text/plain");
  9854. });
  9855. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9856. auto se = detail::scope_exit([&] {
  9857. svr.stop();
  9858. t.join();
  9859. ASSERT_FALSE(svr.is_running());
  9860. });
  9861. svr.wait_until_ready();
  9862. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9863. cli.enable_server_certificate_verification(false);
  9864. cli.set_connection_timeout(30);
  9865. auto res = cli.Get("/test");
  9866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9867. ASSERT_EQ(StatusCode::OK_200, res->status);
  9868. }
  9869. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9870. class NoListenSSLServer : public SSLServer {
  9871. public:
  9872. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9873. const char *client_ca_cert_file_path,
  9874. const char *client_ca_cert_dir_path = nullptr)
  9875. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9876. client_ca_cert_dir_path),
  9877. stop_(false) {}
  9878. std::atomic_bool stop_;
  9879. private:
  9880. bool process_and_close_socket(socket_t /*sock*/) override {
  9881. // Don't create SSL context
  9882. while (!stop_.load()) {
  9883. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9884. }
  9885. return true;
  9886. }
  9887. };
  9888. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9889. CLIENT_CA_CERT_FILE);
  9890. ASSERT_TRUE(svr.is_valid());
  9891. svr.Get("/test", [&](const Request &, Response &res) {
  9892. res.set_content("test", "text/plain");
  9893. });
  9894. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9895. auto se = detail::scope_exit([&] {
  9896. svr.stop_ = true;
  9897. svr.stop();
  9898. t.join();
  9899. ASSERT_FALSE(svr.is_running());
  9900. });
  9901. svr.wait_until_ready();
  9902. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9903. cli.enable_server_certificate_verification(false);
  9904. cli.set_connection_timeout(1);
  9905. auto res = cli.Get("/test");
  9906. ASSERT_TRUE(!res);
  9907. EXPECT_EQ(Error::SSLConnection, res.error());
  9908. // Timeout results in WantRead error code (maps to backend-specific value)
  9909. EXPECT_NE(0, res.ssl_error());
  9910. }
  9911. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9912. // Test SSLServer with client certificate verification using the standard
  9913. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9915. CLIENT_CA_CERT_DIR);
  9916. ASSERT_TRUE(svr.is_valid());
  9917. svr.Get("/test", [&](const Request &req, Response &res) {
  9918. res.set_content("test", "text/plain");
  9919. auto cert = req.peer_cert();
  9920. ASSERT_TRUE(static_cast<bool>(cert));
  9921. auto common_name = cert.subject_cn();
  9922. EXPECT_EQ("Common Name", common_name);
  9923. });
  9924. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9925. auto se = detail::scope_exit([&] {
  9926. svr.stop();
  9927. t.join();
  9928. ASSERT_FALSE(svr.is_running());
  9929. });
  9930. svr.wait_until_ready();
  9931. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9932. cli.enable_server_certificate_verification(false);
  9933. cli.set_connection_timeout(30);
  9934. auto res = cli.Get("/test");
  9935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9936. ASSERT_EQ(StatusCode::OK_200, res->status);
  9937. }
  9938. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9939. // Verifies that wildcard matching and exact matching work consistently
  9940. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9941. using namespace httplib::tls;
  9942. // We need a running server to test against
  9943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9944. ASSERT_TRUE(svr.is_valid());
  9945. svr.Get("/test", [](const Request &, Response &res) {
  9946. res.set_content("ok", "text/plain");
  9947. });
  9948. thread t([&]() { svr.listen(HOST, PORT); });
  9949. auto se = detail::scope_exit([&] {
  9950. svr.stop();
  9951. t.join();
  9952. });
  9953. svr.wait_until_ready();
  9954. bool verify_callback_called = false;
  9955. bool verify_result_wrong = false;
  9956. SSLClient cli(HOST, PORT);
  9957. cli.enable_server_certificate_verification(true);
  9958. cli.set_ca_cert_path(CA_CERT_FILE);
  9959. cli.set_connection_timeout(5);
  9960. // Note: Test certificate has CN="Common Name", not "localhost"
  9961. bool verify_result_cn = false;
  9962. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9963. verify_callback_called = true;
  9964. if (!ctx.cert) return false;
  9965. // Test 1: "Common Name" should match (our test server cert CN)
  9966. verify_result_cn = ctx.check_hostname("Common Name");
  9967. // Test 2: wrong hostname should not match
  9968. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9969. return true; // Accept for the purpose of this test
  9970. });
  9971. auto res = cli.Get("/test");
  9972. // The request may succeed or fail depending on cert configuration
  9973. // but the callback should have been called
  9974. ASSERT_TRUE(verify_callback_called)
  9975. << "Verify callback should have been called";
  9976. // CN="Common Name" should match our test certificate
  9977. //
  9978. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9979. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9980. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9981. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9982. // <openssl/base.h>, which is included transitively when
  9983. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9984. #if defined(OPENSSL_IS_BORINGSSL)
  9985. EXPECT_FALSE(verify_result_cn)
  9986. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9987. #else
  9988. EXPECT_TRUE(verify_result_cn)
  9989. << "verify_hostname should match 'Common Name' (certificate CN)";
  9990. #endif
  9991. // Wrong hostname should not match
  9992. EXPECT_FALSE(verify_result_wrong)
  9993. << "verify_hostname should not match 'wronghost.example.com'";
  9994. }
  9995. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9996. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9997. // X509_check_ip behavior and must hold for every backend.
  9998. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9999. using namespace httplib::tls;
  10000. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10001. SSLServer svr(SERVER_CERT_IP_CN_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 ip_matched_via_cn = true;
  10014. SSLClient cli(HOST, PORT);
  10015. cli.enable_server_certificate_verification(true);
  10016. cli.set_ca_cert_path(CA_CERT_FILE);
  10017. cli.set_connection_timeout(5);
  10018. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10019. verify_callback_called = true;
  10020. if (!ctx.cert) return false;
  10021. // The IP appears only in the CN, so it must NOT be accepted.
  10022. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10023. return true; // Accept for the purpose of this test
  10024. });
  10025. cli.Get("/test");
  10026. ASSERT_TRUE(verify_callback_called)
  10027. << "Verify callback should have been called";
  10028. EXPECT_FALSE(ip_matched_via_cn)
  10029. << "An IP host must not be authenticated via the certificate CN";
  10030. }
  10031. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10032. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10033. using namespace httplib::tls;
  10034. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10035. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10036. ASSERT_TRUE(svr.is_valid());
  10037. svr.Get("/test", [](const Request &, Response &res) {
  10038. res.set_content("ok", "text/plain");
  10039. });
  10040. thread t([&]() { svr.listen(HOST, PORT); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. t.join();
  10044. });
  10045. svr.wait_until_ready();
  10046. bool verify_callback_called = false;
  10047. bool san_matched = false;
  10048. bool wrong_ipv6_matched = true;
  10049. bool cn_ipv6_matched = true;
  10050. SSLClient cli(HOST, PORT);
  10051. cli.enable_server_certificate_verification(true);
  10052. cli.set_ca_cert_path(CA_CERT_FILE);
  10053. cli.set_connection_timeout(5);
  10054. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10055. verify_callback_called = true;
  10056. if (!ctx.cert) return false;
  10057. // Matches the IPv6 iPAddress SAN.
  10058. san_matched = ctx.check_hostname("2001:db8::1");
  10059. // A different IPv6 address must not match.
  10060. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10061. // "::1" lives only in the CN, so it must not be accepted.
  10062. cn_ipv6_matched = ctx.check_hostname("::1");
  10063. return true; // Accept for the purpose of this test
  10064. });
  10065. cli.Get("/test");
  10066. ASSERT_TRUE(verify_callback_called)
  10067. << "Verify callback should have been called";
  10068. EXPECT_TRUE(san_matched)
  10069. << "verify_hostname should match an IPv6 iPAddress SAN";
  10070. EXPECT_FALSE(wrong_ipv6_matched)
  10071. << "verify_hostname should not match a non-matching IPv6 address";
  10072. EXPECT_FALSE(cn_ipv6_matched)
  10073. << "An IPv6 host must not be authenticated via the certificate CN";
  10074. }
  10075. #endif
  10076. // mbedTLS-specific callback constructor test
  10077. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10078. #ifdef CPPHTTPLIB_SSL_ENABLED
  10079. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10081. ASSERT_TRUE(svr.is_valid());
  10082. // Set up a handler to verify client certificate is present
  10083. bool client_cert_verified = false;
  10084. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10085. // Verify that client certificate was provided
  10086. client_cert_verified = true;
  10087. res.set_content("success", "text/plain");
  10088. });
  10089. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10090. auto se = detail::scope_exit([&] {
  10091. svr.stop();
  10092. t.join();
  10093. ASSERT_FALSE(svr.is_running());
  10094. });
  10095. svr.wait_until_ready();
  10096. // Client with certificate
  10097. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10098. cli.enable_server_certificate_verification(false);
  10099. cli.set_connection_timeout(30);
  10100. auto res = cli.Get("/test");
  10101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10102. ASSERT_EQ(StatusCode::OK_200, res->status);
  10103. ASSERT_TRUE(client_cert_verified);
  10104. EXPECT_EQ("success", res->body);
  10105. }
  10106. #endif
  10107. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10108. // backends
  10109. #ifdef CPPHTTPLIB_SSL_ENABLED
  10110. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10111. using namespace httplib::tls;
  10112. // Test that when client CA cert file is provided,
  10113. // the server properly requests and validates client certificates
  10114. // Create a server with client authentication
  10115. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10116. ASSERT_TRUE(svr.is_valid());
  10117. bool handler_called = false;
  10118. svr.Get("/test", [&](const Request &req, Response &res) {
  10119. handler_called = true;
  10120. // Verify that a client certificate was provided
  10121. auto cert = req.peer_cert();
  10122. ASSERT_TRUE(static_cast<bool>(cert));
  10123. // Get the issuer name
  10124. std::string issuer_str = cert.issuer_name();
  10125. ASSERT_FALSE(issuer_str.empty());
  10126. // The client certificate should be issued by our test CA
  10127. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10128. res.set_content("authenticated", "text/plain");
  10129. });
  10130. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10131. auto se = detail::scope_exit([&] {
  10132. svr.stop();
  10133. t.join();
  10134. ASSERT_FALSE(svr.is_running());
  10135. });
  10136. svr.wait_until_ready();
  10137. // Connect with a client certificate issued by the CA
  10138. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10139. cli.enable_server_certificate_verification(false);
  10140. cli.set_connection_timeout(30);
  10141. auto res = cli.Get("/test");
  10142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10143. ASSERT_EQ(StatusCode::OK_200, res->status);
  10144. ASSERT_TRUE(handler_called);
  10145. EXPECT_EQ("authenticated", res->body);
  10146. }
  10147. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10148. using namespace httplib::tls;
  10149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10150. ASSERT_TRUE(svr.is_valid());
  10151. svr.Get("/test", [](const Request &, Response &res) {
  10152. res.set_content("ok", "text/plain");
  10153. });
  10154. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10155. auto se = detail::scope_exit([&] {
  10156. svr.stop();
  10157. t.join();
  10158. });
  10159. svr.wait_until_ready();
  10160. SSLClient cli(HOST, PORT);
  10161. cli.enable_server_certificate_verification(false);
  10162. cli.set_connection_timeout(30);
  10163. bool cert_checked = false;
  10164. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10165. if (ctx.cert) {
  10166. auto sans = ctx.sans();
  10167. // Test certificate may or may not have SANs - just verify the API
  10168. // works If SANs exist, verify the types are valid
  10169. for (const auto &san : sans) {
  10170. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10171. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10172. san.type == SanType::OTHER);
  10173. EXPECT_FALSE(san.value.empty());
  10174. }
  10175. cert_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(cert_checked);
  10182. }
  10183. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  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 validity_checked = false;
  10200. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10201. if (ctx.cert) {
  10202. time_t not_before = 0, not_after = 0;
  10203. bool result = ctx.validity(not_before, not_after);
  10204. EXPECT_TRUE(result);
  10205. // Verify that not_before < now < not_after for a valid cert
  10206. time_t now = time(nullptr);
  10207. EXPECT_LT(not_before, now);
  10208. EXPECT_GT(not_after, now);
  10209. validity_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(validity_checked);
  10216. }
  10217. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10218. using namespace httplib::tls;
  10219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10220. ASSERT_TRUE(svr.is_valid());
  10221. svr.Get("/test", [](const Request &, Response &res) {
  10222. res.set_content("ok", "text/plain");
  10223. });
  10224. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10225. auto se = detail::scope_exit([&] {
  10226. svr.stop();
  10227. t.join();
  10228. });
  10229. svr.wait_until_ready();
  10230. SSLClient cli(HOST, PORT);
  10231. cli.enable_server_certificate_verification(false);
  10232. cli.set_connection_timeout(30);
  10233. bool serial_checked = false;
  10234. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10235. if (ctx.cert) {
  10236. std::string serial = ctx.serial();
  10237. EXPECT_FALSE(serial.empty());
  10238. // Serial should be a hex string
  10239. for (char c : serial) {
  10240. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10241. (c >= 'a' && c <= 'f'));
  10242. }
  10243. serial_checked = true;
  10244. }
  10245. return true;
  10246. });
  10247. auto res = cli.Get("/test");
  10248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10249. EXPECT_TRUE(serial_checked);
  10250. }
  10251. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10252. // Test 1: Valid CA file - no error should be recorded
  10253. {
  10254. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10255. CLIENT_CA_CERT_FILE);
  10256. ASSERT_TRUE(svr.is_valid());
  10257. // With valid setup, last_ssl_error should be 0
  10258. EXPECT_EQ(0, svr.ssl_last_error());
  10259. }
  10260. // Test 2: Invalid CA file content
  10261. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10262. {
  10263. // Create a temporary file with completely invalid content
  10264. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10265. {
  10266. std::ofstream ofs(temp_invalid_ca);
  10267. ofs << "This is not a certificate file at all\n";
  10268. ofs << "Just plain text content\n";
  10269. }
  10270. // Create server with invalid CA file
  10271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10272. // Clean up temporary file
  10273. std::remove(temp_invalid_ca);
  10274. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10275. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10276. // Note: SSL_CTX_load_verify_locations typically fails first,
  10277. // but our error handling code path is still exercised
  10278. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10279. }
  10280. }
  10281. TEST(VerifyCallbackTest, VerifyContextFields) {
  10282. using namespace httplib::tls;
  10283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10284. ASSERT_TRUE(svr.is_valid());
  10285. svr.Get("/test", [](const Request &, Response &res) {
  10286. res.set_content("ok", "text/plain");
  10287. });
  10288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10289. auto se = detail::scope_exit([&] {
  10290. svr.stop();
  10291. t.join();
  10292. });
  10293. svr.wait_until_ready();
  10294. SSLClient cli(HOST, PORT);
  10295. cli.enable_server_certificate_verification(false);
  10296. cli.set_connection_timeout(30);
  10297. int callback_count = 0;
  10298. bool saw_leaf_cert = false;
  10299. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10300. if (ctx.cert) {
  10301. callback_count++;
  10302. // We should see at least one certificate (the leaf)
  10303. std::string cn = ctx.subject_cn();
  10304. if (!cn.empty()) { saw_leaf_cert = true; }
  10305. // Verify context fields are populated
  10306. EXPECT_NE(ctx.session, nullptr);
  10307. EXPECT_GE(ctx.depth, 0);
  10308. }
  10309. return true;
  10310. });
  10311. auto res = cli.Get("/test");
  10312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10313. EXPECT_GT(callback_count, 0);
  10314. EXPECT_TRUE(saw_leaf_cert);
  10315. }
  10316. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10317. using httplib::tls::TlsError;
  10318. // Test that verify_error_to_string returns empty for success
  10319. std::string success_str = TlsError::verify_error_to_string(0);
  10320. EXPECT_TRUE(success_str.empty());
  10321. // Test that verify_error_to_string returns non-empty for error codes
  10322. // Using a common error code (certificate expired)
  10323. std::string error_str =
  10324. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10325. EXPECT_FALSE(error_str.empty());
  10326. }
  10327. TEST(SessionVerifierTest, CertificateAccepted) {
  10328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10329. ASSERT_TRUE(svr.is_valid());
  10330. svr.Get("/test", [](const Request &, Response &res) {
  10331. res.set_content("ok", "text/plain");
  10332. });
  10333. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10334. auto se = detail::scope_exit([&] {
  10335. svr.stop();
  10336. t.join();
  10337. });
  10338. svr.wait_until_ready();
  10339. SSLClient cli(HOST, PORT);
  10340. cli.enable_server_certificate_verification(false);
  10341. cli.set_connection_timeout(30);
  10342. bool callback_called = false;
  10343. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10344. EXPECT_NE(session, nullptr);
  10345. callback_called = true;
  10346. return SSLVerifierResponse::CertificateAccepted;
  10347. });
  10348. auto res = cli.Get("/test");
  10349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10350. EXPECT_EQ(200, res->status);
  10351. EXPECT_TRUE(callback_called);
  10352. }
  10353. TEST(SessionVerifierTest, CertificateRejected) {
  10354. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10355. ASSERT_TRUE(svr.is_valid());
  10356. svr.Get("/test", [](const Request &, Response &res) {
  10357. res.set_content("ok", "text/plain");
  10358. });
  10359. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10360. auto se = detail::scope_exit([&] {
  10361. svr.stop();
  10362. t.join();
  10363. });
  10364. svr.wait_until_ready();
  10365. SSLClient cli(HOST, PORT);
  10366. cli.enable_server_certificate_verification(false);
  10367. cli.set_connection_timeout(30);
  10368. bool callback_called = false;
  10369. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10370. EXPECT_NE(session, nullptr);
  10371. callback_called = true;
  10372. return SSLVerifierResponse::CertificateRejected;
  10373. });
  10374. auto res = cli.Get("/test");
  10375. EXPECT_FALSE(res);
  10376. EXPECT_TRUE(callback_called);
  10377. }
  10378. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10380. ASSERT_TRUE(svr.is_valid());
  10381. svr.Get("/test", [](const Request &, Response &res) {
  10382. res.set_content("ok", "text/plain");
  10383. });
  10384. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10385. auto se = detail::scope_exit([&] {
  10386. svr.stop();
  10387. t.join();
  10388. });
  10389. svr.wait_until_ready();
  10390. // NoDecisionMade with verification disabled should succeed (no default check)
  10391. SSLClient cli(HOST, PORT);
  10392. cli.enable_server_certificate_verification(false);
  10393. cli.set_connection_timeout(30);
  10394. bool callback_called = false;
  10395. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10396. EXPECT_NE(session, nullptr);
  10397. callback_called = true;
  10398. return SSLVerifierResponse::NoDecisionMade;
  10399. });
  10400. auto res = cli.Get("/test");
  10401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10402. EXPECT_EQ(200, res->status);
  10403. EXPECT_TRUE(callback_called);
  10404. }
  10405. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10407. ASSERT_TRUE(svr.is_valid());
  10408. svr.Get("/test", [](const Request &, Response &res) {
  10409. res.set_content("ok", "text/plain");
  10410. });
  10411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10412. auto se = detail::scope_exit([&] {
  10413. svr.stop();
  10414. t.join();
  10415. });
  10416. svr.wait_until_ready();
  10417. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10418. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10419. // so we only check that the request fails, not whether the callback was
  10420. // called.
  10421. SSLClient cli(HOST, PORT);
  10422. cli.enable_server_certificate_verification(true);
  10423. cli.set_connection_timeout(30);
  10424. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10425. EXPECT_NE(session, nullptr);
  10426. return SSLVerifierResponse::NoDecisionMade;
  10427. });
  10428. auto res = cli.Get("/test");
  10429. EXPECT_FALSE(res);
  10430. }
  10431. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10432. // Test SSL server using PemMemory constructor with client CA certificates
  10433. // Read PEM files
  10434. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10435. read_file(SERVER_CERT_FILE, server_cert_pem);
  10436. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10437. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10438. // Create SSLServer with PemMemory constructor including client CA
  10439. SSLServer::PemMemory server_pem = {
  10440. server_cert_pem.c_str(),
  10441. server_cert_pem.size(),
  10442. server_key_pem.c_str(),
  10443. server_key_pem.size(),
  10444. client_ca_pem.c_str(),
  10445. client_ca_pem.size(),
  10446. nullptr // no password for server key
  10447. };
  10448. SSLServer svr(server_pem);
  10449. ASSERT_TRUE(svr.is_valid());
  10450. // No SSL error should be recorded for valid setup
  10451. EXPECT_EQ(0, svr.ssl_last_error());
  10452. // Set up server endpoints
  10453. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10454. res.set_content("ok", "text/plain");
  10455. });
  10456. // Start server in a thread
  10457. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10458. svr.wait_until_ready();
  10459. // Connect with client certificate (using constructor with paths)
  10460. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10461. cli.enable_server_certificate_verification(false);
  10462. auto res = cli.Get("/test-pem-ca");
  10463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10464. EXPECT_EQ(200, res->status);
  10465. EXPECT_EQ("ok", res->body);
  10466. svr.stop();
  10467. server_thread.join();
  10468. }
  10469. #endif
  10470. #ifdef _WIN32
  10471. TEST(CleanupTest, WSACleanup) {
  10472. int ret = WSACleanup();
  10473. ASSERT_EQ(0, ret);
  10474. }
  10475. #endif
  10476. #ifndef CPPHTTPLIB_SSL_ENABLED
  10477. TEST(NoSSLSupport, SimpleInterface) {
  10478. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10479. }
  10480. #endif
  10481. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10482. TEST(InvalidScheme, SimpleInterface) {
  10483. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10484. }
  10485. #endif
  10486. TEST(NoScheme, SimpleInterface) {
  10487. Client cli("yahoo.com:80");
  10488. ASSERT_TRUE(cli.is_valid());
  10489. }
  10490. TEST(SendAPI, SimpleInterface_Online) {
  10491. Client cli("http://yahoo.com");
  10492. Request req;
  10493. req.method = "GET";
  10494. req.path = "/";
  10495. auto res = cli.send(req);
  10496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10497. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10498. }
  10499. TEST(SendAPI, WithParamsInRequest) {
  10500. Server svr;
  10501. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10502. EXPECT_TRUE(req.has_param("test"));
  10503. EXPECT_EQ("test_value", req.get_param_value("test"));
  10504. });
  10505. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10506. auto se = detail::scope_exit([&] {
  10507. svr.stop();
  10508. t.join();
  10509. ASSERT_FALSE(svr.is_running());
  10510. });
  10511. svr.wait_until_ready();
  10512. Client cli(HOST, PORT);
  10513. {
  10514. Request req;
  10515. req.method = "GET";
  10516. req.path = "/";
  10517. req.params.emplace("test", "test_value");
  10518. auto res = cli.send(req);
  10519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10520. }
  10521. {
  10522. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10524. }
  10525. }
  10526. TEST(ClientImplMethods, GetSocketTest) {
  10527. httplib::Server svr;
  10528. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10529. res.status = StatusCode::OK_200;
  10530. });
  10531. auto port = svr.bind_to_any_port("127.0.0.1");
  10532. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10533. auto se = detail::scope_exit([&] {
  10534. svr.stop();
  10535. thread.join();
  10536. ASSERT_FALSE(svr.is_running());
  10537. });
  10538. svr.wait_until_ready();
  10539. {
  10540. httplib::Client cli("127.0.0.1", port);
  10541. cli.set_keep_alive(true);
  10542. // Use the behavior of cpp-httplib of opening the connection
  10543. // only when the first request happens. If that changes,
  10544. // this test would be obsolete.
  10545. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10546. // This also implicitly tests the server. But other tests would fail much
  10547. // earlier than this one to be considered.
  10548. auto res = cli.Get("/");
  10549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10550. EXPECT_EQ(StatusCode::OK_200, res->status);
  10551. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10552. }
  10553. }
  10554. #ifdef CPPHTTPLIB_SSL_ENABLED
  10555. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10556. Client cli("http://yahoo.com");
  10557. auto res = cli.Get("/");
  10558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10559. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10560. cli.set_follow_location(true);
  10561. res = cli.Get("/");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::OK_200, res->status);
  10564. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10565. }
  10566. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10567. Client cli("https://yahoo.com");
  10568. auto res = cli.Get("/");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10571. cli.set_follow_location(true);
  10572. res = cli.Get("/");
  10573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10574. EXPECT_EQ(StatusCode::OK_200, res->status);
  10575. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10576. }
  10577. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10578. Client cli("https://yahoo.com");
  10579. auto res = cli.Get("/");
  10580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10581. ASSERT_FALSE(!res);
  10582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10583. ASSERT_FALSE(res == nullptr);
  10584. ASSERT_TRUE(res != nullptr);
  10585. EXPECT_EQ(Error::Success, res.error());
  10586. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10587. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10588. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10589. cli.set_follow_location(true);
  10590. res = cli.Get("/");
  10591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10592. EXPECT_EQ(Error::Success, res.error());
  10593. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10594. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10595. EXPECT_EQ(StatusCode::OK_200, res->status);
  10596. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10597. }
  10598. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10599. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10600. Client cli("https://cdnjs.cloudflare.com");
  10601. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10602. Headers{{"Accept-Encoding", "br"}});
  10603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10604. EXPECT_EQ(StatusCode::OK_200, res->status);
  10605. EXPECT_EQ(287630U, res->body.size());
  10606. EXPECT_EQ("application/javascript; charset=utf-8",
  10607. res->get_header_value("Content-Type"));
  10608. }
  10609. #endif
  10610. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10611. #undef REDIR_HOST // Silence compiler warning
  10612. #define REDIR_HOST "https://httpbingo.org"
  10613. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10614. Client cli(REDIR_HOST);
  10615. cli.set_follow_location(true);
  10616. auto res =
  10617. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ(StatusCode::OK_200, res->status);
  10620. }
  10621. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10622. Client cli(REDIR_HOST);
  10623. cli.set_follow_location(true);
  10624. Params params;
  10625. params.emplace("url", "http://example.com");
  10626. params.emplace("status_code", "302");
  10627. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10629. EXPECT_EQ(StatusCode::OK_200, res->status);
  10630. }
  10631. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10632. Client cli(REDIR_HOST);
  10633. cli.set_follow_location(true);
  10634. Params params;
  10635. params.emplace("url", "http://example.com");
  10636. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10638. EXPECT_EQ(StatusCode::OK_200, res->status);
  10639. }
  10640. TEST(HttpToHttpsRedirectTest, CertFile) {
  10641. auto ssl_port = PORT + 1;
  10642. Server svr;
  10643. ASSERT_TRUE(svr.is_valid());
  10644. svr.Get("/index", [&](const Request &, Response &res) {
  10645. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10646. "/index");
  10647. svr.stop();
  10648. });
  10649. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10650. ASSERT_TRUE(ssl_svr.is_valid());
  10651. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10652. res.set_content("test", "text/plain");
  10653. ssl_svr.stop();
  10654. });
  10655. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10656. thread t2 =
  10657. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10658. auto se = detail::scope_exit([&] {
  10659. t2.join();
  10660. t.join();
  10661. ASSERT_FALSE(svr.is_running());
  10662. });
  10663. svr.wait_until_ready();
  10664. ssl_svr.wait_until_ready();
  10665. Client cli("127.0.0.1", PORT);
  10666. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10667. cli.enable_server_certificate_verification(true);
  10668. cli.set_follow_location(true);
  10669. cli.set_connection_timeout(30);
  10670. auto res = cli.Get("/index");
  10671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10672. ASSERT_EQ(StatusCode::OK_200, res->status);
  10673. }
  10674. TEST(SSLClientRedirectTest, CertFile) {
  10675. auto ssl_port = PORT + 1;
  10676. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10677. ASSERT_TRUE(ssl_svr1.is_valid());
  10678. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10679. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10680. "/index");
  10681. ssl_svr1.stop();
  10682. });
  10683. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10684. ASSERT_TRUE(ssl_svr2.is_valid());
  10685. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10686. res.set_content("test", "text/plain");
  10687. ssl_svr2.stop();
  10688. });
  10689. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10690. thread t2 =
  10691. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10692. auto se = detail::scope_exit([&] {
  10693. t2.join();
  10694. t.join();
  10695. ASSERT_FALSE(ssl_svr1.is_running());
  10696. });
  10697. ssl_svr1.wait_until_ready();
  10698. ssl_svr2.wait_until_ready();
  10699. SSLClient cli("127.0.0.1", PORT);
  10700. std::string cert;
  10701. read_file(SERVER_CERT2_FILE, cert);
  10702. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10703. cli.enable_server_certificate_verification(true);
  10704. cli.set_follow_location(true);
  10705. cli.set_connection_timeout(30);
  10706. auto res = cli.Get("/index");
  10707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10708. ASSERT_EQ(StatusCode::OK_200, res->status);
  10709. }
  10710. #endif
  10711. #ifdef CPPHTTPLIB_SSL_ENABLED
  10712. // Test that set_ca_cert_store() skips system certs (consistent with
  10713. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10714. // should be trusted - system certs should NOT be loaded.
  10715. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10716. // Load a specific cert that is NOT a system CA cert
  10717. std::string cert;
  10718. read_file(SERVER_CERT2_FILE, cert);
  10719. SSLClient cli("google.com");
  10720. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10721. cli.enable_server_certificate_verification(true);
  10722. // This should FAIL because:
  10723. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10724. // 2. System certs should NOT be loaded when custom store is set
  10725. // If system certs WERE loaded, this would succeed
  10726. auto res = cli.Get("/");
  10727. ASSERT_FALSE(res);
  10728. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10729. }
  10730. // Same as above, but through the native store handle path. Regression test:
  10731. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10732. // merged system certs into the user-provided store.
  10733. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10734. std::string cert;
  10735. read_file(SERVER_CERT2_FILE, cert);
  10736. SSLClient cli("google.com");
  10737. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10738. cli.enable_server_certificate_verification(true);
  10739. auto res = cli.Get("/");
  10740. ASSERT_FALSE(res);
  10741. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10742. }
  10743. // A custom store set via the native handle must still verify a server whose
  10744. // cert it does contain.
  10745. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10746. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10747. ASSERT_TRUE(svr.is_valid());
  10748. svr.Get("/test", [&](const Request &, Response &res) {
  10749. res.set_content("test", "text/plain");
  10750. });
  10751. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10752. auto se = detail::scope_exit([&] {
  10753. svr.stop();
  10754. t.join();
  10755. ASSERT_FALSE(svr.is_running());
  10756. });
  10757. svr.wait_until_ready();
  10758. SSLClient cli("127.0.0.1", PORT);
  10759. std::string cert;
  10760. read_file(SERVER_CERT2_FILE, cert);
  10761. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10762. cli.enable_server_certificate_verification(true);
  10763. cli.set_connection_timeout(30);
  10764. auto res = cli.Get("/test");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. ASSERT_EQ(StatusCode::OK_200, res->status);
  10767. }
  10768. // CA certs loaded through the universal Client must be transferred to the
  10769. // client created internally for following an HTTPS redirect. Regression test:
  10770. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10771. // the CA data for redirect transfer.
  10772. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10773. auto ssl_port = PORT + 1;
  10774. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10775. ASSERT_TRUE(ssl_svr1.is_valid());
  10776. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10777. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10778. "/index");
  10779. });
  10780. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10781. ASSERT_TRUE(ssl_svr2.is_valid());
  10782. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10783. res.set_content("test", "text/plain");
  10784. });
  10785. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10786. thread t2 =
  10787. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10788. auto se = detail::scope_exit([&] {
  10789. ssl_svr2.stop();
  10790. ssl_svr1.stop();
  10791. t2.join();
  10792. t.join();
  10793. ASSERT_FALSE(ssl_svr1.is_running());
  10794. });
  10795. ssl_svr1.wait_until_ready();
  10796. ssl_svr2.wait_until_ready();
  10797. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10798. std::string cert;
  10799. read_file(SERVER_CERT2_FILE, cert);
  10800. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10801. cli.enable_server_certificate_verification(true);
  10802. cli.set_follow_location(true);
  10803. cli.set_connection_timeout(30);
  10804. auto res = cli.Get("/index");
  10805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10806. ASSERT_EQ(StatusCode::OK_200, res->status);
  10807. }
  10808. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10809. // so a host signed by a system CA verifies even though a custom CA is set
  10810. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10811. std::string cert;
  10812. read_file(SERVER_CERT2_FILE, cert);
  10813. SSLClient cli("google.com");
  10814. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10815. cli.enable_system_ca(true);
  10816. cli.enable_server_certificate_verification(true);
  10817. auto res = cli.Get("/");
  10818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10819. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10820. }
  10821. // The custom CA remains effective when combined with the system CA
  10822. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10823. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10824. ASSERT_TRUE(svr.is_valid());
  10825. svr.Get("/test", [&](const Request &, Response &res) {
  10826. res.set_content("test", "text/plain");
  10827. });
  10828. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. t.join();
  10832. ASSERT_FALSE(svr.is_running());
  10833. });
  10834. svr.wait_until_ready();
  10835. SSLClient cli("127.0.0.1", PORT);
  10836. std::string cert;
  10837. read_file(SERVER_CERT2_FILE, cert);
  10838. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10839. cli.enable_system_ca(true);
  10840. cli.enable_server_certificate_verification(true);
  10841. cli.set_connection_timeout(30);
  10842. auto res = cli.Get("/test");
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. ASSERT_EQ(StatusCode::OK_200, res->status);
  10845. }
  10846. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10847. // skip chain verification entirely (only the certificate identity was
  10848. // checked), so a server presenting an untrusted certificate with a matching
  10849. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10850. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10851. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10852. ASSERT_TRUE(svr.is_valid());
  10853. svr.Get("/test", [&](const Request &, Response &res) {
  10854. res.set_content("test", "text/plain");
  10855. });
  10856. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10857. auto se = detail::scope_exit([&] {
  10858. svr.stop();
  10859. t.join();
  10860. ASSERT_FALSE(svr.is_running());
  10861. });
  10862. svr.wait_until_ready();
  10863. SSLClient cli("127.0.0.1", PORT);
  10864. std::string cert;
  10865. // A trusted CA that did not sign the server certificate. The server cert
  10866. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10867. // this connection.
  10868. read_file(CLIENT_CA_CERT_FILE, cert);
  10869. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10870. cli.enable_server_certificate_verification(true);
  10871. cli.set_connection_timeout(30);
  10872. auto res = cli.Get("/test");
  10873. ASSERT_FALSE(res);
  10874. }
  10875. // enable_system_ca(false) prevents system CA loading entirely
  10876. TEST(SSLClientTest, DisableSystemCa_Online) {
  10877. SSLClient cli("google.com");
  10878. cli.enable_system_ca(false);
  10879. cli.enable_server_certificate_verification(true);
  10880. auto res = cli.Get("/");
  10881. ASSERT_FALSE(res);
  10882. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10883. // itself when the CA chain is empty
  10884. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10885. res.error() == Error::SSLConnection);
  10886. }
  10887. // The universal Client forwards enable_system_ca()
  10888. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10889. std::string cert;
  10890. read_file(SERVER_CERT2_FILE, cert);
  10891. Client cli("https://google.com");
  10892. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10893. cli.enable_system_ca(true);
  10894. cli.enable_server_certificate_verification(true);
  10895. auto res = cli.Get("/");
  10896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10897. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10898. }
  10899. // The system CA policy must carry over to the client created internally for
  10900. // following a cross-host HTTPS redirect
  10901. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10902. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10903. ASSERT_TRUE(svr.is_valid());
  10904. svr.Get("/index", [&](const Request &, Response &res) {
  10905. res.set_redirect("https://www.google.com/");
  10906. });
  10907. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10908. auto se = detail::scope_exit([&] {
  10909. svr.stop();
  10910. t.join();
  10911. ASSERT_FALSE(svr.is_running());
  10912. });
  10913. svr.wait_until_ready();
  10914. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10915. std::string cert;
  10916. read_file(SERVER_CERT2_FILE, cert);
  10917. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10918. cli.enable_system_ca(true);
  10919. cli.enable_server_certificate_verification(true);
  10920. cli.set_follow_location(true);
  10921. cli.set_connection_timeout(30);
  10922. // Receiving any response proves the redirect client completed the TLS
  10923. // handshake with a system-CA-signed host
  10924. auto res = cli.Get("/index");
  10925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10926. }
  10927. TEST(MultipartFormDataTest, LargeData) {
  10928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10929. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10930. const ContentReader &content_reader) {
  10931. if (req.is_multipart_form_data()) {
  10932. std::vector<FormData> items;
  10933. content_reader(
  10934. [&](const FormData &file) {
  10935. items.push_back(file);
  10936. return true;
  10937. },
  10938. [&](const char *data, size_t data_length) {
  10939. items.back().content.append(data, data_length);
  10940. return true;
  10941. });
  10942. EXPECT_TRUE(std::string(items[0].name) == "document");
  10943. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10944. EXPECT_TRUE(items[0].filename == "2MB_data");
  10945. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10946. EXPECT_TRUE(items[1].name == "hello");
  10947. EXPECT_TRUE(items[1].content == "world");
  10948. EXPECT_TRUE(items[1].filename == "");
  10949. EXPECT_TRUE(items[1].content_type == "");
  10950. } else {
  10951. std::string body;
  10952. content_reader([&](const char *data, size_t data_length) {
  10953. body.append(data, data_length);
  10954. return true;
  10955. });
  10956. }
  10957. });
  10958. auto port = svr.bind_to_any_port(HOST);
  10959. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10960. auto se = detail::scope_exit([&] {
  10961. svr.stop();
  10962. t.join();
  10963. ASSERT_FALSE(svr.is_running());
  10964. });
  10965. svr.wait_until_ready();
  10966. {
  10967. std::string data(1024 * 1024 * 2, '.');
  10968. std::stringstream buffer;
  10969. buffer << data;
  10970. SSLClient cli(HOST, port);
  10971. cli.enable_server_certificate_verification(false);
  10972. UploadFormDataItems items{
  10973. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10974. {"hello", "world", "", ""},
  10975. };
  10976. auto res = cli.Post("/post", items);
  10977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10978. ASSERT_EQ(StatusCode::OK_200, res->status);
  10979. }
  10980. }
  10981. TEST(MultipartFormDataTest, DataProviderItems) {
  10982. std::random_device seed_gen;
  10983. std::mt19937 random(seed_gen());
  10984. std::string rand1;
  10985. rand1.resize(1000);
  10986. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10987. std::string rand2;
  10988. rand2.resize(3000);
  10989. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10991. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10992. const ContentReader &content_reader) {
  10993. ASSERT_FALSE(req.is_multipart_form_data());
  10994. std::string body;
  10995. content_reader([&](const char *data, size_t data_length) {
  10996. body.append(data, data_length);
  10997. return true;
  10998. });
  10999. EXPECT_EQ(body, "");
  11000. });
  11001. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11002. const ContentReader &content_reader) {
  11003. ASSERT_TRUE(req.is_multipart_form_data());
  11004. std::vector<FormData> items;
  11005. content_reader(
  11006. [&](const FormData &file) {
  11007. items.push_back(file);
  11008. return true;
  11009. },
  11010. [&](const char *data, size_t data_length) {
  11011. items.back().content.append(data, data_length);
  11012. return true;
  11013. });
  11014. ASSERT_TRUE(items.size() == 2);
  11015. EXPECT_EQ(std::string(items[0].name), "name1");
  11016. EXPECT_EQ(items[0].content, "Testing123");
  11017. EXPECT_EQ(items[0].filename, "filename1");
  11018. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11019. EXPECT_EQ(items[1].name, "name2");
  11020. EXPECT_EQ(items[1].content, "Testing456");
  11021. EXPECT_EQ(items[1].filename, "");
  11022. EXPECT_EQ(items[1].content_type, "");
  11023. });
  11024. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11025. const ContentReader &content_reader) {
  11026. ASSERT_TRUE(req.is_multipart_form_data());
  11027. std::vector<FormData> items;
  11028. content_reader(
  11029. [&](const FormData &file) {
  11030. items.push_back(file);
  11031. return true;
  11032. },
  11033. [&](const char *data, size_t data_length) {
  11034. items.back().content.append(data, data_length);
  11035. return true;
  11036. });
  11037. ASSERT_TRUE(items.size() == 2);
  11038. EXPECT_EQ(items[0].name, "name3");
  11039. EXPECT_EQ(items[0].content, rand1);
  11040. EXPECT_EQ(items[0].filename, "filename3");
  11041. EXPECT_EQ(items[0].content_type, "");
  11042. EXPECT_EQ(items[1].name, "name4");
  11043. EXPECT_EQ(items[1].content, rand2);
  11044. EXPECT_EQ(items[1].filename, "filename4");
  11045. EXPECT_EQ(items[1].content_type, "");
  11046. });
  11047. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11048. const ContentReader &content_reader) {
  11049. ASSERT_TRUE(req.is_multipart_form_data());
  11050. std::vector<FormData> items;
  11051. content_reader(
  11052. [&](const FormData &file) {
  11053. items.push_back(file);
  11054. return true;
  11055. },
  11056. [&](const char *data, size_t data_length) {
  11057. items.back().content.append(data, data_length);
  11058. return true;
  11059. });
  11060. ASSERT_TRUE(items.size() == 4);
  11061. EXPECT_EQ(std::string(items[0].name), "name1");
  11062. EXPECT_EQ(items[0].content, "Testing123");
  11063. EXPECT_EQ(items[0].filename, "filename1");
  11064. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11065. EXPECT_EQ(items[1].name, "name2");
  11066. EXPECT_EQ(items[1].content, "Testing456");
  11067. EXPECT_EQ(items[1].filename, "");
  11068. EXPECT_EQ(items[1].content_type, "");
  11069. EXPECT_EQ(items[2].name, "name3");
  11070. EXPECT_EQ(items[2].content, rand1);
  11071. EXPECT_EQ(items[2].filename, "filename3");
  11072. EXPECT_EQ(items[2].content_type, "");
  11073. EXPECT_EQ(items[3].name, "name4");
  11074. EXPECT_EQ(items[3].content, rand2);
  11075. EXPECT_EQ(items[3].filename, "filename4");
  11076. EXPECT_EQ(items[3].content_type, "");
  11077. });
  11078. auto port = svr.bind_to_any_port("localhost");
  11079. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11080. auto se = detail::scope_exit([&] {
  11081. svr.stop();
  11082. t.join();
  11083. ASSERT_FALSE(svr.is_running());
  11084. });
  11085. svr.wait_until_ready();
  11086. {
  11087. SSLClient cli("localhost", port);
  11088. cli.enable_server_certificate_verification(false);
  11089. UploadFormDataItems items{
  11090. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11091. {"name2", "Testing456", "", ""}, // not a file
  11092. };
  11093. {
  11094. auto res = cli.Post("/post-none", {}, {}, {});
  11095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11096. ASSERT_EQ(StatusCode::OK_200, res->status);
  11097. }
  11098. FormDataProviderItems providers;
  11099. {
  11100. auto res =
  11101. cli.Post("/post-items", {}, items, providers); // empty providers
  11102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11103. ASSERT_EQ(StatusCode::OK_200, res->status);
  11104. }
  11105. providers.push_back({"name3",
  11106. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11107. // test the offset is given correctly at each step
  11108. if (!offset)
  11109. sink.os.write(rand1.data(), 30);
  11110. else if (offset == 30)
  11111. sink.os.write(rand1.data() + 30, 300);
  11112. else if (offset == 330)
  11113. sink.os.write(rand1.data() + 330, 670);
  11114. else if (offset == rand1.size())
  11115. sink.done();
  11116. return true;
  11117. },
  11118. "filename3",
  11119. {}});
  11120. providers.push_back({"name4",
  11121. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11122. // test the offset is given correctly at each step
  11123. if (!offset)
  11124. sink.os.write(rand2.data(), 2000);
  11125. else if (offset == 2000)
  11126. sink.os.write(rand2.data() + 2000, 1);
  11127. else if (offset == 2001)
  11128. sink.os.write(rand2.data() + 2001, 999);
  11129. else if (offset == rand2.size())
  11130. sink.done();
  11131. return true;
  11132. },
  11133. "filename4",
  11134. {}});
  11135. {
  11136. auto res = cli.Post("/post-providers", {}, {}, providers);
  11137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11138. ASSERT_EQ(StatusCode::OK_200, res->status);
  11139. }
  11140. {
  11141. auto res = cli.Post("/post-both", {}, items, providers);
  11142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11143. ASSERT_EQ(StatusCode::OK_200, res->status);
  11144. }
  11145. }
  11146. }
  11147. TEST(MultipartFormDataTest, BadHeader) {
  11148. Server svr;
  11149. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11150. res.set_content("ok", "text/plain");
  11151. });
  11152. thread t = thread([&] { svr.listen(HOST, PORT); });
  11153. auto se = detail::scope_exit([&] {
  11154. svr.stop();
  11155. t.join();
  11156. ASSERT_FALSE(svr.is_running());
  11157. });
  11158. svr.wait_until_ready();
  11159. const std::string body =
  11160. "This is the preamble. It is to be ignored, though it\r\n"
  11161. "is a handy place for composition agents to include an\r\n"
  11162. "explanatory note to non-MIME conformant readers.\r\n"
  11163. "\r\n"
  11164. "\r\n"
  11165. "--simple boundary\r\n"
  11166. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11167. ": BAD...\r\n"
  11168. "\r\n"
  11169. "value1\r\n"
  11170. "--simple boundary\r\n"
  11171. "Content-Disposition: form-data; name=\"field2\"; "
  11172. "filename=\"example.txt\"\r\n"
  11173. "\r\n"
  11174. "value2\r\n"
  11175. "--simple boundary--\r\n"
  11176. "This is the epilogue. It is also to be ignored.\r\n";
  11177. std::string content_type =
  11178. R"(multipart/form-data; boundary="simple boundary")";
  11179. Client cli(HOST, PORT);
  11180. auto res = cli.Post("/post", body, content_type.c_str());
  11181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11182. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11183. }
  11184. TEST(MultipartFormDataTest, WithPreamble) {
  11185. Server svr;
  11186. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11187. res.set_content("ok", "text/plain");
  11188. });
  11189. thread t = thread([&] { svr.listen(HOST, PORT); });
  11190. auto se = detail::scope_exit([&] {
  11191. svr.stop();
  11192. t.join();
  11193. ASSERT_FALSE(svr.is_running());
  11194. });
  11195. svr.wait_until_ready();
  11196. const std::string body =
  11197. "This is the preamble. It is to be ignored, though it\r\n"
  11198. "is a handy place for composition agents to include an\r\n"
  11199. "explanatory note to non-MIME conformant readers.\r\n"
  11200. "\r\n"
  11201. "\r\n"
  11202. "--simple boundary\r\n"
  11203. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11204. "\r\n"
  11205. "value1\r\n"
  11206. "--simple boundary\r\n"
  11207. "Content-Disposition: form-data; name=\"field2\"; "
  11208. "filename=\"example.txt\"\r\n"
  11209. "\r\n"
  11210. "value2\r\n"
  11211. "--simple boundary--\r\n"
  11212. "This is the epilogue. It is also to be ignored.\r\n";
  11213. std::string content_type =
  11214. R"(multipart/form-data; boundary="simple boundary")";
  11215. Client cli(HOST, PORT);
  11216. auto res = cli.Post("/post", body, content_type.c_str());
  11217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11218. EXPECT_EQ(StatusCode::OK_200, res->status);
  11219. }
  11220. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11222. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11223. const ContentReader &content_reader) {
  11224. if (req.is_multipart_form_data()) {
  11225. std::vector<FormData> items;
  11226. content_reader(
  11227. [&](const FormData &file) {
  11228. items.push_back(file);
  11229. return true;
  11230. },
  11231. [&](const char *data, size_t data_length) {
  11232. items.back().content.append(data, data_length);
  11233. return true;
  11234. });
  11235. EXPECT_TRUE(std::string(items[0].name) == "document");
  11236. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11237. EXPECT_TRUE(items[0].filename == "2MB_data");
  11238. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11239. EXPECT_TRUE(items[1].name == "hello");
  11240. EXPECT_TRUE(items[1].content == "world");
  11241. EXPECT_TRUE(items[1].filename == "");
  11242. EXPECT_TRUE(items[1].content_type == "");
  11243. } else {
  11244. std::string body;
  11245. content_reader([&](const char *data, size_t data_length) {
  11246. body.append(data, data_length);
  11247. return true;
  11248. });
  11249. }
  11250. });
  11251. auto port = svr.bind_to_any_port("localhost");
  11252. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11253. auto se = detail::scope_exit([&] {
  11254. svr.stop();
  11255. t.join();
  11256. ASSERT_FALSE(svr.is_running());
  11257. });
  11258. svr.wait_until_ready();
  11259. {
  11260. std::string data(1024 * 1024 * 2, '.');
  11261. std::stringstream buffer;
  11262. buffer << data;
  11263. SSLClient cli("localhost", port);
  11264. cli.enable_server_certificate_verification(false);
  11265. UploadFormDataItems items{
  11266. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11267. {"hello", "world", "", ""},
  11268. };
  11269. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11271. ASSERT_EQ(StatusCode::OK_200, res->status);
  11272. }
  11273. }
  11274. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11275. std::string data(1024 * 1024 * 2, '&');
  11276. std::stringstream buffer;
  11277. buffer << data;
  11278. Client cli("https://localhost:8080");
  11279. UploadFormDataItems items{
  11280. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11281. {"hello", "world", "", ""},
  11282. };
  11283. for (const char &c : " \t\r\n") {
  11284. auto res =
  11285. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11286. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11287. ASSERT_FALSE(res);
  11288. }
  11289. }
  11290. TEST(MultipartFormDataTest, PutFormData) {
  11291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11292. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11293. const ContentReader &content_reader) {
  11294. if (req.is_multipart_form_data()) {
  11295. std::vector<FormData> items;
  11296. content_reader(
  11297. [&](const FormData &file) {
  11298. items.push_back(file);
  11299. return true;
  11300. },
  11301. [&](const char *data, size_t data_length) {
  11302. items.back().content.append(data, data_length);
  11303. return true;
  11304. });
  11305. EXPECT_TRUE(std::string(items[0].name) == "document");
  11306. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11307. EXPECT_TRUE(items[0].filename == "2MB_data");
  11308. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11309. EXPECT_TRUE(items[1].name == "hello");
  11310. EXPECT_TRUE(items[1].content == "world");
  11311. EXPECT_TRUE(items[1].filename == "");
  11312. EXPECT_TRUE(items[1].content_type == "");
  11313. } else {
  11314. std::string body;
  11315. content_reader([&](const char *data, size_t data_length) {
  11316. body.append(data, data_length);
  11317. return true;
  11318. });
  11319. }
  11320. });
  11321. auto port = svr.bind_to_any_port("localhost");
  11322. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11323. auto se = detail::scope_exit([&] {
  11324. svr.stop();
  11325. t.join();
  11326. ASSERT_FALSE(svr.is_running());
  11327. });
  11328. svr.wait_until_ready();
  11329. {
  11330. std::string data(1024 * 1024 * 2, '&');
  11331. std::stringstream buffer;
  11332. buffer << data;
  11333. SSLClient cli("localhost", port);
  11334. cli.enable_server_certificate_verification(false);
  11335. UploadFormDataItems items{
  11336. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11337. {"hello", "world", "", ""},
  11338. };
  11339. auto res = cli.Put("/put", items);
  11340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11341. ASSERT_EQ(StatusCode::OK_200, res->status);
  11342. }
  11343. }
  11344. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11346. svr.Put("/put_customboundary",
  11347. [&](const Request &req, const Response & /*res*/,
  11348. const ContentReader &content_reader) {
  11349. if (req.is_multipart_form_data()) {
  11350. std::vector<FormData> items;
  11351. content_reader(
  11352. [&](const FormData &file) {
  11353. items.push_back(file);
  11354. return true;
  11355. },
  11356. [&](const char *data, size_t data_length) {
  11357. items.back().content.append(data, data_length);
  11358. return true;
  11359. });
  11360. EXPECT_TRUE(std::string(items[0].name) == "document");
  11361. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11362. EXPECT_TRUE(items[0].filename == "2MB_data");
  11363. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11364. EXPECT_TRUE(items[1].name == "hello");
  11365. EXPECT_TRUE(items[1].content == "world");
  11366. EXPECT_TRUE(items[1].filename == "");
  11367. EXPECT_TRUE(items[1].content_type == "");
  11368. } else {
  11369. std::string body;
  11370. content_reader([&](const char *data, size_t data_length) {
  11371. body.append(data, data_length);
  11372. return true;
  11373. });
  11374. }
  11375. });
  11376. auto port = svr.bind_to_any_port("localhost");
  11377. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. t.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. {
  11385. std::string data(1024 * 1024 * 2, '&');
  11386. std::stringstream buffer;
  11387. buffer << data;
  11388. SSLClient cli("localhost", port);
  11389. cli.enable_server_certificate_verification(false);
  11390. UploadFormDataItems items{
  11391. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11392. {"hello", "world", "", ""},
  11393. };
  11394. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11396. ASSERT_EQ(StatusCode::OK_200, res->status);
  11397. }
  11398. }
  11399. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11400. std::string data(1024 * 1024 * 2, '&');
  11401. std::stringstream buffer;
  11402. buffer << data;
  11403. Client cli("https://localhost:8080");
  11404. cli.enable_server_certificate_verification(false);
  11405. UploadFormDataItems items{
  11406. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11407. {"hello", "world", "", ""},
  11408. };
  11409. for (const char &c : " \t\r\n") {
  11410. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11411. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11412. ASSERT_FALSE(res);
  11413. }
  11414. }
  11415. TEST(MultipartFormDataTest, AlternateFilename) {
  11416. auto handled = false;
  11417. Server svr;
  11418. svr.Post("/test", [&](const Request &req, Response &res) {
  11419. ASSERT_EQ(2u, req.form.files.size());
  11420. ASSERT_EQ(1u, req.form.fields.size());
  11421. // Test files
  11422. const auto &file1 = req.form.get_file("file1");
  11423. ASSERT_EQ("file1", file1.name);
  11424. ASSERT_EQ("A.txt", file1.filename);
  11425. ASSERT_EQ("text/plain", file1.content_type);
  11426. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11427. const auto &file2 = req.form.get_file("file2");
  11428. ASSERT_EQ("file2", file2.name);
  11429. ASSERT_EQ("a.html", file2.filename);
  11430. ASSERT_EQ("text/html", file2.content_type);
  11431. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11432. file2.content);
  11433. // Test text field
  11434. const auto &text = req.form.get_field("text");
  11435. ASSERT_EQ("text default", text);
  11436. res.set_content("ok", "text/plain");
  11437. handled = true;
  11438. });
  11439. thread t = thread([&] { svr.listen(HOST, PORT); });
  11440. auto se = detail::scope_exit([&] {
  11441. svr.stop();
  11442. t.join();
  11443. ASSERT_FALSE(svr.is_running());
  11444. ASSERT_TRUE(handled);
  11445. });
  11446. svr.wait_until_ready();
  11447. auto req = "POST /test HTTP/1.1\r\n"
  11448. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11449. "Content-Length: 399\r\n"
  11450. "\r\n"
  11451. "----------\r\n"
  11452. "Content-Disposition: form-data; name=\"text\"\r\n"
  11453. "\r\n"
  11454. "text default\r\n"
  11455. "----------\r\n"
  11456. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11457. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11458. "Content-Type: text/plain\r\n"
  11459. "\r\n"
  11460. "Content of a.txt.\r\n"
  11461. "\r\n"
  11462. "----------\r\n"
  11463. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11464. "\"a.html\"\r\n"
  11465. "Content-Type: text/html\r\n"
  11466. "\r\n"
  11467. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11468. "\r\n"
  11469. "------------\r\n";
  11470. ASSERT_TRUE(send_request(1, req));
  11471. }
  11472. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11473. auto handled = false;
  11474. Server svr;
  11475. svr.Post("/test", [&](const Request &req, Response &res) {
  11476. // Case-insensitive "utf-8''" prefix with a long value
  11477. const auto &file = req.form.get_file("file1");
  11478. ASSERT_EQ("file1", file.name);
  11479. // 8000 chars exercises both the Content-Disposition parser and the
  11480. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11481. // Prior to the fix, std::regex_match on this header would cause O(N)
  11482. // stack recursion in libstdc++, leading to SIGSEGV.
  11483. std::string expected_filename(8000, 'A');
  11484. ASSERT_EQ(expected_filename, file.filename);
  11485. res.set_content("ok", "text/plain");
  11486. handled = true;
  11487. });
  11488. thread t = thread([&] { svr.listen(HOST, PORT); });
  11489. auto se = detail::scope_exit([&] {
  11490. svr.stop();
  11491. t.join();
  11492. ASSERT_FALSE(svr.is_running());
  11493. ASSERT_TRUE(handled);
  11494. });
  11495. svr.wait_until_ready();
  11496. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11497. // Regression test for GHSA-qq6v-r583-3h69
  11498. std::string long_filename(8000, 'A');
  11499. std::string body = "----------\r\n"
  11500. "Content-Disposition: form-data; name=\"file1\"; "
  11501. "filename*=\"Utf-8''" +
  11502. long_filename +
  11503. "\"\r\n"
  11504. "\r\n"
  11505. "hello\r\n"
  11506. "------------\r\n";
  11507. auto req = "POST /test HTTP/1.1\r\n"
  11508. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11509. "Content-Length: " +
  11510. std::to_string(body.size()) + "\r\n\r\n" + body;
  11511. ASSERT_TRUE(send_request(1, req));
  11512. }
  11513. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11514. auto handled = false;
  11515. Server svr;
  11516. svr.Post("/test", [&](const Request &req, Response &) {
  11517. ASSERT_EQ(2u, req.form.fields.size());
  11518. const auto &text1 = req.form.get_field("text1");
  11519. ASSERT_EQ("text1", text1);
  11520. const auto &text2 = req.form.get_field("text2");
  11521. ASSERT_EQ("text2", text2);
  11522. handled = true;
  11523. });
  11524. thread t = thread([&] { svr.listen(HOST, PORT); });
  11525. auto se = detail::scope_exit([&] {
  11526. svr.stop();
  11527. t.join();
  11528. ASSERT_FALSE(svr.is_running());
  11529. ASSERT_TRUE(handled);
  11530. });
  11531. svr.wait_until_ready();
  11532. auto req = "POST /test HTTP/1.1\r\n"
  11533. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11534. "Content-Length: 146\r\n"
  11535. "\r\n----------\r\n"
  11536. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11537. "\r\n"
  11538. "text1"
  11539. "\r\n----------\r\n"
  11540. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11541. "\r\n"
  11542. "text2"
  11543. "\r\n------------";
  11544. std::string response;
  11545. ASSERT_TRUE(send_request(1, req, &response));
  11546. ASSERT_EQ("200", response.substr(9, 3));
  11547. }
  11548. TEST(MultipartFormDataTest, ContentLength) {
  11549. auto handled = false;
  11550. Server svr;
  11551. svr.Post("/test", [&](const Request &req, Response &) {
  11552. ASSERT_EQ(2u, req.form.fields.size());
  11553. const auto &text1 = req.form.get_field("text1");
  11554. ASSERT_EQ("text1", text1);
  11555. const auto &text2 = req.form.get_field("text2");
  11556. ASSERT_EQ("text2", text2);
  11557. handled = true;
  11558. });
  11559. thread t = thread([&] { svr.listen(HOST, PORT); });
  11560. auto se = detail::scope_exit([&] {
  11561. svr.stop();
  11562. t.join();
  11563. ASSERT_FALSE(svr.is_running());
  11564. ASSERT_TRUE(handled);
  11565. });
  11566. svr.wait_until_ready();
  11567. auto req = "POST /test HTTP/1.1\r\n"
  11568. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11569. "Content-Length: 167\r\n"
  11570. "\r\n----------\r\n"
  11571. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11572. "Content-Length: 5\r\n"
  11573. "\r\n"
  11574. "text1"
  11575. "\r\n----------\r\n"
  11576. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11577. "\r\n"
  11578. "text2"
  11579. "\r\n------------\r\n";
  11580. std::string response;
  11581. ASSERT_TRUE(send_request(1, req, &response));
  11582. ASSERT_EQ("200", response.substr(9, 3));
  11583. }
  11584. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11585. auto handled = false;
  11586. Server svr;
  11587. svr.Post("/test", [&](const Request &req, Response &) {
  11588. ASSERT_EQ(2u, req.form.fields.size());
  11589. const auto &text1 = req.form.get_field("text1");
  11590. ASSERT_EQ("text1", text1);
  11591. // TODO: Add header access for text fields if needed
  11592. const auto &text2 = req.form.get_field("text2");
  11593. ASSERT_EQ("text2", text2);
  11594. // TODO: Header access for text fields needs to be implemented
  11595. // auto &headers = it->second.headers;
  11596. // ASSERT_EQ(3U, headers.size());
  11597. // auto custom_header = headers.find("x-whatever");
  11598. // ASSERT_TRUE(custom_header != headers.end());
  11599. // ASSERT_NE("customvalue", custom_header->second);
  11600. // ASSERT_EQ("CustomValue", custom_header->second);
  11601. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11602. handled = true;
  11603. });
  11604. thread t = thread([&] { svr.listen(HOST, PORT); });
  11605. auto se = detail::scope_exit([&] {
  11606. svr.stop();
  11607. t.join();
  11608. ASSERT_FALSE(svr.is_running());
  11609. ASSERT_TRUE(handled);
  11610. });
  11611. svr.wait_until_ready();
  11612. auto req = "POST /test HTTP/1.1\r\n"
  11613. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11614. "Content-Length: 232\r\n"
  11615. "\r\n----------\r\n"
  11616. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11617. "Content-Length: 5\r\n"
  11618. "X-Test: 1\r\n"
  11619. "\r\n"
  11620. "text1"
  11621. "\r\n----------\r\n"
  11622. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11623. "Content-Type: text/plain\r\n"
  11624. "X-Whatever: CustomValue\r\n"
  11625. "\r\n"
  11626. "text2"
  11627. "\r\n------------\r\n"
  11628. "That should be disregarded. Not even read";
  11629. std::string response;
  11630. ASSERT_TRUE(send_request(1, req, &response));
  11631. ASSERT_EQ("200", response.substr(9, 3));
  11632. }
  11633. TEST(MultipartFormDataTest, LargeHeader) {
  11634. auto handled = false;
  11635. Server svr;
  11636. svr.Post("/test", [&](const Request &req, Response &) {
  11637. ASSERT_EQ(1u, req.form.fields.size());
  11638. const auto &text = req.form.get_field("name1");
  11639. ASSERT_EQ("text1", text);
  11640. handled = true;
  11641. });
  11642. thread t = thread([&] { svr.listen(HOST, PORT); });
  11643. auto se = detail::scope_exit([&] {
  11644. svr.stop();
  11645. t.join();
  11646. ASSERT_FALSE(svr.is_running());
  11647. ASSERT_TRUE(handled);
  11648. });
  11649. svr.wait_until_ready();
  11650. auto boundary = std::string("cpp-httplib-multipart-data");
  11651. std::string content = "--" + boundary +
  11652. "\r\n"
  11653. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11654. "\r\n"
  11655. "text1\r\n"
  11656. "--" +
  11657. boundary + "--\r\n";
  11658. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11659. "Content-Type: multipart/form-data;boundary=" +
  11660. boundary +
  11661. "\r\n"
  11662. "Content-Length: " +
  11663. std::to_string(content.size()) +
  11664. "\r\n"
  11665. "Dummy-Header: ";
  11666. std::string header_suffix = "\r\n"
  11667. "\r\n";
  11668. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11669. size_t header_dummy_size =
  11670. read_buff_size -
  11671. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11672. auto header_dummy = std::string(header_dummy_size, '@');
  11673. auto req = header_prefix + header_dummy + header_suffix + content;
  11674. std::string response;
  11675. ASSERT_TRUE(send_request(1, req, &response));
  11676. ASSERT_EQ("200", response.substr(9, 3));
  11677. }
  11678. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11679. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11680. // (not chunked Transfer-Encoding) after the streaming refactor.
  11681. auto handled = false;
  11682. Server svr;
  11683. svr.Post("/upload", [&](const Request &req, Response &res) {
  11684. auto cl_it = req.headers.find("Content-Length");
  11685. EXPECT_TRUE(cl_it != req.headers.end());
  11686. auto te_it = req.headers.find("Transfer-Encoding");
  11687. EXPECT_TRUE(te_it == req.headers.end());
  11688. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11689. res.set_content("ok", "text/plain");
  11690. handled = true;
  11691. });
  11692. auto port = svr.bind_to_any_port(HOST);
  11693. auto t = thread([&] { svr.listen_after_bind(); });
  11694. auto se = detail::scope_exit([&] {
  11695. svr.stop();
  11696. t.join();
  11697. ASSERT_FALSE(svr.is_running());
  11698. ASSERT_TRUE(handled);
  11699. });
  11700. svr.wait_until_ready();
  11701. UploadFormDataItems items = {
  11702. {"field1", "hello", "", "text/plain"},
  11703. {"file1", "world", "test.txt", "application/octet-stream"},
  11704. };
  11705. Client cli(HOST, port);
  11706. auto res = cli.Post("/upload", {}, items);
  11707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11708. EXPECT_EQ(StatusCode::OK_200, res->status);
  11709. }
  11710. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11711. // Verify that make_multipart_content_provider coalesces many small segments
  11712. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11713. constexpr size_t kItemCount = 1000;
  11714. UploadFormDataItems items;
  11715. items.reserve(kItemCount);
  11716. for (size_t i = 0; i < kItemCount; i++) {
  11717. items.push_back(
  11718. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11719. }
  11720. const std::string boundary = "----test-boundary";
  11721. auto content_length = detail::get_multipart_content_length(items, boundary);
  11722. auto provider = detail::make_multipart_content_provider(items, boundary);
  11723. // Drive the provider the same way write_content_with_progress does
  11724. size_t write_count = 0;
  11725. size_t total_bytes = 0;
  11726. DataSink sink;
  11727. size_t offset = 0;
  11728. sink.write = [&](const char *d, size_t l) -> bool {
  11729. (void)d;
  11730. write_count++;
  11731. total_bytes += l;
  11732. offset += l;
  11733. return true;
  11734. };
  11735. sink.is_writable = []() -> bool { return true; };
  11736. while (offset < content_length) {
  11737. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11738. }
  11739. EXPECT_EQ(content_length, total_bytes);
  11740. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11741. // With buffering into 64KB blocks, write_count should be much smaller.
  11742. auto segment_count = 3 * kItemCount + 1;
  11743. EXPECT_LT(write_count, segment_count / 10);
  11744. }
  11745. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11746. // Integration test: send many UploadFormDataItems and verify the server
  11747. // receives all of them correctly (#2410).
  11748. constexpr size_t kItemCount = 500;
  11749. auto handled = false;
  11750. Server svr;
  11751. svr.Post("/upload", [&](const Request &req, Response &res) {
  11752. EXPECT_EQ(kItemCount, req.form.fields.size());
  11753. for (size_t i = 0; i < kItemCount; i++) {
  11754. auto key = "field" + std::to_string(i);
  11755. auto val = "value" + std::to_string(i);
  11756. auto it = req.form.fields.find(key);
  11757. if (it != req.form.fields.end()) {
  11758. EXPECT_EQ(val, it->second.content);
  11759. } else {
  11760. ADD_FAILURE() << "Missing field: " << key;
  11761. }
  11762. }
  11763. res.set_content("ok", "text/plain");
  11764. handled = true;
  11765. });
  11766. auto port = svr.bind_to_any_port(HOST);
  11767. auto t = thread([&] { svr.listen_after_bind(); });
  11768. auto se = detail::scope_exit([&] {
  11769. svr.stop();
  11770. t.join();
  11771. ASSERT_FALSE(svr.is_running());
  11772. ASSERT_TRUE(handled);
  11773. });
  11774. svr.wait_until_ready();
  11775. UploadFormDataItems items;
  11776. items.reserve(kItemCount);
  11777. for (size_t i = 0; i < kItemCount; i++) {
  11778. items.push_back(
  11779. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11780. }
  11781. Client cli(HOST, port);
  11782. auto res = cli.Post("/upload", items);
  11783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11784. EXPECT_EQ(StatusCode::OK_200, res->status);
  11785. }
  11786. TEST(MultipartFormDataTest, MakeFileProvider) {
  11787. // Verify make_file_provider sends a file's contents correctly.
  11788. const std::string file_content(4096, 'Z');
  11789. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11790. {
  11791. std::ofstream ofs(tmp_path, std::ios::binary);
  11792. ofs.write(file_content.data(),
  11793. static_cast<std::streamsize>(file_content.size()));
  11794. }
  11795. auto handled = false;
  11796. Server svr;
  11797. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11798. const ContentReader &content_reader) {
  11799. ASSERT_TRUE(req.is_multipart_form_data());
  11800. std::vector<FormData> items;
  11801. content_reader(
  11802. [&](const FormData &file) {
  11803. items.push_back(file);
  11804. return true;
  11805. },
  11806. [&](const char *data, size_t data_length) {
  11807. items.back().content.append(data, data_length);
  11808. return true;
  11809. });
  11810. ASSERT_EQ(1u, items.size());
  11811. EXPECT_EQ("myfile", items[0].name);
  11812. EXPECT_EQ("data.bin", items[0].filename);
  11813. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11814. EXPECT_EQ(file_content, items[0].content);
  11815. handled = true;
  11816. });
  11817. auto port = svr.bind_to_any_port(HOST);
  11818. auto t = thread([&] { svr.listen_after_bind(); });
  11819. auto se = detail::scope_exit([&] {
  11820. svr.stop();
  11821. t.join();
  11822. ASSERT_FALSE(svr.is_running());
  11823. ASSERT_TRUE(handled);
  11824. std::remove(tmp_path.c_str());
  11825. });
  11826. svr.wait_until_ready();
  11827. FormDataProviderItems providers;
  11828. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11829. "application/octet-stream"));
  11830. Client cli(HOST, port);
  11831. auto res = cli.Post("/upload", {}, {}, providers);
  11832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11833. EXPECT_EQ(StatusCode::OK_200, res->status);
  11834. }
  11835. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11836. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11837. // (100) headers is rejected with a 400 Bad Request response.
  11838. Server svr;
  11839. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11840. res.set_content("ok", "text/plain");
  11841. });
  11842. thread t = thread([&] { svr.listen(HOST, PORT); });
  11843. auto se = detail::scope_exit([&] {
  11844. svr.stop();
  11845. t.join();
  11846. ASSERT_FALSE(svr.is_running());
  11847. });
  11848. svr.wait_until_ready();
  11849. // Build a multipart part with 101 custom headers (exceeding
  11850. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11851. std::stringstream body;
  11852. body << "--simpleboundary\r\n"
  11853. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11854. for (int i = 0; i < 101; i++) {
  11855. body << "X-Custom-Header-" << i << ": value\r\n";
  11856. }
  11857. body << "\r\n"
  11858. << "value1\r\n"
  11859. << "--simpleboundary--\r\n";
  11860. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11861. Client cli(HOST, PORT);
  11862. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11864. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11865. }
  11866. TEST(MakeFileBodyTest, Basic) {
  11867. const std::string file_content(4096, 'Z');
  11868. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11869. {
  11870. std::ofstream ofs(tmp_path, std::ios::binary);
  11871. ofs.write(file_content.data(),
  11872. static_cast<std::streamsize>(file_content.size()));
  11873. }
  11874. auto handled = false;
  11875. Server svr;
  11876. svr.Post("/upload", [&](const Request &req, Response &res) {
  11877. EXPECT_EQ(file_content, req.body);
  11878. handled = true;
  11879. res.status = StatusCode::OK_200;
  11880. });
  11881. auto port = svr.bind_to_any_port(HOST);
  11882. auto t = thread([&] { svr.listen_after_bind(); });
  11883. auto se = detail::scope_exit([&] {
  11884. svr.stop();
  11885. t.join();
  11886. ASSERT_FALSE(svr.is_running());
  11887. ASSERT_TRUE(handled);
  11888. std::remove(tmp_path.c_str());
  11889. });
  11890. svr.wait_until_ready();
  11891. auto fb = make_file_body(tmp_path);
  11892. ASSERT_GT(fb.first, 0u);
  11893. Client cli(HOST, port);
  11894. auto res =
  11895. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11897. EXPECT_EQ(StatusCode::OK_200, res->status);
  11898. }
  11899. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11900. static constexpr unsigned int number_of_tasks{1000000};
  11901. std::atomic_uint count{0};
  11902. std::unique_ptr<TaskQueue> task_queue{
  11903. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11904. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11905. auto queued = task_queue->enqueue(
  11906. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11907. EXPECT_TRUE(queued);
  11908. }
  11909. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11910. task_queue->shutdown();
  11911. #else
  11912. EXPECT_NO_THROW(task_queue->shutdown());
  11913. #endif
  11914. EXPECT_EQ(number_of_tasks, count.load());
  11915. }
  11916. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11917. static constexpr unsigned int number_of_tasks{1000000};
  11918. static constexpr unsigned int qlimit{2};
  11919. unsigned int queued_count{0};
  11920. std::atomic_uint count{0};
  11921. std::unique_ptr<TaskQueue> task_queue{
  11922. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11923. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11924. if (task_queue->enqueue(
  11925. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11926. queued_count++;
  11927. }
  11928. }
  11929. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11930. task_queue->shutdown();
  11931. #else
  11932. EXPECT_NO_THROW(task_queue->shutdown());
  11933. #endif
  11934. EXPECT_EQ(queued_count, count.load());
  11935. EXPECT_TRUE(queued_count <= number_of_tasks);
  11936. EXPECT_TRUE(queued_count >= qlimit);
  11937. }
  11938. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11939. // Use a short idle timeout so a dynamic thread spawns, times out and
  11940. // exits during the test, and the pool keeps working afterwards.
  11941. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11942. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11943. /*idle_timeout_sec=*/1}};
  11944. std::atomic_uint count{0};
  11945. std::condition_variable cv;
  11946. std::mutex mtx;
  11947. bool release = false;
  11948. // Block the base thread so the second task spawns a dynamic thread.
  11949. EXPECT_TRUE(task_queue->enqueue([&] {
  11950. std::unique_lock<std::mutex> lock(mtx);
  11951. while (!release) {
  11952. cv.wait(lock);
  11953. }
  11954. count++;
  11955. }));
  11956. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11957. // Let the dynamic thread finish its task and exceed the idle timeout.
  11958. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11959. {
  11960. std::unique_lock<std::mutex> lock(mtx);
  11961. release = true;
  11962. }
  11963. cv.notify_all();
  11964. // The pool must still accept and run tasks after the dynamic thread exited.
  11965. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11966. task_queue->shutdown();
  11967. EXPECT_EQ(3u, count.load());
  11968. }
  11969. TEST(TaskQueueTest, MaxQueuedRequests) {
  11970. static constexpr unsigned int qlimit{3};
  11971. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11972. std::condition_variable sem_cv;
  11973. std::mutex sem_mtx;
  11974. int credits = 0;
  11975. bool queued;
  11976. /* Fill up the queue with tasks that will block until we give them credits to
  11977. * complete. */
  11978. for (unsigned int n = 0; n <= qlimit;) {
  11979. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11980. std::unique_lock<std::mutex> lock(sem_mtx);
  11981. while (credits <= 0) {
  11982. sem_cv.wait(lock);
  11983. }
  11984. /* Consume the credit and signal the test code if they are all gone. */
  11985. if (--credits == 0) { sem_cv.notify_one(); }
  11986. });
  11987. if (n < qlimit) {
  11988. /* The first qlimit enqueues must succeed. */
  11989. EXPECT_TRUE(queued);
  11990. } else {
  11991. /* The last one will succeed only when the worker thread
  11992. * starts and dequeues the first blocking task. Although
  11993. * not necessary for the correctness of this test, we sleep for
  11994. * a short while to avoid busy waiting. */
  11995. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11996. }
  11997. if (queued) { n++; }
  11998. }
  11999. /* Further enqueues must fail since the queue is full. */
  12000. for (auto i = 0; i < 4; i++) {
  12001. queued = task_queue->enqueue([] {});
  12002. EXPECT_FALSE(queued);
  12003. }
  12004. /* Give the credits to allow the previous tasks to complete. */
  12005. {
  12006. std::unique_lock<std::mutex> lock(sem_mtx);
  12007. credits += qlimit + 1;
  12008. }
  12009. sem_cv.notify_all();
  12010. /* Wait for all the credits to be consumed. */
  12011. {
  12012. std::unique_lock<std::mutex> lock(sem_mtx);
  12013. while (credits > 0) {
  12014. sem_cv.wait(lock);
  12015. }
  12016. }
  12017. /* Check that we are able again to enqueue at least qlimit tasks. */
  12018. for (unsigned int i = 0; i < qlimit; i++) {
  12019. queued = task_queue->enqueue([] {});
  12020. EXPECT_TRUE(queued);
  12021. }
  12022. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12023. task_queue->shutdown();
  12024. #else
  12025. EXPECT_NO_THROW(task_queue->shutdown());
  12026. #endif
  12027. }
  12028. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12029. Server svr;
  12030. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12031. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12032. });
  12033. svr.Get("/hello", [](const Request &req, Response &res) {
  12034. res.set_content(req.get_param_value("key"), "text/plain");
  12035. });
  12036. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12037. auto se = detail::scope_exit([&] {
  12038. svr.stop();
  12039. thread.join();
  12040. ASSERT_FALSE(svr.is_running());
  12041. });
  12042. svr.wait_until_ready();
  12043. {
  12044. Client cli(HOST, PORT);
  12045. cli.set_follow_location(true);
  12046. auto res = cli.Get("/");
  12047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12048. EXPECT_EQ(StatusCode::OK_200, res->status);
  12049. EXPECT_EQ("val&key2=val2", res->body);
  12050. }
  12051. }
  12052. #endif
  12053. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12054. Server svr;
  12055. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12056. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12057. });
  12058. svr.Get("/hello", [](const Request &req, Response &res) {
  12059. res.set_content(req.get_param_value("key"), "text/plain");
  12060. });
  12061. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12062. auto se = detail::scope_exit([&] {
  12063. svr.stop();
  12064. thread.join();
  12065. ASSERT_FALSE(svr.is_running());
  12066. });
  12067. svr.wait_until_ready();
  12068. {
  12069. Client cli(HOST, PORT);
  12070. cli.set_follow_location(true);
  12071. auto res = cli.Get("/");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_EQ(StatusCode::OK_200, res->status);
  12074. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12075. }
  12076. }
  12077. TEST(RedirectTest, RedirectWithPlusInPath) {
  12078. Server svr;
  12079. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12080. res.set_redirect("/a+b");
  12081. });
  12082. // Route pattern uses regex; escape + as \\+
  12083. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12084. res.set_content(req.path, "text/plain");
  12085. });
  12086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12087. auto se = detail::scope_exit([&] {
  12088. svr.stop();
  12089. thread.join();
  12090. ASSERT_FALSE(svr.is_running());
  12091. });
  12092. svr.wait_until_ready();
  12093. {
  12094. Client cli(HOST, PORT);
  12095. cli.set_follow_location(true);
  12096. auto res = cli.Get("/");
  12097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12098. EXPECT_EQ(StatusCode::OK_200, res->status);
  12099. EXPECT_EQ("/a+b", res->body);
  12100. }
  12101. }
  12102. #ifdef CPPHTTPLIB_SSL_ENABLED
  12103. TEST(RedirectTest, Issue2185_Online) {
  12104. SSLClient client("github.com");
  12105. client.set_follow_location(true);
  12106. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12107. "Coollab-Windows.zip");
  12108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12109. EXPECT_EQ(StatusCode::OK_200, res->status);
  12110. EXPECT_EQ(9920427U, res->body.size());
  12111. }
  12112. #endif
  12113. TEST(VulnerabilityTest, CRLFInjection) {
  12114. Server svr;
  12115. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12116. res.set_content("Hello 1", "text/plain");
  12117. });
  12118. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12119. res.set_content("Hello 2", "text/plain");
  12120. });
  12121. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12122. res.set_content("Hello 3", "text/plain");
  12123. });
  12124. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12125. res.set_content("Hello 4", "text/plain");
  12126. });
  12127. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12128. for (const auto &x : req.headers) {
  12129. auto key = x.first;
  12130. EXPECT_STRNE("evil", key.c_str());
  12131. }
  12132. });
  12133. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12134. auto se = detail::scope_exit([&] {
  12135. svr.stop();
  12136. thread.join();
  12137. ASSERT_FALSE(svr.is_running());
  12138. });
  12139. svr.wait_until_ready();
  12140. {
  12141. Client cli(HOST, PORT);
  12142. cli.Post("/test1", "A=B",
  12143. "application/x-www-form-urlencoded\r\nevil: hello1");
  12144. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12145. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12146. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12147. }
  12148. }
  12149. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12150. auto server_thread = std::thread([] {
  12151. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12152. default_socket_options(srv);
  12153. sockaddr_in addr{};
  12154. addr.sin_family = AF_INET;
  12155. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12156. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12157. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12158. ::listen(srv, 1);
  12159. sockaddr_in cli_addr{};
  12160. socklen_t cli_len = sizeof(cli_addr);
  12161. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12162. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12163. std::string buf_all;
  12164. char buf[2048];
  12165. ssize_t n;
  12166. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12167. buf_all.append(buf, static_cast<size_t>(n));
  12168. size_t pos;
  12169. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12170. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12171. auto e = request_block.find("\r\n");
  12172. if (e != std::string::npos) {
  12173. auto request_line = request_block.substr(0, e);
  12174. std::string msg =
  12175. "CRLF injection detected in request line: '" + request_line + "'";
  12176. EXPECT_FALSE(true) << msg;
  12177. }
  12178. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12179. ::send(cli,
  12180. #ifdef _WIN32
  12181. static_cast<const char *>(resp.c_str()),
  12182. static_cast<int>(resp.size()),
  12183. #else
  12184. resp.c_str(), resp.size(),
  12185. #endif
  12186. 0);
  12187. buf_all.erase(0, pos + 4);
  12188. }
  12189. }
  12190. detail::close_socket(cli);
  12191. detail::close_socket(srv);
  12192. });
  12193. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12194. auto cli = Client("127.0.0.1", PORT + 1);
  12195. auto headers = Headers{
  12196. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12197. {"Connection", "keep-alive"}};
  12198. auto res = cli.Get("/hi", headers);
  12199. EXPECT_FALSE(res);
  12200. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12201. server_thread.join();
  12202. }
  12203. TEST(PathParamsTest, StaticMatch) {
  12204. const auto pattern = "/users/all";
  12205. detail::PathParamsMatcher matcher(pattern);
  12206. Request request;
  12207. request.path = "/users/all";
  12208. ASSERT_TRUE(matcher.match(request));
  12209. std::unordered_map<std::string, std::string> expected_params = {};
  12210. EXPECT_EQ(request.path_params, expected_params);
  12211. }
  12212. TEST(PathParamsTest, StaticMismatch) {
  12213. const auto pattern = "/users/all";
  12214. detail::PathParamsMatcher matcher(pattern);
  12215. Request request;
  12216. request.path = "/users/1";
  12217. ASSERT_FALSE(matcher.match(request));
  12218. }
  12219. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12220. const auto pattern = "/users/:id/subscriptions";
  12221. detail::PathParamsMatcher matcher(pattern);
  12222. Request request;
  12223. request.path = "/users/42/subscriptions";
  12224. ASSERT_TRUE(matcher.match(request));
  12225. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12226. EXPECT_EQ(request.path_params, expected_params);
  12227. }
  12228. TEST(PathParamsTest, SingleParamInTheEnd) {
  12229. const auto pattern = "/users/:id";
  12230. detail::PathParamsMatcher matcher(pattern);
  12231. Request request;
  12232. request.path = "/users/24";
  12233. ASSERT_TRUE(matcher.match(request));
  12234. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12235. EXPECT_EQ(request.path_params, expected_params);
  12236. }
  12237. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12238. const auto pattern = "/users/:id/";
  12239. detail::PathParamsMatcher matcher(pattern);
  12240. Request request;
  12241. request.path = "/users/42/";
  12242. ASSERT_TRUE(matcher.match(request));
  12243. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12244. EXPECT_EQ(request.path_params, expected_params);
  12245. }
  12246. TEST(PathParamsTest, EmptyParam) {
  12247. const auto pattern = "/users/:id/";
  12248. detail::PathParamsMatcher matcher(pattern);
  12249. Request request;
  12250. request.path = "/users//";
  12251. ASSERT_TRUE(matcher.match(request));
  12252. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12253. EXPECT_EQ(request.path_params, expected_params);
  12254. }
  12255. TEST(PathParamsTest, FragmentMismatch) {
  12256. const auto pattern = "/users/:id/";
  12257. detail::PathParamsMatcher matcher(pattern);
  12258. Request request;
  12259. request.path = "/admins/24/";
  12260. ASSERT_FALSE(matcher.match(request));
  12261. }
  12262. TEST(PathParamsTest, ExtraFragments) {
  12263. const auto pattern = "/users/:id";
  12264. detail::PathParamsMatcher matcher(pattern);
  12265. Request request;
  12266. request.path = "/users/42/subscriptions";
  12267. ASSERT_FALSE(matcher.match(request));
  12268. }
  12269. TEST(PathParamsTest, MissingTrailingParam) {
  12270. const auto pattern = "/users/:id";
  12271. detail::PathParamsMatcher matcher(pattern);
  12272. Request request;
  12273. request.path = "/users";
  12274. ASSERT_FALSE(matcher.match(request));
  12275. }
  12276. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12277. const auto pattern = "/users/:id/subscriptions";
  12278. detail::PathParamsMatcher matcher(pattern);
  12279. Request request;
  12280. request.path = "/users/subscriptions";
  12281. ASSERT_FALSE(matcher.match(request));
  12282. }
  12283. TEST(PathParamsTest, MultipleParams) {
  12284. const auto pattern = "/users/:userid/subscriptions/:subid";
  12285. detail::PathParamsMatcher matcher(pattern);
  12286. Request request;
  12287. request.path = "/users/42/subscriptions/2";
  12288. ASSERT_TRUE(matcher.match(request));
  12289. std::unordered_map<std::string, std::string> expected_params = {
  12290. {"userid", "42"}, {"subid", "2"}};
  12291. EXPECT_EQ(request.path_params, expected_params);
  12292. }
  12293. TEST(PathParamsTest, SequenceOfParams) {
  12294. const auto pattern = "/values/:x/:y/:z";
  12295. detail::PathParamsMatcher matcher(pattern);
  12296. Request request;
  12297. request.path = "/values/1/2/3";
  12298. ASSERT_TRUE(matcher.match(request));
  12299. std::unordered_map<std::string, std::string> expected_params = {
  12300. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12301. EXPECT_EQ(request.path_params, expected_params);
  12302. }
  12303. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12304. const auto pattern = "/prefix:suffix";
  12305. detail::PathParamsMatcher matcher(pattern);
  12306. Request request;
  12307. request.path = "/prefix:suffix";
  12308. ASSERT_TRUE(matcher.match(request));
  12309. const std::unordered_map<std::string, std::string> expected_params = {};
  12310. EXPECT_EQ(request.path_params, expected_params);
  12311. }
  12312. TEST(ParseUrlTest, VariousPatterns) {
  12313. {
  12314. detail::UrlComponents uc;
  12315. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12316. EXPECT_EQ("http", uc.scheme);
  12317. EXPECT_EQ("example.com", uc.host);
  12318. EXPECT_EQ("8080", uc.port);
  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("https://example.com/path", uc));
  12325. EXPECT_EQ("https", uc.scheme);
  12326. EXPECT_EQ("example.com", uc.host);
  12327. EXPECT_TRUE(uc.port.empty());
  12328. EXPECT_EQ("/path", uc.path);
  12329. }
  12330. {
  12331. detail::UrlComponents uc;
  12332. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12333. EXPECT_EQ("::1", uc.host);
  12334. EXPECT_EQ("8080", uc.port);
  12335. EXPECT_EQ("/path", uc.path);
  12336. }
  12337. {
  12338. detail::UrlComponents uc;
  12339. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12340. }
  12341. {
  12342. detail::UrlComponents uc;
  12343. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12344. EXPECT_TRUE(uc.scheme.empty());
  12345. EXPECT_EQ("example.com", uc.host);
  12346. EXPECT_EQ("/path", uc.path);
  12347. EXPECT_EQ("?q=1", uc.query);
  12348. }
  12349. {
  12350. detail::UrlComponents uc;
  12351. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12352. EXPECT_TRUE(uc.host.empty());
  12353. EXPECT_EQ("/path", uc.path);
  12354. EXPECT_EQ("?q=1", uc.query);
  12355. }
  12356. {
  12357. detail::UrlComponents uc;
  12358. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12359. EXPECT_EQ("example.com", uc.host);
  12360. EXPECT_EQ("8080", uc.port);
  12361. }
  12362. {
  12363. // Unix socket path — must not be parsed as host
  12364. detail::UrlComponents uc;
  12365. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12366. EXPECT_TRUE(uc.host.empty());
  12367. }
  12368. {
  12369. detail::UrlComponents uc;
  12370. ASSERT_TRUE(detail::parse_url("", uc));
  12371. EXPECT_TRUE(uc.host.empty());
  12372. EXPECT_TRUE(uc.path.empty());
  12373. }
  12374. {
  12375. detail::UrlComponents uc;
  12376. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12377. }
  12378. {
  12379. detail::UrlComponents uc;
  12380. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12381. }
  12382. {
  12383. // Accepted by parse_url; callers restrict to http/https
  12384. detail::UrlComponents uc;
  12385. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12386. EXPECT_EQ("ftp", uc.scheme);
  12387. }
  12388. {
  12389. detail::UrlComponents uc;
  12390. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12391. }
  12392. {
  12393. detail::UrlComponents uc;
  12394. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12395. }
  12396. }
  12397. TEST(ParseUrlTest, FragmentHandling) {
  12398. {
  12399. detail::UrlComponents uc;
  12400. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12401. EXPECT_EQ("/path", uc.path);
  12402. EXPECT_TRUE(uc.query.empty());
  12403. }
  12404. {
  12405. detail::UrlComponents uc;
  12406. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12407. EXPECT_TRUE(uc.path.empty());
  12408. EXPECT_TRUE(uc.query.empty());
  12409. }
  12410. }
  12411. TEST(ParseUrlTest, UserinfoHandling) {
  12412. // Userinfo with @ but no colon — host includes @
  12413. detail::UrlComponents uc;
  12414. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12415. EXPECT_EQ("user@host.com", uc.host);
  12416. EXPECT_EQ("/path", uc.path);
  12417. }
  12418. TEST(ParseUrlTest, IPv6EdgeCases) {
  12419. {
  12420. detail::UrlComponents uc;
  12421. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12422. EXPECT_TRUE(uc.scheme.empty());
  12423. EXPECT_EQ("::1", uc.host);
  12424. EXPECT_EQ("8080", uc.port);
  12425. }
  12426. {
  12427. // Zone ID '%25' is not in [a-fA-F0-9:]
  12428. detail::UrlComponents uc;
  12429. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12430. }
  12431. }
  12432. TEST(ParseUrlTest, SchemeEdgeCases) {
  12433. {
  12434. detail::UrlComponents uc;
  12435. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12436. }
  12437. {
  12438. detail::UrlComponents uc;
  12439. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12440. }
  12441. {
  12442. detail::UrlComponents uc;
  12443. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12444. }
  12445. }
  12446. TEST(ParseUrlTest, PortEdgeCases) {
  12447. {
  12448. detail::UrlComponents uc;
  12449. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12450. EXPECT_TRUE(uc.port.empty());
  12451. EXPECT_EQ("/path", uc.path);
  12452. }
  12453. {
  12454. // parse_url accepts any port string; validation is done by parse_port
  12455. detail::UrlComponents uc;
  12456. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12457. EXPECT_EQ("abc", uc.port);
  12458. }
  12459. }
  12460. TEST(ParseUrlTest, WebSocketPatterns) {
  12461. {
  12462. detail::UrlComponents uc;
  12463. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12464. EXPECT_EQ("ws", uc.scheme);
  12465. EXPECT_EQ("echo.example.com", uc.host);
  12466. EXPECT_EQ("8080", uc.port);
  12467. EXPECT_EQ("/ws", uc.path);
  12468. }
  12469. {
  12470. detail::UrlComponents uc;
  12471. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12472. EXPECT_EQ("wss", uc.scheme);
  12473. EXPECT_EQ("echo.example.com", uc.host);
  12474. EXPECT_TRUE(uc.port.empty());
  12475. EXPECT_EQ("/ws", uc.path);
  12476. }
  12477. }
  12478. TEST(ParseUrlTest, QueryOnly) {
  12479. detail::UrlComponents uc;
  12480. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12481. EXPECT_TRUE(uc.host.empty());
  12482. EXPECT_TRUE(uc.path.empty());
  12483. EXPECT_EQ("?q=1&r=2", uc.query);
  12484. }
  12485. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12486. detail::UrlComponents uc;
  12487. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12488. EXPECT_TRUE(uc.scheme.empty());
  12489. EXPECT_EQ("example.com", uc.host);
  12490. EXPECT_EQ("443", uc.port);
  12491. EXPECT_EQ("/path", uc.path);
  12492. }
  12493. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12494. // If ipv6 regex working, regex match codepath is taken.
  12495. // else port will default to 80 in Client impl
  12496. int clientImplMagicPort = 80;
  12497. int port = 4321;
  12498. // above ports must be different to avoid false negative
  12499. EXPECT_NE(clientImplMagicPort, port);
  12500. std::string ipV6TestURL = "http://[ff06::c3]";
  12501. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12502. CLIENT_PRIVATE_KEY_FILE);
  12503. EXPECT_EQ(cli.port(), port);
  12504. }
  12505. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12506. auto file_path = "./www/dir/index.html";
  12507. auto dir_path = "./www/dir";
  12508. detail::FileStat stat_file(file_path);
  12509. EXPECT_TRUE(stat_file.is_file());
  12510. EXPECT_FALSE(stat_file.is_dir());
  12511. detail::FileStat stat_dir(dir_path);
  12512. EXPECT_FALSE(stat_dir.is_file());
  12513. EXPECT_TRUE(stat_dir.is_dir());
  12514. }
  12515. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12516. // IPv4 with default HTTP port (80)
  12517. EXPECT_EQ("example.com",
  12518. detail::make_host_and_port_string("example.com", 80, false));
  12519. // IPv4 with default HTTPS port (443)
  12520. EXPECT_EQ("example.com",
  12521. detail::make_host_and_port_string("example.com", 443, true));
  12522. // IPv4 with non-default HTTP port
  12523. EXPECT_EQ("example.com:8080",
  12524. detail::make_host_and_port_string("example.com", 8080, false));
  12525. // IPv4 with non-default HTTPS port
  12526. EXPECT_EQ("example.com:8443",
  12527. detail::make_host_and_port_string("example.com", 8443, true));
  12528. // IPv6 with default HTTP port (80)
  12529. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12530. // IPv6 with default HTTPS port (443)
  12531. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12532. // IPv6 with non-default HTTP port
  12533. EXPECT_EQ("[::1]:8080",
  12534. detail::make_host_and_port_string("::1", 8080, false));
  12535. // IPv6 with non-default HTTPS port
  12536. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12537. // IPv6 full address with default port
  12538. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12539. detail::make_host_and_port_string(
  12540. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12541. // IPv6 full address with non-default port
  12542. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12543. detail::make_host_and_port_string(
  12544. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12545. // IPv6 localhost with non-default port
  12546. EXPECT_EQ("[::1]:3000",
  12547. detail::make_host_and_port_string("::1", 3000, false));
  12548. // IPv6 with zone ID (link-local address) with default port
  12549. EXPECT_EQ("[fe80::1%eth0]",
  12550. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12551. // IPv6 with zone ID (link-local address) with non-default port
  12552. EXPECT_EQ("[fe80::1%eth0]:8080",
  12553. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12554. // Edge case: Port 443 with is_ssl=false (should add port)
  12555. EXPECT_EQ("example.com:443",
  12556. detail::make_host_and_port_string("example.com", 443, false));
  12557. // Edge case: Port 80 with is_ssl=true (should add port)
  12558. EXPECT_EQ("example.com:80",
  12559. detail::make_host_and_port_string("example.com", 80, true));
  12560. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12561. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12562. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12563. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12564. // Security fix: Already bracketed IPv6 should not get double brackets
  12565. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12566. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12567. EXPECT_EQ("[::1]:8080",
  12568. detail::make_host_and_port_string("[::1]", 8080, false));
  12569. EXPECT_EQ("[2001:db8::1]:8080",
  12570. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12571. EXPECT_EQ("[fe80::1%eth0]",
  12572. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12573. EXPECT_EQ("[fe80::1%eth0]:8080",
  12574. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12575. // Edge case: Empty host (should return as-is)
  12576. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12577. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12578. // This is a known limitation but shouldn't crash
  12579. EXPECT_EQ("[host:name]",
  12580. detail::make_host_and_port_string("host:name", 80, false));
  12581. // Port number edge cases (no validation, but should not crash)
  12582. EXPECT_EQ("example.com:0",
  12583. detail::make_host_and_port_string("example.com", 0, false));
  12584. EXPECT_EQ("example.com:-1",
  12585. detail::make_host_and_port_string("example.com", -1, false));
  12586. EXPECT_EQ("example.com:65535",
  12587. detail::make_host_and_port_string("example.com", 65535, false));
  12588. EXPECT_EQ("example.com:65536",
  12589. detail::make_host_and_port_string("example.com", 65536, false));
  12590. }
  12591. #ifdef CPPHTTPLIB_SSL_ENABLED
  12592. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12593. httplib::SSLClient cli("roblox.com", 443);
  12594. cli.set_follow_location(true);
  12595. auto res = cli.Get("/");
  12596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12597. EXPECT_EQ(StatusCode::OK_200, res->status);
  12598. }
  12599. #endif
  12600. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12601. Server svr;
  12602. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12603. EXPECT_EQ(res.status, 400);
  12604. });
  12605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12606. auto se = detail::scope_exit([&] {
  12607. svr.stop();
  12608. thread.join();
  12609. ASSERT_FALSE(svr.is_running());
  12610. });
  12611. svr.wait_until_ready();
  12612. Client cli(HOST, PORT);
  12613. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12614. }
  12615. TEST(InvalidHeaderCharsTest, is_field_name) {
  12616. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12617. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12618. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12619. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12620. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12621. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12622. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12623. EXPECT_FALSE(detail::fields::is_field_name(""));
  12624. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12625. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12626. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12627. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12628. }
  12629. TEST(InvalidHeaderCharsTest, is_field_value) {
  12630. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12631. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12632. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12633. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12634. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12635. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12636. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12637. EXPECT_TRUE(detail::fields::is_field_value(""));
  12638. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12639. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12640. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12641. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12642. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12643. }
  12644. TEST(InvalidHeaderCharsTest, OnServer) {
  12645. Server svr;
  12646. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12647. std::string header = "Not Set";
  12648. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12649. res.set_header(header, "value");
  12650. res.set_content("Page Content Page Content", "text/plain");
  12651. });
  12652. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12653. std::string header = "Not Set";
  12654. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12655. res.set_header("X-Test", header);
  12656. res.set_content("Page Content Page Content", "text/plain");
  12657. });
  12658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12659. auto se = detail::scope_exit([&] {
  12660. svr.stop();
  12661. thread.join();
  12662. ASSERT_FALSE(svr.is_running());
  12663. });
  12664. svr.wait_until_ready();
  12665. Client cli(HOST, PORT);
  12666. {
  12667. auto res = cli.Get(
  12668. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12670. EXPECT_EQ("Page Content Page Content", res->body);
  12671. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12672. }
  12673. {
  12674. auto res = cli.Get(
  12675. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12677. EXPECT_EQ("Page Content Page Content", res->body);
  12678. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12679. }
  12680. }
  12681. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12682. auto handled = false;
  12683. Server svr;
  12684. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12685. thread t = thread([&] { svr.listen(HOST, PORT); });
  12686. auto se = detail::scope_exit([&] {
  12687. svr.stop();
  12688. t.join();
  12689. ASSERT_FALSE(svr.is_running());
  12690. ASSERT_FALSE(handled);
  12691. });
  12692. svr.wait_until_ready();
  12693. auto req = "POST /test HTTP/1.1\r\n"
  12694. "Content-Length: x\r\n"
  12695. "\r\n";
  12696. std::string response;
  12697. ASSERT_TRUE(send_request(1, req, &response));
  12698. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12699. response.substr(0, response.find("\r\n")));
  12700. }
  12701. #ifndef _WIN32
  12702. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12703. static constexpr char reject[] = "Unauthorized";
  12704. static constexpr char accept[] = "Upload accepted";
  12705. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12706. Server svr;
  12707. svr.set_expect_100_continue_handler(
  12708. [](const Request & /*req*/, Response &res) {
  12709. res.status = StatusCode::Unauthorized_401;
  12710. res.set_content(reject, "text/plain");
  12711. return res.status;
  12712. });
  12713. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12714. res.set_content(accept, "text/plain");
  12715. });
  12716. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12717. auto se = detail::scope_exit([&] {
  12718. svr.stop();
  12719. thread.join();
  12720. ASSERT_FALSE(svr.is_running());
  12721. });
  12722. svr.wait_until_ready();
  12723. {
  12724. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12725. curl_easy_init(), &curl_easy_cleanup};
  12726. ASSERT_NE(curl, nullptr);
  12727. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12728. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12729. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12730. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12731. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12732. &curl_slist_free_all};
  12733. ASSERT_NE(list, nullptr);
  12734. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12735. struct read_data {
  12736. size_t read_size;
  12737. size_t total_size;
  12738. } data = {0, total_size};
  12739. using read_callback_t =
  12740. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12741. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12742. void *userdata) -> size_t {
  12743. read_data *d = (read_data *)userdata;
  12744. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12745. std::fill_n(ptr, size * nmemb, 'A');
  12746. d->read_size += size * nmemb;
  12747. return size * nmemb;
  12748. };
  12749. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12750. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12751. std::vector<char> buffer;
  12752. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12753. using write_callback_t =
  12754. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12755. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12756. void *userdata) -> size_t {
  12757. std::vector<char> *buf = (std::vector<char> *)userdata;
  12758. buf->reserve(buf->size() + size * nmemb + 1);
  12759. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12760. return size * nmemb;
  12761. };
  12762. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12763. {
  12764. const auto res = curl_easy_perform(curl.get());
  12765. ASSERT_EQ(res, CURLE_OK);
  12766. }
  12767. {
  12768. auto response_code = long{};
  12769. const auto res =
  12770. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12771. ASSERT_EQ(res, CURLE_OK);
  12772. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12773. }
  12774. {
  12775. auto dl = curl_off_t{};
  12776. const auto res =
  12777. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12778. ASSERT_EQ(res, CURLE_OK);
  12779. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12780. }
  12781. {
  12782. buffer.push_back('\0');
  12783. ASSERT_STRCASEEQ(buffer.data(), reject);
  12784. }
  12785. }
  12786. }
  12787. #endif
  12788. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12789. // Regression test for #2458.
  12790. //
  12791. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12792. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12793. // ticket can make the client socket spuriously readable during the
  12794. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12795. // the client withholds the body and then blocks reading a response that never
  12796. // comes, failing with `Failed to read connection`.
  12797. //
  12798. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12799. // within the timeout. This raw OpenSSL server deliberately never sends
  12800. // `100 Continue`; the client must still deliver the body and receive 200.
  12801. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12802. signal(SIGPIPE, SIG_IGN);
  12803. const auto port = PORT + 4;
  12804. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12805. ASSERT_NE(srv, INVALID_SOCKET);
  12806. int opt = 1;
  12807. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12808. sockaddr_in addr{};
  12809. addr.sin_family = AF_INET;
  12810. addr.sin_port = htons(static_cast<uint16_t>(port));
  12811. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12812. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12813. ASSERT_EQ(0, ::listen(srv, 1));
  12814. std::atomic<size_t> server_body_bytes{0};
  12815. auto server_thread = std::thread([&] {
  12816. sockaddr_in cli_addr{};
  12817. socklen_t cli_len = sizeof(cli_addr);
  12818. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12819. if (cli == INVALID_SOCKET) { return; }
  12820. // Bound the lifetime of the server side so a buggy client (which never
  12821. // sends the body) cannot make this thread block forever on join.
  12822. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12823. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12824. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12825. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12826. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12827. SSL *ssl = SSL_new(ctx);
  12828. SSL_set_fd(ssl, static_cast<int>(cli));
  12829. if (SSL_accept(ssl) > 0) {
  12830. // Read the request headers. Reading here also flushes the TLS 1.3
  12831. // session tickets to the client. Deliberately do NOT send
  12832. // `100 Continue`.
  12833. std::string buf;
  12834. char tmp[1024];
  12835. while (buf.find("\r\n\r\n") == std::string::npos) {
  12836. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12837. if (n <= 0) { break; }
  12838. buf.append(tmp, static_cast<size_t>(n));
  12839. }
  12840. // A correct client sends the body now; count what arrives.
  12841. auto pos = buf.find("\r\n\r\n");
  12842. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12843. while (body < 4096) {
  12844. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12845. if (n <= 0) { break; }
  12846. body += static_cast<size_t>(n);
  12847. }
  12848. server_body_bytes = body;
  12849. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12850. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12851. SSL_shutdown(ssl);
  12852. }
  12853. SSL_free(ssl);
  12854. detail::close_socket(cli);
  12855. SSL_CTX_free(ctx);
  12856. });
  12857. auto se = detail::scope_exit([&] {
  12858. server_thread.join();
  12859. detail::close_socket(srv);
  12860. });
  12861. SSLClient cli("127.0.0.1", port);
  12862. cli.enable_server_certificate_verification(false);
  12863. cli.set_connection_timeout(5, 0);
  12864. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12865. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12866. std::string body(4096, 'A');
  12867. auto res = cli.Put("/api/test", body, "application/json");
  12868. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12869. EXPECT_EQ(StatusCode::OK_200, res->status);
  12870. EXPECT_EQ(body.size(), server_body_bytes.load());
  12871. }
  12872. #endif
  12873. template <typename S, typename C>
  12874. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12875. svr.Get("/stream", [&](const Request &, Response &res) {
  12876. auto data = new std::string("01234567890123456789");
  12877. res.set_content_provider(
  12878. data->size(), "text/plain",
  12879. [&, data](size_t offset, size_t length, DataSink &sink) {
  12880. const size_t DATA_CHUNK_SIZE = 4;
  12881. const auto &d = *data;
  12882. std::this_thread::sleep_for(std::chrono::seconds(1));
  12883. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12884. return true;
  12885. },
  12886. [data](bool success) {
  12887. EXPECT_FALSE(success);
  12888. delete data;
  12889. });
  12890. });
  12891. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12892. auto i = new size_t(0);
  12893. res.set_content_provider(
  12894. "text/plain",
  12895. [i](size_t, DataSink &sink) {
  12896. if (*i < 5) {
  12897. std::this_thread::sleep_for(std::chrono::seconds(1));
  12898. sink.write("abcd", 4);
  12899. (*i)++;
  12900. } else {
  12901. sink.done();
  12902. }
  12903. return true;
  12904. },
  12905. [i](bool success) {
  12906. EXPECT_FALSE(success);
  12907. delete i;
  12908. });
  12909. });
  12910. svr.Get("/chunked", [&](const Request &, Response &res) {
  12911. auto i = new size_t(0);
  12912. res.set_chunked_content_provider(
  12913. "text/plain",
  12914. [i](size_t, DataSink &sink) {
  12915. if (*i < 5) {
  12916. std::this_thread::sleep_for(std::chrono::seconds(1));
  12917. sink.os << "abcd";
  12918. (*i)++;
  12919. } else {
  12920. sink.done();
  12921. }
  12922. return true;
  12923. },
  12924. [i](bool success) {
  12925. EXPECT_FALSE(success);
  12926. delete i;
  12927. });
  12928. });
  12929. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12930. auto se = detail::scope_exit([&] {
  12931. svr.stop();
  12932. listen_thread.join();
  12933. ASSERT_FALSE(svr.is_running());
  12934. });
  12935. svr.wait_until_ready();
  12936. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12937. {
  12938. auto start = std::chrono::steady_clock::now();
  12939. auto res = cli.Get("/stream");
  12940. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12941. std::chrono::steady_clock::now() - start)
  12942. .count();
  12943. ASSERT_FALSE(res);
  12944. EXPECT_EQ(Error::Read, res.error());
  12945. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12946. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12947. }
  12948. {
  12949. auto start = std::chrono::steady_clock::now();
  12950. auto res = cli.Get("/stream_without_length");
  12951. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12952. std::chrono::steady_clock::now() - start)
  12953. .count();
  12954. ASSERT_FALSE(res);
  12955. EXPECT_EQ(Error::Read, res.error());
  12956. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12957. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12958. }
  12959. {
  12960. auto start = std::chrono::steady_clock::now();
  12961. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12962. EXPECT_EQ("abcd", string(data, data_length));
  12963. return true;
  12964. });
  12965. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12966. std::chrono::steady_clock::now() - start)
  12967. .count();
  12968. ASSERT_FALSE(res);
  12969. EXPECT_EQ(Error::Read, res.error());
  12970. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12971. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12972. }
  12973. }
  12974. TEST(MaxTimeoutTest, ContentStream) {
  12975. time_t timeout = 2000;
  12976. time_t threshold = 200;
  12977. Server svr;
  12978. Client cli("localhost", PORT);
  12979. max_timeout_test(svr, cli, timeout, threshold);
  12980. }
  12981. #ifdef CPPHTTPLIB_SSL_ENABLED
  12982. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12983. time_t timeout = 2000;
  12984. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12986. SSLClient cli("localhost", PORT);
  12987. cli.enable_server_certificate_verification(false);
  12988. max_timeout_test(svr, cli, timeout, threshold);
  12989. }
  12990. #endif
  12991. class EventDispatcher {
  12992. public:
  12993. EventDispatcher() {}
  12994. bool wait_event(DataSink *sink) {
  12995. unique_lock<mutex> lk(m_);
  12996. int id = id_;
  12997. // Wait with timeout to prevent hanging if client disconnects
  12998. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12999. [&] { return cid_ == id; })) {
  13000. return false; // Timeout occurred
  13001. }
  13002. sink->write(message_.data(), message_.size());
  13003. return true;
  13004. }
  13005. void send_event(const string &message) {
  13006. lock_guard<mutex> lk(m_);
  13007. cid_ = id_++;
  13008. message_ = message;
  13009. cv_.notify_all();
  13010. }
  13011. private:
  13012. mutex m_;
  13013. condition_variable cv_;
  13014. atomic_int id_{0};
  13015. atomic_int cid_{-1};
  13016. string message_;
  13017. };
  13018. TEST(ClientInThreadTest, Issue2068) {
  13019. EventDispatcher ed;
  13020. Server svr;
  13021. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13022. res.set_chunked_content_provider("text/event-stream",
  13023. [&](size_t /*offset*/, DataSink &sink) {
  13024. return ed.wait_event(&sink);
  13025. });
  13026. });
  13027. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13028. svr.wait_until_ready();
  13029. thread event_thread([&] {
  13030. int id = 0;
  13031. while (svr.is_running()) {
  13032. this_thread::sleep_for(chrono::milliseconds(500));
  13033. std::stringstream ss;
  13034. ss << "data: " << id << "\n\n";
  13035. ed.send_event(ss.str());
  13036. id++;
  13037. }
  13038. });
  13039. auto se = detail::scope_exit([&] {
  13040. svr.stop();
  13041. listen_thread.join();
  13042. event_thread.join();
  13043. ASSERT_FALSE(svr.is_running());
  13044. });
  13045. {
  13046. auto client = detail::make_unique<Client>(HOST, PORT);
  13047. client->set_read_timeout(std::chrono::minutes(10));
  13048. std::atomic<bool> stop{false};
  13049. std::thread t([&] {
  13050. client->Get("/event1",
  13051. [&](const char *, size_t) -> bool { return !stop; });
  13052. });
  13053. std::this_thread::sleep_for(std::chrono::seconds(2));
  13054. stop = true;
  13055. client->stop();
  13056. t.join();
  13057. // Reset client after thread has finished
  13058. client.reset();
  13059. }
  13060. }
  13061. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13062. auto handled = false;
  13063. Server svr;
  13064. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13065. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13066. auto se = detail::scope_exit([&] {
  13067. svr.stop();
  13068. t.join();
  13069. ASSERT_FALSE(svr.is_running());
  13070. ASSERT_FALSE(handled);
  13071. });
  13072. svr.wait_until_ready();
  13073. // Two Content-Length headers with different values — must be rejected
  13074. auto req = "POST /test HTTP/1.1\r\n"
  13075. "Content-Length: 5\r\n"
  13076. "Content-Length: 10\r\n"
  13077. "\r\n"
  13078. "hello";
  13079. std::string response;
  13080. ASSERT_TRUE(send_request(1, req, &response));
  13081. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13082. response.substr(0, response.find("\r\n")));
  13083. }
  13084. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13085. auto handled = false;
  13086. Server svr;
  13087. svr.Post("/test", [&](const Request &, Response &res) {
  13088. handled = true;
  13089. res.set_content("ok", "text/plain");
  13090. });
  13091. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13092. auto se = detail::scope_exit([&] {
  13093. svr.stop();
  13094. t.join();
  13095. ASSERT_FALSE(svr.is_running());
  13096. ASSERT_TRUE(handled);
  13097. });
  13098. svr.wait_until_ready();
  13099. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13100. auto req = "POST /test HTTP/1.1\r\n"
  13101. "Content-Length: 5\r\n"
  13102. "Content-Length: 5\r\n"
  13103. "\r\n"
  13104. "hello";
  13105. std::string response;
  13106. ASSERT_TRUE(send_request(1, req, &response));
  13107. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13108. }
  13109. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13110. Server svr;
  13111. svr.Get("/", [](const Request &req, Response &res) {
  13112. EXPECT_EQ(2U, req.trailers.size());
  13113. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13114. // Denied
  13115. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13116. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13117. // Accepted
  13118. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13119. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13120. EXPECT_TRUE(req.has_trailer("X-World"));
  13121. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13122. res.set_content("ok", "text/plain");
  13123. });
  13124. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13125. auto se = detail::scope_exit([&] {
  13126. svr.stop();
  13127. t.join();
  13128. ASSERT_FALSE(svr.is_running());
  13129. });
  13130. svr.wait_until_ready();
  13131. const std::string req = "GET / HTTP/1.1\r\n"
  13132. "Transfer-Encoding: chunked\r\n"
  13133. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13134. "\r\n"
  13135. "0\r\n"
  13136. "Content-Length: 10\r\n"
  13137. "Host: internal.local\r\n"
  13138. "Content-Type: malicious/content\r\n"
  13139. "Cookie: any\r\n"
  13140. "Set-Cookie: any\r\n"
  13141. "X-Forwarded-For: attacker.com\r\n"
  13142. "X-Real-Ip: 1.1.1.1\r\n"
  13143. "X-Hello: hello\r\n"
  13144. "X-World: world\r\n"
  13145. "\r\n";
  13146. std::string res;
  13147. ASSERT_TRUE(send_request(1, req, &res));
  13148. }
  13149. // A direct client that is not listed in trusted_proxies must not be able to
  13150. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13151. // the peer address on the actual TCP connection determines whether the
  13152. // header is honored.
  13153. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13154. Server svr;
  13155. // Deliberately does NOT include the loopback address the test client
  13156. // actually connects from, so the direct connection is not a trusted proxy.
  13157. svr.set_trusted_proxies({"203.0.113.66"});
  13158. std::string observed_remote_addr;
  13159. svr.Get("/ip", [&](const Request &req, Response &res) {
  13160. observed_remote_addr = req.remote_addr;
  13161. res.set_content("ok", "text/plain");
  13162. });
  13163. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13164. auto se = detail::scope_exit([&] {
  13165. svr.stop();
  13166. t.join();
  13167. ASSERT_FALSE(svr.is_running());
  13168. });
  13169. svr.wait_until_ready();
  13170. Client cli(HOST, PORT);
  13171. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13173. EXPECT_EQ(StatusCode::OK_200, res->status);
  13174. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13175. // ignored entirely and the real connection-level address retained.
  13176. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13177. observed_remote_addr == "127.0.0.1");
  13178. }
  13179. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13180. Server svr;
  13181. std::string observed_remote_addr;
  13182. std::string observed_xff;
  13183. svr.Get("/ip", [&](const Request &req, Response &res) {
  13184. observed_remote_addr = req.remote_addr;
  13185. observed_xff = req.get_header_value("X-Forwarded-For");
  13186. res.set_content("ok", "text/plain");
  13187. });
  13188. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13189. auto se = detail::scope_exit([&] {
  13190. svr.stop();
  13191. t.join();
  13192. ASSERT_FALSE(svr.is_running());
  13193. });
  13194. svr.wait_until_ready();
  13195. Client cli(HOST, PORT);
  13196. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13198. EXPECT_EQ(StatusCode::OK_200, res->status);
  13199. EXPECT_EQ(observed_xff, "203.0.113.66");
  13200. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13201. observed_remote_addr == "127.0.0.1");
  13202. }
  13203. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13204. Server svr;
  13205. svr.set_trusted_proxies({"203.0.113.66"});
  13206. std::string observed_remote_addr;
  13207. std::string observed_xff;
  13208. svr.Get("/ip", [&](const Request &req, Response &res) {
  13209. observed_remote_addr = req.remote_addr;
  13210. observed_xff = req.get_header_value("X-Forwarded-For");
  13211. res.set_content("ok", "text/plain");
  13212. });
  13213. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13214. auto se = detail::scope_exit([&] {
  13215. svr.stop();
  13216. t.join();
  13217. ASSERT_FALSE(svr.is_running());
  13218. });
  13219. svr.wait_until_ready();
  13220. Client cli(HOST, PORT);
  13221. auto res = cli.Get("/ip");
  13222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13223. EXPECT_EQ(StatusCode::OK_200, res->status);
  13224. EXPECT_EQ(observed_xff, "");
  13225. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13226. observed_remote_addr == "127.0.0.1");
  13227. }
  13228. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13229. Server svr;
  13230. // Include the loopback address the test client actually connects from, so
  13231. // the direct connection itself is recognized as the trusted proxy hop.
  13232. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13233. std::string observed_remote_addr;
  13234. std::string observed_xff;
  13235. svr.Get("/ip", [&](const Request &req, Response &res) {
  13236. observed_remote_addr = req.remote_addr;
  13237. observed_xff = req.get_header_value("X-Forwarded-For");
  13238. res.set_content("ok", "text/plain");
  13239. });
  13240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13241. auto se = detail::scope_exit([&] {
  13242. svr.stop();
  13243. t.join();
  13244. ASSERT_FALSE(svr.is_running());
  13245. });
  13246. svr.wait_until_ready();
  13247. Client cli(HOST, PORT);
  13248. auto res = cli.Get(
  13249. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13251. EXPECT_EQ(StatusCode::OK_200, res->status);
  13252. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13253. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13254. }
  13255. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13256. Server svr;
  13257. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13258. std::string observed_remote_addr;
  13259. std::string observed_xff;
  13260. svr.Get("/ip", [&](const Request &req, Response &res) {
  13261. observed_remote_addr = req.remote_addr;
  13262. observed_xff = req.get_header_value("X-Forwarded-For");
  13263. res.set_content("ok", "text/plain");
  13264. });
  13265. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13266. auto se = detail::scope_exit([&] {
  13267. svr.stop();
  13268. t.join();
  13269. ASSERT_FALSE(svr.is_running());
  13270. });
  13271. svr.wait_until_ready();
  13272. Client cli(HOST, PORT);
  13273. auto res = cli.Get(
  13274. "/ip",
  13275. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13277. EXPECT_EQ(StatusCode::OK_200, res->status);
  13278. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13279. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13280. }
  13281. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13282. Server svr;
  13283. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13284. std::string observed_remote_addr;
  13285. std::string observed_xff;
  13286. svr.Get("/ip", [&](const Request &req, Response &res) {
  13287. observed_remote_addr = req.remote_addr;
  13288. observed_xff = req.get_header_value("X-Forwarded-For");
  13289. res.set_content("ok", "text/plain");
  13290. });
  13291. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13292. auto se = detail::scope_exit([&] {
  13293. svr.stop();
  13294. t.join();
  13295. ASSERT_FALSE(svr.is_running());
  13296. });
  13297. svr.wait_until_ready();
  13298. Client cli(HOST, PORT);
  13299. auto res = cli.Get(
  13300. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13302. EXPECT_EQ(StatusCode::OK_200, res->status);
  13303. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13304. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13305. // and must not be selected.
  13306. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13307. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13308. }
  13309. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13310. Server svr;
  13311. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13312. std::string observed_remote_addr;
  13313. svr.Get("/ip", [&](const Request &req, Response &res) {
  13314. observed_remote_addr = req.remote_addr;
  13315. res.set_content("ok", "text/plain");
  13316. });
  13317. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13318. auto se = detail::scope_exit([&] {
  13319. svr.stop();
  13320. t.join();
  13321. ASSERT_FALSE(svr.is_running());
  13322. });
  13323. svr.wait_until_ready();
  13324. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13325. // a forged address and the trusted proxy's own address; the forged value must
  13326. // not win over the address the trusted proxy actually recorded.
  13327. Client cli(HOST, PORT);
  13328. auto res = cli.Get(
  13329. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13331. EXPECT_EQ(StatusCode::OK_200, res->status);
  13332. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13333. }
  13334. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13335. Server svr;
  13336. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13337. std::string observed_remote_addr;
  13338. std::string observed_xff;
  13339. svr.Get("/ip", [&](const Request &req, Response &res) {
  13340. observed_remote_addr = req.remote_addr;
  13341. observed_xff = req.get_header_value("X-Forwarded-For");
  13342. res.set_content("ok", "text/plain");
  13343. });
  13344. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13345. auto se = detail::scope_exit([&] {
  13346. svr.stop();
  13347. t.join();
  13348. ASSERT_FALSE(svr.is_running());
  13349. });
  13350. svr.wait_until_ready();
  13351. Client cli(HOST, PORT);
  13352. auto res = cli.Get(
  13353. "/ip",
  13354. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13356. EXPECT_EQ(StatusCode::OK_200, res->status);
  13357. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13358. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13359. }
  13360. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13361. Server svr;
  13362. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13363. std::string observed_remote_addr;
  13364. std::string observed_xff;
  13365. svr.Get("/ip", [&](const Request &req, Response &res) {
  13366. observed_remote_addr = req.remote_addr;
  13367. observed_xff = req.get_header_value("X-Forwarded-For");
  13368. res.set_content("ok", "text/plain");
  13369. });
  13370. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13371. auto se = detail::scope_exit([&] {
  13372. svr.stop();
  13373. t.join();
  13374. ASSERT_FALSE(svr.is_running());
  13375. });
  13376. svr.wait_until_ready();
  13377. std::string raw_req =
  13378. "GET /ip HTTP/1.1\r\n"
  13379. "Host: localhost\r\n"
  13380. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13381. "Connection: close\r\n"
  13382. "\r\n";
  13383. std::string out;
  13384. ASSERT_TRUE(send_request(5, raw_req, &out));
  13385. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13386. // Header parser trims surrounding whitespace of the header value
  13387. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13388. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13389. }
  13390. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13391. // crash the server (it used to call front() on an empty vector inside
  13392. // get_client_ip). The connection-level remote address must be retained instead.
  13393. static void run_malformed_xff_test(const std::string &xff_value) {
  13394. Server svr;
  13395. svr.set_trusted_proxies({"192.0.2.45"});
  13396. std::string observed_remote_addr;
  13397. svr.Get("/ip", [&](const Request &req, Response &res) {
  13398. observed_remote_addr = req.remote_addr;
  13399. res.set_content("ok", "text/plain");
  13400. });
  13401. int port = 0;
  13402. thread t = thread([&]() {
  13403. port = svr.bind_to_any_port(HOST);
  13404. svr.listen_after_bind();
  13405. });
  13406. auto se = detail::scope_exit([&] {
  13407. svr.stop();
  13408. t.join();
  13409. ASSERT_FALSE(svr.is_running());
  13410. });
  13411. svr.wait_until_ready();
  13412. Client cli(HOST, port);
  13413. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13415. EXPECT_EQ(StatusCode::OK_200, res->status);
  13416. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13417. observed_remote_addr == "127.0.0.1");
  13418. }
  13419. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13420. run_malformed_xff_test("");
  13421. }
  13422. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13423. run_malformed_xff_test(",");
  13424. }
  13425. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13426. run_malformed_xff_test(", , ,");
  13427. }
  13428. #ifndef _WIN32
  13429. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13430. Server svr;
  13431. svr.Post("/post", [&](const Request &req, Response &res) {
  13432. res.set_content(req.body, "text/plain");
  13433. });
  13434. svr.Put("/put", [&](const Request &req, Response &res) {
  13435. res.set_content(req.body, "text/plain");
  13436. });
  13437. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13438. res.set_content(req.body, "text/plain");
  13439. });
  13440. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13441. res.set_content(req.body, "text/plain");
  13442. });
  13443. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13444. auto se = detail::scope_exit([&] {
  13445. svr.stop();
  13446. t.join();
  13447. ASSERT_FALSE(svr.is_running());
  13448. });
  13449. svr.wait_until_ready();
  13450. std::string resp;
  13451. // POST without Content-Length
  13452. ASSERT_TRUE(send_request(5,
  13453. "POST /post HTTP/1.1\r\n"
  13454. "Host: localhost\r\n"
  13455. "Connection: close\r\n"
  13456. "\r\n",
  13457. &resp));
  13458. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13459. // PUT without Content-Length
  13460. resp.clear();
  13461. ASSERT_TRUE(send_request(5,
  13462. "PUT /put HTTP/1.1\r\n"
  13463. "Host: localhost\r\n"
  13464. "Connection: close\r\n"
  13465. "\r\n",
  13466. &resp));
  13467. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13468. // PATCH without Content-Length
  13469. resp.clear();
  13470. ASSERT_TRUE(send_request(5,
  13471. "PATCH /patch HTTP/1.1\r\n"
  13472. "Host: localhost\r\n"
  13473. "Connection: close\r\n"
  13474. "\r\n",
  13475. &resp));
  13476. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13477. // DELETE without Content-Length
  13478. resp.clear();
  13479. ASSERT_TRUE(send_request(5,
  13480. "DELETE /delete HTTP/1.1\r\n"
  13481. "Host: localhost\r\n"
  13482. "Connection: close\r\n"
  13483. "\r\n",
  13484. &resp));
  13485. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13486. }
  13487. #endif
  13488. //==============================================================================
  13489. // open_stream() Tests
  13490. //==============================================================================
  13491. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13492. std::string result;
  13493. char buf[8192];
  13494. ssize_t n;
  13495. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13496. result.append(buf, static_cast<size_t>(n));
  13497. }
  13498. return result;
  13499. }
  13500. // Mock stream for unit tests
  13501. class MockStream : public Stream {
  13502. public:
  13503. std::string data;
  13504. size_t pos = 0;
  13505. ssize_t error_after = -1; // -1 = no error
  13506. explicit MockStream(const std::string &d, ssize_t err = -1)
  13507. : data(d), error_after(err) {}
  13508. bool is_readable() const override { return true; }
  13509. bool wait_readable() const override { return true; }
  13510. bool wait_writable() const override { return true; }
  13511. ssize_t read(char *ptr, size_t size) override {
  13512. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13513. if (pos >= data.size()) return 0;
  13514. size_t limit =
  13515. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13516. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13517. std::memcpy(ptr, data.data() + pos, to_read);
  13518. pos += to_read;
  13519. return static_cast<ssize_t>(to_read);
  13520. }
  13521. ssize_t write(const char *, size_t) override { return -1; }
  13522. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13523. ip = "127.0.0.1";
  13524. port = 0;
  13525. }
  13526. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13527. ip = "127.0.0.1";
  13528. port = 0;
  13529. }
  13530. socket_t socket() const override { return INVALID_SOCKET; }
  13531. time_t duration() const override { return 0; }
  13532. };
  13533. TEST(StreamHandleTest, Basic) {
  13534. ClientImpl::StreamHandle handle;
  13535. EXPECT_FALSE(handle.is_valid());
  13536. handle.response = detail::make_unique<Response>();
  13537. handle.error = Error::Connection;
  13538. EXPECT_FALSE(handle.is_valid());
  13539. handle.error = Error::Success;
  13540. EXPECT_TRUE(handle.is_valid());
  13541. }
  13542. TEST(BodyReaderTest, Basic) {
  13543. MockStream stream("Hello, World!");
  13544. detail::BodyReader reader;
  13545. reader.stream = &stream;
  13546. reader.content_length = 13;
  13547. char buf[32];
  13548. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13549. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13550. EXPECT_TRUE(reader.eof);
  13551. }
  13552. TEST(BodyReaderTest, NoStream) {
  13553. detail::BodyReader reader;
  13554. char buf[32];
  13555. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13556. EXPECT_EQ(Error::Connection, reader.last_error);
  13557. }
  13558. TEST(BodyReaderTest, Error) {
  13559. MockStream stream("Hello, World!", 5);
  13560. detail::BodyReader reader;
  13561. reader.stream = &stream;
  13562. reader.content_length = 13;
  13563. char buf[32];
  13564. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13565. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13566. EXPECT_EQ(Error::Read, reader.last_error);
  13567. }
  13568. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13569. // Mock-based StreamHandle tests relying on private internals are removed.
  13570. class OpenStreamTest : public ::testing::Test {
  13571. protected:
  13572. void SetUp() override {
  13573. svr_.Get("/hello", [](const Request &, Response &res) {
  13574. res.set_content("Hello World!", "text/plain");
  13575. });
  13576. svr_.Get("/large", [](const Request &, Response &res) {
  13577. res.set_content(std::string(10000, 'X'), "text/plain");
  13578. });
  13579. svr_.Get("/chunked", [](const Request &, Response &res) {
  13580. res.set_chunked_content_provider("text/plain",
  13581. [](size_t offset, DataSink &sink) {
  13582. if (offset < 15) {
  13583. sink.write("chunk", 5);
  13584. return true;
  13585. }
  13586. sink.done();
  13587. return true;
  13588. });
  13589. });
  13590. svr_.Get("/compressible", [](const Request &, Response &res) {
  13591. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13592. DataSink &sink) {
  13593. if (offset < 100 * 1024) {
  13594. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13595. sink.write(chunk.data(), chunk.size());
  13596. return true;
  13597. }
  13598. sink.done();
  13599. return true;
  13600. });
  13601. });
  13602. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13603. [](const Request & /*req*/, Response &res) {
  13604. auto i = new int(0);
  13605. res.set_header("Trailer", "Content-Length, X-Allowed");
  13606. res.set_chunked_content_provider(
  13607. "text/plain",
  13608. [i](size_t /*offset*/, DataSink &sink) {
  13609. switch (*i) {
  13610. case 0: sink.os << "123"; break;
  13611. case 1: sink.os << "456"; break;
  13612. case 2: sink.os << "789"; break;
  13613. case 3: {
  13614. sink.done_with_trailer(
  13615. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13616. } break;
  13617. }
  13618. (*i)++;
  13619. return true;
  13620. },
  13621. [i](bool success) {
  13622. EXPECT_TRUE(success);
  13623. delete i;
  13624. });
  13625. });
  13626. // Echo headers endpoint for header-related tests
  13627. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13628. std::string body;
  13629. for (const auto &h : req.headers) {
  13630. body.append(h.first);
  13631. body.push_back(':');
  13632. body.append(h.second);
  13633. body.push_back('\n');
  13634. }
  13635. res.set_content(body, "text/plain");
  13636. });
  13637. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13638. std::string body;
  13639. for (const auto &h : req.headers) {
  13640. body.append(h.first);
  13641. body.push_back(':');
  13642. body.append(h.second);
  13643. body.push_back('\n');
  13644. }
  13645. res.set_content(body, "text/plain");
  13646. });
  13647. port_ = svr_.bind_to_any_port("127.0.0.1");
  13648. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13649. svr_.wait_until_ready();
  13650. }
  13651. void TearDown() override {
  13652. svr_.stop();
  13653. if (thread_.joinable()) thread_.join();
  13654. }
  13655. Server svr_;
  13656. std::thread thread_;
  13657. int port_ = 0;
  13658. };
  13659. TEST_F(OpenStreamTest, Basic) {
  13660. Client cli("127.0.0.1", port_);
  13661. auto handle = cli.open_stream("GET", "/hello");
  13662. EXPECT_TRUE(handle.is_valid());
  13663. EXPECT_EQ("Hello World!", read_all(handle));
  13664. }
  13665. TEST_F(OpenStreamTest, SmallBuffer) {
  13666. Client cli("127.0.0.1", port_);
  13667. auto handle = cli.open_stream("GET", "/hello");
  13668. std::string result;
  13669. char buf[4];
  13670. ssize_t n;
  13671. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13672. result.append(buf, static_cast<size_t>(n));
  13673. EXPECT_EQ("Hello World!", result);
  13674. }
  13675. TEST_F(OpenStreamTest, DefaultHeaders) {
  13676. Client cli("127.0.0.1", port_);
  13677. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13678. {
  13679. auto handle = cli.open_stream("GET", "/echo-headers");
  13680. ASSERT_TRUE(handle.is_valid());
  13681. auto body = read_all(handle);
  13682. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13683. std::string::npos);
  13684. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13685. std::string::npos);
  13686. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13687. }
  13688. // open_stream POST with body and no explicit content_type should NOT add
  13689. // text/plain Content-Type (behavior differs from non-streaming path), but
  13690. // should include Content-Length
  13691. {
  13692. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13693. ASSERT_TRUE(handle.is_valid());
  13694. auto body = read_all(handle);
  13695. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13696. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13697. }
  13698. // open_stream POST with explicit Content-Type should preserve it
  13699. {
  13700. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13701. {{"Content-Type", "application/custom"}},
  13702. "{}", "application/custom");
  13703. ASSERT_TRUE(handle.is_valid());
  13704. auto body = read_all(handle);
  13705. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13706. }
  13707. // User-specified User-Agent must not be overwritten for stream API
  13708. {
  13709. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13710. {{"User-Agent", "MyAgent/1.2"}});
  13711. ASSERT_TRUE(handle.is_valid());
  13712. auto body = read_all(handle);
  13713. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13714. }
  13715. }
  13716. TEST_F(OpenStreamTest, Large) {
  13717. Client cli("127.0.0.1", port_);
  13718. auto handle = cli.open_stream("GET", "/large");
  13719. EXPECT_EQ(10000u, read_all(handle).size());
  13720. }
  13721. TEST_F(OpenStreamTest, ConnectionError) {
  13722. Client cli("127.0.0.1", 9999);
  13723. auto handle = cli.open_stream("GET", "/hello");
  13724. EXPECT_FALSE(handle.is_valid());
  13725. }
  13726. TEST_F(OpenStreamTest, Chunked) {
  13727. Client cli("127.0.0.1", port_);
  13728. auto handle = cli.open_stream("GET", "/chunked");
  13729. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13730. "Transfer-Encoding") == "chunked");
  13731. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13732. }
  13733. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13734. Client cli("127.0.0.1", port_);
  13735. auto handle =
  13736. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13737. ASSERT_TRUE(handle.is_valid());
  13738. // Consume body to allow trailers to be received/parsed
  13739. auto body = read_all(handle);
  13740. // Explicitly parse trailers (ensure trailers are available for assertion)
  13741. handle.parse_trailers_if_needed();
  13742. EXPECT_EQ(std::string("123456789"), body);
  13743. // The response should include a Trailer header declaring both names
  13744. ASSERT_TRUE(handle.response);
  13745. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13746. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13747. handle.response->get_header_value("Trailer"));
  13748. // Prohibited trailer must not be present
  13749. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13750. // Allowed trailer should be present
  13751. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13752. EXPECT_EQ(std::string("yes"),
  13753. handle.response->get_trailer_value("X-Allowed"));
  13754. // Verify trailers are NOT present as regular headers
  13755. EXPECT_EQ(std::string(""),
  13756. handle.response->get_header_value("Content-Length"));
  13757. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13758. }
  13759. static std::thread serve_single_response(std::promise<int> &port_promise,
  13760. const std::string &response) {
  13761. return std::thread([&port_promise, response] {
  13762. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13763. default_socket_options(srv);
  13764. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13765. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13766. sockaddr_in addr{};
  13767. addr.sin_family = AF_INET;
  13768. addr.sin_port = htons(0); // Let OS assign a free port
  13769. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13770. int opt = 1;
  13771. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13772. #ifdef _WIN32
  13773. reinterpret_cast<const char *>(&opt),
  13774. #else
  13775. &opt,
  13776. #endif
  13777. sizeof(opt));
  13778. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13779. ::listen(srv, 1) != 0) {
  13780. port_promise.set_value(-1);
  13781. detail::close_socket(srv);
  13782. return;
  13783. }
  13784. socklen_t addr_len = sizeof(addr);
  13785. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13786. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13787. sockaddr_in cli_addr{};
  13788. socklen_t cli_len = sizeof(cli_addr);
  13789. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13790. if (cli != INVALID_SOCKET) {
  13791. // Read the complete HTTP request (until the blank line that terminates
  13792. // headers) before sending the response. If the server closes the socket
  13793. // while the client's request data is still unread in the kernel receive
  13794. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13795. // connection on both sides: it discards the client's receive buffer
  13796. // (which already holds our response) and causes any in-progress write on
  13797. // the client to fail with ECONNRESET. Reading all request data first
  13798. // ensures close() emits a graceful FIN.
  13799. {
  13800. char rbuf[256];
  13801. std::string req;
  13802. while (req.find("\r\n\r\n") == std::string::npos) {
  13803. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13804. if (n <= 0) { break; }
  13805. req.append(rbuf, static_cast<size_t>(n));
  13806. }
  13807. }
  13808. ::send(cli,
  13809. #ifdef _WIN32
  13810. static_cast<const char *>(response.c_str()),
  13811. static_cast<int>(response.size()),
  13812. #else
  13813. response.c_str(), response.size(),
  13814. #endif
  13815. 0);
  13816. detail::close_socket(cli);
  13817. }
  13818. detail::close_socket(srv);
  13819. });
  13820. }
  13821. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13822. #ifndef _WIN32
  13823. signal(SIGPIPE, SIG_IGN);
  13824. #endif
  13825. std::promise<int> port_promise;
  13826. auto port_future = port_promise.get_future();
  13827. auto server_thread =
  13828. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13829. "Content-Type: text/plain\r\n"
  13830. "Content-Length: not-a-number\r\n"
  13831. "Connection: close\r\n"
  13832. "\r\n"
  13833. "hello");
  13834. auto port = port_future.get();
  13835. ASSERT_GT(port, 0);
  13836. Client cli("127.0.0.1", port);
  13837. auto handle = cli.open_stream("GET", "/");
  13838. EXPECT_FALSE(handle.is_valid());
  13839. server_thread.join();
  13840. }
  13841. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13842. #ifndef _WIN32
  13843. signal(SIGPIPE, SIG_IGN);
  13844. #endif
  13845. std::promise<int> port_promise;
  13846. auto port_future = port_promise.get_future();
  13847. auto server_thread = serve_single_response(
  13848. port_promise, "HTTP/1.1 200 OK\r\n"
  13849. "Content-Type: text/plain\r\n"
  13850. "Content-Length: 99999999999999999999999999\r\n"
  13851. "Connection: close\r\n"
  13852. "\r\n"
  13853. "hello");
  13854. auto port = port_future.get();
  13855. ASSERT_GT(port, 0);
  13856. // Historically std::stoull would throw std::out_of_range here and crash
  13857. // the process, then parsing silently clamped to a bogus framing length and
  13858. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13859. // so the stream fails to open, matching the not-a-number case above. The
  13860. // process still must NOT terminate.
  13861. Client cli("127.0.0.1", port);
  13862. auto handle = cli.open_stream("GET", "/");
  13863. EXPECT_FALSE(handle.is_valid());
  13864. server_thread.join();
  13865. }
  13866. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13867. TEST_F(OpenStreamTest, Gzip) {
  13868. Client cli("127.0.0.1", port_);
  13869. auto handle = cli.open_stream("GET", "/compressible", {},
  13870. {{"Accept-Encoding", "gzip"}});
  13871. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13872. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13873. }
  13874. #endif
  13875. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13876. TEST_F(OpenStreamTest, Brotli) {
  13877. Client cli("127.0.0.1", port_);
  13878. auto handle =
  13879. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13880. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13881. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13882. }
  13883. #endif
  13884. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13885. TEST_F(OpenStreamTest, Zstd) {
  13886. Client cli("127.0.0.1", port_);
  13887. auto handle = cli.open_stream("GET", "/compressible", {},
  13888. {{"Accept-Encoding", "zstd"}});
  13889. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13890. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13891. }
  13892. #endif
  13893. #ifdef CPPHTTPLIB_SSL_ENABLED
  13894. class SSLOpenStreamTest : public ::testing::Test {
  13895. protected:
  13896. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13897. void SetUp() override {
  13898. svr_.Get("/hello", [](const Request &, Response &res) {
  13899. res.set_content("Hello SSL World!", "text/plain");
  13900. });
  13901. svr_.Get("/chunked", [](const Request &, Response &res) {
  13902. res.set_chunked_content_provider("text/plain",
  13903. [](size_t offset, DataSink &sink) {
  13904. if (offset < 15) {
  13905. sink.write("chunk", 5);
  13906. return true;
  13907. }
  13908. sink.done();
  13909. return true;
  13910. });
  13911. });
  13912. svr_.Post("/echo", [](const Request &req, Response &res) {
  13913. res.set_content(req.body, req.get_header_value("Content-Type"));
  13914. });
  13915. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13916. std::string body = req.body;
  13917. res.set_chunked_content_provider(
  13918. "text/plain", [body](size_t offset, DataSink &sink) {
  13919. if (offset < body.size()) {
  13920. sink.write(body.data() + offset, body.size() - offset);
  13921. }
  13922. sink.done();
  13923. return true;
  13924. });
  13925. });
  13926. port_ = svr_.bind_to_any_port("127.0.0.1");
  13927. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13928. svr_.wait_until_ready();
  13929. }
  13930. void TearDown() override {
  13931. svr_.stop();
  13932. if (thread_.joinable()) thread_.join();
  13933. }
  13934. SSLServer svr_;
  13935. std::thread thread_;
  13936. int port_ = 0;
  13937. };
  13938. TEST_F(SSLOpenStreamTest, Basic) {
  13939. SSLClient cli("127.0.0.1", port_);
  13940. cli.enable_server_certificate_verification(false);
  13941. auto handle = cli.open_stream("GET", "/hello");
  13942. ASSERT_TRUE(handle.is_valid());
  13943. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13944. }
  13945. TEST_F(SSLOpenStreamTest, Chunked) {
  13946. SSLClient cli("127.0.0.1", port_);
  13947. cli.enable_server_certificate_verification(false);
  13948. auto handle = cli.open_stream("GET", "/chunked");
  13949. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13950. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13951. "Transfer-Encoding") == "chunked");
  13952. auto body = read_all(handle);
  13953. EXPECT_EQ("chunkchunkchunk", body);
  13954. }
  13955. TEST_F(SSLOpenStreamTest, Post) {
  13956. SSLClient cli("127.0.0.1", port_);
  13957. cli.enable_server_certificate_verification(false);
  13958. auto handle =
  13959. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13960. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13961. EXPECT_EQ(200, handle.response->status);
  13962. auto body = read_all(handle);
  13963. EXPECT_EQ("Hello SSL POST", body);
  13964. }
  13965. TEST_F(SSLOpenStreamTest, PostChunked) {
  13966. SSLClient cli("127.0.0.1", port_);
  13967. cli.enable_server_certificate_verification(false);
  13968. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13969. "Chunked SSL Data", "text/plain");
  13970. ASSERT_TRUE(handle.is_valid());
  13971. EXPECT_EQ(200, handle.response->status);
  13972. auto body = read_all(handle);
  13973. EXPECT_EQ("Chunked SSL Data", body);
  13974. }
  13975. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13976. // Content-Length is terminated by the server closing the connection. When the
  13977. // SSL peer sends a close_notify after the body, the client must treat it as a
  13978. // clean EOF and return a successful response rather than an error.
  13979. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13981. ASSERT_TRUE(svr.is_valid());
  13982. svr.set_keep_alive_max_count(1);
  13983. const std::string expected_body = "Hello from connection-close response!";
  13984. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13985. res.set_content_provider("text/plain",
  13986. [&](size_t offset, DataSink &sink) -> bool {
  13987. if (offset < expected_body.size()) {
  13988. sink.write(expected_body.data() + offset,
  13989. expected_body.size() - offset);
  13990. }
  13991. sink.done();
  13992. return true;
  13993. });
  13994. });
  13995. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13996. auto se = detail::scope_exit([&] {
  13997. svr.stop();
  13998. listen_thread.join();
  13999. ASSERT_FALSE(svr.is_running());
  14000. });
  14001. svr.wait_until_ready();
  14002. SSLClient cli(HOST, PORT);
  14003. cli.enable_server_certificate_verification(false);
  14004. auto res = cli.Get("/no-content-length");
  14005. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14006. EXPECT_EQ(StatusCode::OK_200, res->status);
  14007. EXPECT_EQ(expected_body, res->body);
  14008. }
  14009. #endif // CPPHTTPLIB_SSL_ENABLED
  14010. //==============================================================================
  14011. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14012. // results for various scenarios.
  14013. //==============================================================================
  14014. TEST(ParityTest, GetVsOpenStream) {
  14015. Server svr;
  14016. const std::string path = "/parity";
  14017. const std::string content = "Parity test content: hello world";
  14018. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14019. res.set_content(content, "text/plain");
  14020. });
  14021. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14022. auto se = detail::scope_exit([&] {
  14023. svr.stop();
  14024. t.join();
  14025. ASSERT_FALSE(svr.is_running());
  14026. });
  14027. svr.wait_until_ready();
  14028. Client cli(HOST, PORT);
  14029. // Non-stream path
  14030. auto r1 = cli.Get(path);
  14031. ASSERT_TRUE(r1);
  14032. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14033. // Stream path
  14034. auto h = cli.open_stream("GET", path);
  14035. ASSERT_TRUE(h.is_valid());
  14036. EXPECT_EQ(r1->body, read_all(h));
  14037. }
  14038. // Helper to compress data with provided compressor type T
  14039. template <typename Compressor>
  14040. static std::string compress_payload_for_parity(const std::string &in) {
  14041. std::string out;
  14042. Compressor compressor;
  14043. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14044. [&](const char *data, size_t n) {
  14045. out.append(data, n);
  14046. return true;
  14047. });
  14048. EXPECT_TRUE(ok);
  14049. return out;
  14050. }
  14051. // Helper function for compression parity tests
  14052. template <typename Compressor>
  14053. static void test_compression_parity(const std::string &original,
  14054. const std::string &path,
  14055. const std::string &encoding) {
  14056. const std::string compressed =
  14057. compress_payload_for_parity<Compressor>(original);
  14058. Server svr;
  14059. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14060. res.set_content(compressed, "application/octet-stream");
  14061. res.set_header("Content-Encoding", encoding);
  14062. });
  14063. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14064. auto se = detail::scope_exit([&] {
  14065. svr.stop();
  14066. t.join();
  14067. ASSERT_FALSE(svr.is_running());
  14068. });
  14069. svr.wait_until_ready();
  14070. Client cli(HOST, PORT);
  14071. // Non-streaming
  14072. {
  14073. auto res = cli.Get(path);
  14074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14075. EXPECT_EQ(StatusCode::OK_200, res->status);
  14076. EXPECT_EQ(original, res->body);
  14077. }
  14078. // Streaming
  14079. {
  14080. auto h = cli.open_stream("GET", path);
  14081. ASSERT_TRUE(h.is_valid());
  14082. EXPECT_EQ(original, read_all(h));
  14083. }
  14084. }
  14085. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14086. TEST(ParityTest, Gzip) {
  14087. test_compression_parity<detail::gzip_compressor>(
  14088. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14089. }
  14090. #endif
  14091. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14092. TEST(ParityTest, Brotli) {
  14093. test_compression_parity<detail::brotli_compressor>(
  14094. "Hello, brotli parity test payload", "/parity-br", "br");
  14095. }
  14096. #endif
  14097. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14098. TEST(ParityTest, Zstd) {
  14099. test_compression_parity<detail::zstd_compressor>(
  14100. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14101. }
  14102. #endif
  14103. //==============================================================================
  14104. // New Stream API Tests
  14105. //==============================================================================
  14106. inline std::string read_body(httplib::stream::Result &result) {
  14107. std::string body;
  14108. while (result.next()) {
  14109. body.append(result.data(), result.size());
  14110. }
  14111. return body;
  14112. }
  14113. TEST(ClientConnectionTest, Basic) {
  14114. httplib::ClientConnection conn;
  14115. EXPECT_FALSE(conn.is_open());
  14116. conn.sock = 1;
  14117. EXPECT_TRUE(conn.is_open());
  14118. httplib::ClientConnection conn2(std::move(conn));
  14119. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14120. conn2.sock = INVALID_SOCKET;
  14121. }
  14122. // Unified test server for all stream::* tests
  14123. class StreamApiTest : public ::testing::Test {
  14124. protected:
  14125. void SetUp() override {
  14126. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14127. res.set_content("Hello World!", "text/plain");
  14128. });
  14129. svr_.Get("/echo-params",
  14130. [](const httplib::Request &req, httplib::Response &res) {
  14131. std::string r;
  14132. for (const auto &p : req.params) {
  14133. if (!r.empty()) r += "&";
  14134. r += p.first + "=" + p.second;
  14135. }
  14136. res.set_content(r, "text/plain");
  14137. });
  14138. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14139. res.set_content(req.body, req.get_header_value("Content-Type"));
  14140. });
  14141. svr_.Post("/echo-headers",
  14142. [](const httplib::Request &req, httplib::Response &res) {
  14143. std::string r;
  14144. for (const auto &h : req.headers)
  14145. r += h.first + ": " + h.second + "\n";
  14146. res.set_content(r, "text/plain");
  14147. });
  14148. svr_.Post("/echo-params",
  14149. [](const httplib::Request &req, httplib::Response &res) {
  14150. std::string r = "params:";
  14151. for (const auto &p : req.params)
  14152. r += p.first + "=" + p.second + ";";
  14153. res.set_content(r + " body:" + req.body, "text/plain");
  14154. });
  14155. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14156. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14157. });
  14158. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14159. res.set_content("PUT:" + req.body, "text/plain");
  14160. });
  14161. svr_.Patch("/echo",
  14162. [](const httplib::Request &req, httplib::Response &res) {
  14163. res.set_content("PATCH:" + req.body, "text/plain");
  14164. });
  14165. svr_.Delete(
  14166. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14167. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14168. "text/plain");
  14169. });
  14170. svr_.Get("/head-test",
  14171. [](const httplib::Request &, httplib::Response &res) {
  14172. res.set_content("body for HEAD", "text/plain");
  14173. });
  14174. svr_.Options("/options",
  14175. [](const httplib::Request &, httplib::Response &res) {
  14176. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14177. });
  14178. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14179. svr_.wait_until_ready();
  14180. }
  14181. void TearDown() override {
  14182. svr_.stop();
  14183. if (thread_.joinable()) thread_.join();
  14184. }
  14185. httplib::Server svr_;
  14186. std::thread thread_;
  14187. };
  14188. // stream::Get tests
  14189. TEST_F(StreamApiTest, GetBasic) {
  14190. httplib::Client cli(HOST, PORT);
  14191. auto result = httplib::stream::Get(cli, "/hello");
  14192. ASSERT_TRUE(result.is_valid());
  14193. EXPECT_EQ(200, result.status());
  14194. EXPECT_EQ("Hello World!", read_body(result));
  14195. }
  14196. TEST_F(StreamApiTest, GetWithParams) {
  14197. httplib::Client cli(HOST, PORT);
  14198. httplib::Params params{{"foo", "bar"}};
  14199. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14200. ASSERT_TRUE(result.is_valid());
  14201. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14202. }
  14203. TEST_F(StreamApiTest, GetConnectionError) {
  14204. httplib::Client cli(HOST, 9999);
  14205. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14206. }
  14207. TEST_F(StreamApiTest, Get404) {
  14208. httplib::Client cli(HOST, PORT);
  14209. auto result = httplib::stream::Get(cli, "/nonexistent");
  14210. EXPECT_TRUE(result.is_valid());
  14211. EXPECT_EQ(404, result.status());
  14212. }
  14213. // stream::Post tests
  14214. TEST_F(StreamApiTest, PostBasic) {
  14215. httplib::Client cli(HOST, PORT);
  14216. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14217. "application/json");
  14218. ASSERT_TRUE(result.is_valid());
  14219. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14220. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14221. }
  14222. TEST_F(StreamApiTest, PostWithHeaders) {
  14223. httplib::Client cli(HOST, PORT);
  14224. httplib::Headers headers{{"X-Custom", "value"}};
  14225. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14226. "text/plain");
  14227. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14228. }
  14229. TEST_F(StreamApiTest, PostWithParams) {
  14230. httplib::Client cli(HOST, PORT);
  14231. httplib::Params params{{"k", "v"}};
  14232. auto result =
  14233. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14234. auto body = read_body(result);
  14235. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14236. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14237. }
  14238. TEST_F(StreamApiTest, PostLarge) {
  14239. httplib::Client cli(HOST, PORT);
  14240. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14241. size_t total = 0;
  14242. while (result.next()) {
  14243. total += result.size();
  14244. }
  14245. EXPECT_EQ(100u * 1024u, total);
  14246. }
  14247. // stream::Put/Patch tests
  14248. TEST_F(StreamApiTest, PutAndPatch) {
  14249. httplib::Client cli(HOST, PORT);
  14250. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14251. EXPECT_EQ("PUT:test", read_body(put));
  14252. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14253. EXPECT_EQ("PATCH:test", read_body(patch));
  14254. }
  14255. // stream::Delete tests
  14256. TEST_F(StreamApiTest, Delete) {
  14257. httplib::Client cli(HOST, PORT);
  14258. auto del1 = httplib::stream::Delete(cli, "/resource");
  14259. EXPECT_EQ("Deleted", read_body(del1));
  14260. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14261. EXPECT_EQ("Deleted:data", read_body(del2));
  14262. }
  14263. // stream::Head/Options tests
  14264. TEST_F(StreamApiTest, HeadAndOptions) {
  14265. httplib::Client cli(HOST, PORT);
  14266. auto head = httplib::stream::Head(cli, "/head-test");
  14267. EXPECT_TRUE(head.is_valid());
  14268. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14269. auto opts = httplib::stream::Options(cli, "/options");
  14270. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14271. }
  14272. // SSL stream::* tests
  14273. #ifdef CPPHTTPLIB_SSL_ENABLED
  14274. class SSLStreamApiTest : public ::testing::Test {
  14275. protected:
  14276. void SetUp() override {
  14277. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14278. res.set_content("Hello SSL!", "text/plain");
  14279. });
  14280. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14281. res.set_content(req.body, "text/plain");
  14282. });
  14283. port_ = svr_.bind_to_any_port("127.0.0.1");
  14284. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14285. svr_.wait_until_ready();
  14286. }
  14287. void TearDown() override {
  14288. svr_.stop();
  14289. if (thread_.joinable()) thread_.join();
  14290. }
  14291. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14292. std::thread thread_;
  14293. int port_ = 0;
  14294. };
  14295. TEST_F(SSLStreamApiTest, GetAndPost) {
  14296. httplib::SSLClient cli("127.0.0.1", port_);
  14297. cli.enable_server_certificate_verification(false);
  14298. auto get = httplib::stream::Get(cli, "/hello");
  14299. EXPECT_EQ("Hello SSL!", read_body(get));
  14300. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14301. EXPECT_EQ("test", read_body(post));
  14302. }
  14303. #endif
  14304. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14305. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14306. // BodyReader
  14307. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14308. // Test that read timeout during streaming is detected
  14309. // Use a large content-length response where server delays mid-stream
  14310. Server svr;
  14311. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14312. // Send a large response with delay in the middle
  14313. res.set_content_provider(
  14314. 1000, // content_length
  14315. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14316. if (offset < 100) {
  14317. // Send first 100 bytes immediately
  14318. std::string data(100, 'A');
  14319. sink.write(data.c_str(), data.size());
  14320. return true;
  14321. }
  14322. // Then delay longer than client timeout
  14323. std::this_thread::sleep_for(std::chrono::seconds(3));
  14324. std::string data(900, 'B');
  14325. sink.write(data.c_str(), data.size());
  14326. return true;
  14327. });
  14328. });
  14329. auto port = 8091;
  14330. std::thread t([&]() { svr.listen("localhost", port); });
  14331. svr.wait_until_ready();
  14332. Client cli("localhost", port);
  14333. cli.set_read_timeout(1, 0); // 1 second timeout
  14334. auto handle = cli.open_stream("GET", "/slow-stream");
  14335. ASSERT_TRUE(handle.is_valid());
  14336. char buf[256];
  14337. ssize_t total = 0;
  14338. ssize_t n;
  14339. bool got_error = false;
  14340. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14341. total += n;
  14342. }
  14343. if (n < 0) {
  14344. got_error = true;
  14345. // Should be timeout or read error
  14346. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14347. handle.get_read_error() == Error::Read)
  14348. << "Actual error: " << to_string(handle.get_read_error());
  14349. }
  14350. // Either we got an error, or we got less data than expected
  14351. EXPECT_TRUE(got_error || total < 1000)
  14352. << "Expected timeout but got all " << total << " bytes";
  14353. svr.stop();
  14354. t.join();
  14355. }
  14356. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14357. // Test connection closed detection via BodyReader
  14358. Server svr;
  14359. std::atomic<bool> close_now{false};
  14360. svr.Get("/will-close", [&](const Request &, Response &res) {
  14361. res.set_content_provider(
  14362. 10000, // Large content_length that we won't fully send
  14363. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14364. if (offset < 100) {
  14365. std::string data(100, 'X');
  14366. sink.write(data.c_str(), data.size());
  14367. return true;
  14368. }
  14369. // Wait for signal then abort
  14370. while (!close_now) {
  14371. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14372. }
  14373. return false; // Abort - server will close connection
  14374. });
  14375. });
  14376. auto port = 8092;
  14377. std::thread t([&]() { svr.listen("localhost", port); });
  14378. svr.wait_until_ready();
  14379. Client cli("localhost", port);
  14380. auto handle = cli.open_stream("GET", "/will-close");
  14381. ASSERT_TRUE(handle.is_valid());
  14382. char buf[256];
  14383. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14384. EXPECT_GT(n, 0) << "First read should succeed";
  14385. // Signal server to close
  14386. close_now = true;
  14387. // Keep reading until error or EOF
  14388. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14389. // Keep reading
  14390. }
  14391. // Should get an error since content_length wasn't satisfied
  14392. if (n < 0) {
  14393. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14394. handle.get_read_error() == Error::Read)
  14395. << "Actual error: " << to_string(handle.get_read_error());
  14396. }
  14397. svr.stop();
  14398. t.join();
  14399. }
  14400. #ifdef CPPHTTPLIB_SSL_ENABLED
  14401. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14402. // Test that read timeout during SSL streaming is detected
  14403. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14404. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14405. res.set_content_provider(
  14406. 1000, "text/plain",
  14407. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14408. if (offset < 100) {
  14409. std::string data(100, 'A');
  14410. sink.write(data.c_str(), data.size());
  14411. return true;
  14412. }
  14413. std::this_thread::sleep_for(std::chrono::seconds(3));
  14414. std::string data(900, 'B');
  14415. sink.write(data.c_str(), data.size());
  14416. return true;
  14417. });
  14418. });
  14419. auto port = 8093;
  14420. std::thread t([&]() { svr.listen("localhost", port); });
  14421. svr.wait_until_ready();
  14422. SSLClient cli("localhost", port);
  14423. cli.enable_server_certificate_verification(false);
  14424. cli.set_read_timeout(1, 0); // 1 second timeout
  14425. auto handle = cli.open_stream("GET", "/slow-stream");
  14426. ASSERT_TRUE(handle.is_valid());
  14427. char buf[256];
  14428. ssize_t total = 0;
  14429. ssize_t n;
  14430. bool got_error = false;
  14431. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14432. total += n;
  14433. }
  14434. if (n < 0) {
  14435. got_error = true;
  14436. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14437. handle.get_read_error() == Error::Read)
  14438. << "Actual error: " << to_string(handle.get_read_error());
  14439. }
  14440. EXPECT_TRUE(got_error || total < 1000)
  14441. << "Expected timeout but got all " << total << " bytes";
  14442. svr.stop();
  14443. t.join();
  14444. }
  14445. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14446. // Test SSL connection closed detection
  14447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14448. std::atomic<bool> close_now{false};
  14449. svr.Get("/will-close", [&](const Request &, Response &res) {
  14450. res.set_content_provider(
  14451. 10000, "text/plain",
  14452. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14453. if (offset < 100) {
  14454. std::string data(100, 'X');
  14455. sink.write(data.c_str(), data.size());
  14456. return true;
  14457. }
  14458. while (!close_now) {
  14459. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14460. }
  14461. return false;
  14462. });
  14463. });
  14464. auto port = 8094;
  14465. std::thread t([&]() { svr.listen("localhost", port); });
  14466. svr.wait_until_ready();
  14467. SSLClient cli("localhost", port);
  14468. cli.enable_server_certificate_verification(false);
  14469. auto handle = cli.open_stream("GET", "/will-close");
  14470. ASSERT_TRUE(handle.is_valid());
  14471. char buf[256];
  14472. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14473. EXPECT_GT(n, 0);
  14474. // Signal server to close
  14475. close_now = true;
  14476. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14477. // Keep reading
  14478. }
  14479. if (n < 0) {
  14480. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14481. handle.get_read_error() == Error::Read)
  14482. << "Actual error: " << to_string(handle.get_read_error());
  14483. }
  14484. svr.stop();
  14485. t.join();
  14486. }
  14487. #endif
  14488. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14489. using namespace httplib;
  14490. // Create a test file
  14491. const char *fname = "etag_testfile.txt";
  14492. const char *content = "etag-content";
  14493. {
  14494. std::ofstream ofs(fname);
  14495. ofs << content;
  14496. ASSERT_TRUE(ofs.good());
  14497. }
  14498. Server svr;
  14499. svr.set_mount_point("/static", ".");
  14500. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14501. svr.wait_until_ready();
  14502. Client cli(HOST, PORT);
  14503. // First request: should get 200 with ETag header
  14504. auto res1 = cli.Get("/static/etag_testfile.txt");
  14505. ASSERT_TRUE(res1);
  14506. ASSERT_EQ(200, res1->status);
  14507. ASSERT_TRUE(res1->has_header("ETag"));
  14508. std::string etag = res1->get_header_value("ETag");
  14509. EXPECT_FALSE(etag.empty());
  14510. // Verify ETag format: W/"hex-hex"
  14511. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14512. EXPECT_EQ('W', etag[0]);
  14513. EXPECT_EQ('/', etag[1]);
  14514. EXPECT_EQ('"', etag[2]);
  14515. EXPECT_EQ('"', etag.back());
  14516. // Exact match: expect 304 Not Modified
  14517. Headers h2 = {{"If-None-Match", etag}};
  14518. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14519. ASSERT_TRUE(res2);
  14520. EXPECT_EQ(304, res2->status);
  14521. // Wildcard match: expect 304 Not Modified
  14522. Headers h3 = {{"If-None-Match", "*"}};
  14523. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14524. ASSERT_TRUE(res3);
  14525. EXPECT_EQ(304, res3->status);
  14526. // Non-matching ETag: expect 200
  14527. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14528. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14529. ASSERT_TRUE(res4);
  14530. EXPECT_EQ(200, res4->status);
  14531. // Multiple ETags with one matching: expect 304
  14532. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14533. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14534. ASSERT_TRUE(res5);
  14535. EXPECT_EQ(304, res5->status);
  14536. svr.stop();
  14537. t.join();
  14538. std::remove(fname);
  14539. }
  14540. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14541. using namespace httplib;
  14542. Server svr;
  14543. svr.set_mount_point("/static", ".");
  14544. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14545. svr.wait_until_ready();
  14546. Client cli(HOST, PORT);
  14547. // Send If-None-Match: * to a non-existent file
  14548. Headers h = {{"If-None-Match", "*"}};
  14549. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14551. EXPECT_EQ(404, res->status);
  14552. svr.stop();
  14553. t.join();
  14554. }
  14555. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14556. using namespace httplib;
  14557. // Create a test file
  14558. const char *fname = "etag_boundary_testfile.txt";
  14559. const char *content = "boundary-test";
  14560. {
  14561. std::ofstream ofs(fname);
  14562. ofs << content;
  14563. ASSERT_TRUE(ofs.good());
  14564. }
  14565. Server svr;
  14566. svr.set_mount_point("/static", ".");
  14567. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14568. svr.wait_until_ready();
  14569. Client cli(HOST, PORT);
  14570. // Get the actual ETag
  14571. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14572. ASSERT_TRUE(res1);
  14573. ASSERT_EQ(200, res1->status);
  14574. ASSERT_TRUE(res1->has_header("ETag"));
  14575. std::string etag = res1->get_header_value("ETag");
  14576. // Test 1: Very long ETag value (longer than actual ETag)
  14577. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14578. Headers h1 = {{"If-None-Match", "W/"
  14579. "\"very-long-etag-value-that-is-much-longer-"
  14580. "than-the-actual-etag-value\""}};
  14581. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14582. ASSERT_TRUE(res2);
  14583. EXPECT_EQ(200, res2->status); // Should not match
  14584. // Test 2: Long string followed by wildcard
  14585. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14586. // string)
  14587. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14588. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14589. ASSERT_TRUE(res3);
  14590. EXPECT_EQ(304, res3->status); // Should match on "*"
  14591. // Test 3: Wildcard followed by long string
  14592. // Should match on "*" immediately and return 304
  14593. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14594. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14595. ASSERT_TRUE(res4);
  14596. EXPECT_EQ(304, res4->status); // Should match on "*"
  14597. // Test 4: Multiple long non-matching values
  14598. // Should NOT match and return 200 (test that all comparisons are safe)
  14599. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14600. "W/\"second-long-non-matching-value\", "
  14601. "W/\"third-long-non-matching-value\""}};
  14602. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14603. ASSERT_TRUE(res5);
  14604. EXPECT_EQ(200, res5->status); // Should not match
  14605. // Test 5: Single character that is not "*" (edge case)
  14606. Headers h5 = {{"If-None-Match", "X"}};
  14607. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14608. ASSERT_TRUE(res6);
  14609. EXPECT_EQ(200, res6->status); // Should not match
  14610. svr.stop();
  14611. t.join();
  14612. std::remove(fname);
  14613. }
  14614. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14615. using namespace httplib;
  14616. // Create a test file
  14617. const char *fname = "ims_testfile.txt";
  14618. const char *content = "if-modified-since-test";
  14619. {
  14620. std::ofstream ofs(fname);
  14621. ofs << content;
  14622. ASSERT_TRUE(ofs.good());
  14623. }
  14624. Server svr;
  14625. svr.set_mount_point("/static", ".");
  14626. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14627. svr.wait_until_ready();
  14628. Client cli(HOST, PORT);
  14629. // First request: should get 200 with Last-Modified header
  14630. auto res1 = cli.Get("/static/ims_testfile.txt");
  14631. ASSERT_TRUE(res1);
  14632. ASSERT_EQ(200, res1->status);
  14633. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14634. std::string last_modified = res1->get_header_value("Last-Modified");
  14635. EXPECT_FALSE(last_modified.empty());
  14636. // If-Modified-Since with same time: expect 304
  14637. Headers h2 = {{"If-Modified-Since", last_modified}};
  14638. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14639. ASSERT_TRUE(res2);
  14640. EXPECT_EQ(304, res2->status);
  14641. // If-Modified-Since with future time: expect 304
  14642. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14643. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14644. ASSERT_TRUE(res3);
  14645. EXPECT_EQ(304, res3->status);
  14646. // If-Modified-Since with past time: expect 200
  14647. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14648. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14649. ASSERT_TRUE(res4);
  14650. EXPECT_EQ(200, res4->status);
  14651. // If-None-Match takes precedence over If-Modified-Since
  14652. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14653. ASSERT_TRUE(res1->has_header("ETag"));
  14654. std::string etag = res1->get_header_value("ETag");
  14655. Headers h5 = {{"If-None-Match", etag},
  14656. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14657. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14658. ASSERT_TRUE(res5);
  14659. EXPECT_EQ(304, res5->status);
  14660. svr.stop();
  14661. t.join();
  14662. std::remove(fname);
  14663. }
  14664. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14665. using namespace httplib;
  14666. Server svr;
  14667. // Endpoint that returns compressible content
  14668. svr.Get("/compressible", [](const Request &, Response &res) {
  14669. // Return a large enough body to trigger compression
  14670. std::string body(1000, 'a');
  14671. res.set_content(body, "text/plain");
  14672. });
  14673. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14674. svr.wait_until_ready();
  14675. Client cli(HOST, PORT);
  14676. // Request with gzip support: should get Vary header when compressed
  14677. cli.set_compress(true);
  14678. auto res1 = cli.Get("/compressible");
  14679. ASSERT_TRUE(res1);
  14680. EXPECT_EQ(200, res1->status);
  14681. // If Content-Encoding is set, Vary should also be set
  14682. if (res1->has_header("Content-Encoding")) {
  14683. EXPECT_TRUE(res1->has_header("Vary"));
  14684. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14685. }
  14686. // Request without Accept-Encoding header: should not have compression
  14687. Headers h_no_compress;
  14688. auto res2 = cli.Get("/compressible", h_no_compress);
  14689. ASSERT_TRUE(res2);
  14690. EXPECT_EQ(200, res2->status);
  14691. // Verify Vary header is present when compression is applied
  14692. // (the exact behavior depends on server configuration)
  14693. svr.stop();
  14694. t.join();
  14695. }
  14696. TEST(ETagTest, IfRangeWithETag) {
  14697. using namespace httplib;
  14698. // Create a test file with known content
  14699. const char *fname = "if_range_testfile.txt";
  14700. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14701. {
  14702. std::ofstream ofs(fname);
  14703. ofs << content;
  14704. ASSERT_TRUE(ofs.good());
  14705. }
  14706. Server svr;
  14707. svr.set_mount_point("/static", ".");
  14708. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14709. svr.wait_until_ready();
  14710. Client cli(HOST, PORT);
  14711. // First request: get ETag
  14712. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14713. ASSERT_TRUE(res1);
  14714. ASSERT_EQ(200, res1->status);
  14715. ASSERT_TRUE(res1->has_header("ETag"));
  14716. std::string etag = res1->get_header_value("ETag");
  14717. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14718. // Since our server generates weak ETags (W/"..."), If-Range with our
  14719. // ETag should NOT result in partial content - it should return full content.
  14720. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14721. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14722. ASSERT_TRUE(res2);
  14723. // Weak ETag in If-Range -> full content (200), not partial (206)
  14724. EXPECT_EQ(200, res2->status);
  14725. EXPECT_EQ(content, res2->body);
  14726. EXPECT_FALSE(res2->has_header("Content-Range"));
  14727. // Range request with non-matching If-Range (ETag): should get 200 (full
  14728. // content)
  14729. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14730. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14731. ASSERT_TRUE(res3);
  14732. EXPECT_EQ(200, res3->status);
  14733. EXPECT_EQ(content, res3->body);
  14734. EXPECT_FALSE(res3->has_header("Content-Range"));
  14735. // Range request with strong ETag (hypothetical - our server doesn't generate
  14736. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14737. // should return full content)
  14738. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14739. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14740. ASSERT_TRUE(res4);
  14741. EXPECT_EQ(200, res4->status);
  14742. EXPECT_EQ(content, res4->body);
  14743. EXPECT_FALSE(res4->has_header("Content-Range"));
  14744. svr.stop();
  14745. t.join();
  14746. std::remove(fname);
  14747. }
  14748. TEST(ETagTest, IfRangeWithDate) {
  14749. using namespace httplib;
  14750. // Create a test file
  14751. const char *fname = "if_range_date_testfile.txt";
  14752. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14753. {
  14754. std::ofstream ofs(fname);
  14755. ofs << content;
  14756. ASSERT_TRUE(ofs.good());
  14757. }
  14758. Server svr;
  14759. svr.set_mount_point("/static", ".");
  14760. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14761. svr.wait_until_ready();
  14762. Client cli(HOST, PORT);
  14763. // First request: get Last-Modified
  14764. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14765. ASSERT_TRUE(res1);
  14766. ASSERT_EQ(200, res1->status);
  14767. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14768. std::string last_modified = res1->get_header_value("Last-Modified");
  14769. // Range request with matching If-Range (date): should get 206
  14770. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14771. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14772. ASSERT_TRUE(res2);
  14773. EXPECT_EQ(206, res2->status);
  14774. EXPECT_EQ("FGHIJ", res2->body);
  14775. // Range request with old If-Range date: should get 200 (full content)
  14776. Headers h3 = {{"Range", "bytes=5-9"},
  14777. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14778. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14779. ASSERT_TRUE(res3);
  14780. EXPECT_EQ(200, res3->status);
  14781. EXPECT_EQ(content, res3->body);
  14782. // Range request with future If-Range date: should get 206
  14783. Headers h4 = {{"Range", "bytes=0-4"},
  14784. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14785. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14786. ASSERT_TRUE(res4);
  14787. EXPECT_EQ(206, res4->status);
  14788. EXPECT_EQ("ABCDE", res4->body);
  14789. svr.stop();
  14790. t.join();
  14791. std::remove(fname);
  14792. }
  14793. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14794. using namespace httplib;
  14795. const char *fname = "etag_malformed.txt";
  14796. const char *content = "malformed-etag";
  14797. {
  14798. std::ofstream ofs(fname);
  14799. ofs << content;
  14800. ASSERT_TRUE(ofs.good());
  14801. }
  14802. Server svr;
  14803. svr.set_mount_point("/static", ".");
  14804. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14805. svr.wait_until_ready();
  14806. Client cli(HOST, PORT);
  14807. // baseline: should get 200 and an ETag
  14808. auto res1 = cli.Get("/static/etag_malformed.txt");
  14809. ASSERT_TRUE(res1);
  14810. ASSERT_EQ(200, res1->status);
  14811. ASSERT_TRUE(res1->has_header("ETag"));
  14812. // Malformed ETag value (missing quotes) should be treated as non-matching
  14813. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14814. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14815. ASSERT_TRUE(res_bad);
  14816. EXPECT_EQ(200, res_bad->status);
  14817. // Whitespace-only header value should be considered invalid / non-matching
  14818. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14819. "Host: localhost\r\n"
  14820. "If-None-Match: \r\n"
  14821. "Connection: close\r\n"
  14822. "\r\n";
  14823. std::string out;
  14824. ASSERT_TRUE(send_request(5, raw_req, &out));
  14825. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14826. svr.stop();
  14827. t.join();
  14828. std::remove(fname);
  14829. }
  14830. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14831. using namespace httplib;
  14832. const char *fname = "ims_invalid_format.txt";
  14833. const char *content = "ims-bad-format";
  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. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14845. ASSERT_TRUE(res1);
  14846. ASSERT_EQ(200, res1->status);
  14847. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14848. // If-Modified-Since with invalid format should not result in 304
  14849. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14850. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14851. ASSERT_TRUE(res_bad);
  14852. EXPECT_EQ(200, res_bad->status);
  14853. // If-Range with invalid date format should be treated as mismatch -> full
  14854. // content (200)
  14855. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14856. {"If-Range", "invalid-date"}};
  14857. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14858. ASSERT_TRUE(res_ifrange);
  14859. EXPECT_EQ(200, res_ifrange->status);
  14860. svr.stop();
  14861. t.join();
  14862. std::remove(fname);
  14863. }
  14864. TEST(ETagTest, IfRangeWithMalformedETag) {
  14865. using namespace httplib;
  14866. const char *fname = "ifrange_malformed.txt";
  14867. const std::string content = "0123456789";
  14868. {
  14869. std::ofstream ofs(fname);
  14870. ofs << content;
  14871. ASSERT_TRUE(ofs.good());
  14872. }
  14873. Server svr;
  14874. svr.set_mount_point("/static", ".");
  14875. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14876. svr.wait_until_ready();
  14877. Client cli(HOST, PORT);
  14878. // First request: get ETag
  14879. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14880. ASSERT_TRUE(res1);
  14881. ASSERT_EQ(200, res1->status);
  14882. ASSERT_TRUE(res1->has_header("ETag"));
  14883. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14884. // full content (200)
  14885. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14886. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14887. ASSERT_TRUE(res2);
  14888. EXPECT_EQ(200, res2->status);
  14889. EXPECT_EQ(content, res2->body);
  14890. svr.stop();
  14891. t.join();
  14892. std::remove(fname);
  14893. }
  14894. TEST(ETagTest, ExtremeLargeDateValues) {
  14895. using namespace httplib;
  14896. const char *fname = "ims_extreme_date.txt";
  14897. const char *content = "ims-extreme-date";
  14898. {
  14899. std::ofstream ofs(fname);
  14900. ofs << content;
  14901. ASSERT_TRUE(ofs.good());
  14902. }
  14903. Server svr;
  14904. svr.set_mount_point("/static", ".");
  14905. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14906. svr.wait_until_ready();
  14907. Client cli(HOST, PORT);
  14908. auto res1 = cli.Get(std::string("/static/") + fname);
  14909. ASSERT_TRUE(res1);
  14910. ASSERT_EQ(200, res1->status);
  14911. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14912. // Extremely large year that may overflow date parsing routines.
  14913. Headers h_large_date = {
  14914. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14915. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14916. ASSERT_TRUE(res_bad);
  14917. // Expect server to treat this as invalid/mismatch and return full content
  14918. EXPECT_EQ(200, res_bad->status);
  14919. // If-Range with extremely large date should be treated as mismatch -> full
  14920. // content (200)
  14921. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14922. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14923. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14924. ASSERT_TRUE(res_ifrange);
  14925. EXPECT_EQ(200, res_ifrange->status);
  14926. svr.stop();
  14927. t.join();
  14928. std::remove(fname);
  14929. }
  14930. TEST(ETagTest, NegativeFileModificationTime) {
  14931. using namespace httplib;
  14932. const char *fname = "ims_negative_mtime.txt";
  14933. const std::string content = "negative-mtime";
  14934. {
  14935. std::ofstream ofs(fname);
  14936. ofs << content;
  14937. ASSERT_TRUE(ofs.good());
  14938. }
  14939. // Try to set file mtime to a negative value. This may fail on some
  14940. // platforms/filesystems; if it fails, the test will still verify server
  14941. // behaves safely by performing a regular conditional request.
  14942. #if defined(__APPLE__) || defined(__linux__)
  14943. bool set_negative = false;
  14944. do {
  14945. struct timeval times[2];
  14946. // access time: now
  14947. times[0].tv_sec = time(nullptr);
  14948. times[0].tv_usec = 0;
  14949. // modification time: negative (e.g., -1)
  14950. times[1].tv_sec = -1;
  14951. times[1].tv_usec = 0;
  14952. if (utimes(fname, times) == 0) { set_negative = true; }
  14953. } while (0);
  14954. #else
  14955. bool set_negative = false;
  14956. #endif
  14957. Server svr;
  14958. svr.set_mount_point("/static", ".");
  14959. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14960. svr.wait_until_ready();
  14961. Client cli(HOST, PORT);
  14962. auto res1 = cli.Get(std::string("/static/") + fname);
  14963. ASSERT_TRUE(res1);
  14964. ASSERT_EQ(200, res1->status);
  14965. bool has_last_modified = res1->has_header("Last-Modified");
  14966. std::string last_modified;
  14967. if (has_last_modified) {
  14968. last_modified = res1->get_header_value("Last-Modified");
  14969. }
  14970. if (set_negative) {
  14971. // If we successfully set a negative mtime, ensure server returns a
  14972. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14973. // with an old date and ensure server handles it without crash.
  14974. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14975. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14976. ASSERT_TRUE(res2);
  14977. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14978. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14979. } else {
  14980. // Could not set negative mtime on this platform; fall back to verifying
  14981. // that normal invalid/malformed dates are treated safely (non-304).
  14982. Headers h_bad_date = {
  14983. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14984. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14985. ASSERT_TRUE(res_bad);
  14986. EXPECT_EQ(200, res_bad->status);
  14987. }
  14988. svr.stop();
  14989. t.join();
  14990. std::remove(fname);
  14991. }
  14992. //==============================================================================
  14993. // SSE Parsing Tests
  14994. //==============================================================================
  14995. class SSEParsingTest : public ::testing::Test {
  14996. protected:
  14997. // Test helper that mimics SSE parsing behavior
  14998. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14999. int &retry_ms) {
  15000. // Blank line signals end of event
  15001. if (line.empty() || line == "\r") { return true; }
  15002. // Lines starting with ':' are comments (ignored)
  15003. if (!line.empty() && line[0] == ':') { return false; }
  15004. // Find the colon separator
  15005. auto colon_pos = line.find(':');
  15006. if (colon_pos == std::string::npos) {
  15007. // Line with no colon is treated as field name with empty value
  15008. return false;
  15009. }
  15010. std::string field = line.substr(0, colon_pos);
  15011. std::string value;
  15012. // Value starts after colon, skip optional single space
  15013. if (colon_pos + 1 < line.size()) {
  15014. size_t value_start = colon_pos + 1;
  15015. if (line[value_start] == ' ') { value_start++; }
  15016. value = line.substr(value_start);
  15017. // Remove trailing \r if present
  15018. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15019. }
  15020. // Handle known fields
  15021. if (field == "event") {
  15022. msg.event = value;
  15023. } else if (field == "data") {
  15024. // Multiple data lines are concatenated with newlines
  15025. if (!msg.data.empty()) { msg.data += "\n"; }
  15026. msg.data += value;
  15027. } else if (field == "id") {
  15028. // Empty id is valid (clears the last event ID)
  15029. msg.id = value;
  15030. } else if (field == "retry") {
  15031. // Parse retry interval in milliseconds
  15032. {
  15033. int v = 0;
  15034. auto res =
  15035. detail::from_chars(value.data(), value.data() + value.size(), v);
  15036. if (res.ec == std::errc{}) { retry_ms = v; }
  15037. }
  15038. }
  15039. // Unknown fields are ignored per SSE spec
  15040. return false;
  15041. }
  15042. };
  15043. // Test: Single-line data
  15044. TEST_F(SSEParsingTest, SingleLineData) {
  15045. sse::SSEMessage msg;
  15046. int retry_ms = 3000;
  15047. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15048. EXPECT_EQ(msg.data, "hello");
  15049. EXPECT_EQ(msg.event, "message");
  15050. // Blank line ends event
  15051. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15052. }
  15053. // Test: Multi-line data
  15054. TEST_F(SSEParsingTest, MultiLineData) {
  15055. sse::SSEMessage msg;
  15056. int retry_ms = 3000;
  15057. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15058. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15059. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15060. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15061. }
  15062. // Test: Custom event types
  15063. TEST_F(SSEParsingTest, CustomEventType) {
  15064. sse::SSEMessage msg;
  15065. int retry_ms = 3000;
  15066. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15067. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15068. EXPECT_EQ(msg.event, "update");
  15069. EXPECT_EQ(msg.data, "payload");
  15070. }
  15071. // Test: Event ID handling
  15072. TEST_F(SSEParsingTest, EventIdHandling) {
  15073. sse::SSEMessage msg;
  15074. int retry_ms = 3000;
  15075. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15076. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15077. EXPECT_EQ(msg.id, "12345");
  15078. }
  15079. // Test: Empty event ID (clears last event ID)
  15080. TEST_F(SSEParsingTest, EmptyEventId) {
  15081. sse::SSEMessage msg;
  15082. msg.id = "previous";
  15083. int retry_ms = 3000;
  15084. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15085. EXPECT_EQ(msg.id, "");
  15086. }
  15087. // Test: Retry field parsing
  15088. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15089. sse::SSEMessage msg;
  15090. int retry_ms = 3000;
  15091. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15092. EXPECT_EQ(retry_ms, 5000);
  15093. }
  15094. // Test: Invalid retry value
  15095. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15096. sse::SSEMessage msg;
  15097. int retry_ms = 3000;
  15098. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15099. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15100. }
  15101. // Test: Comments (lines starting with :)
  15102. TEST_F(SSEParsingTest, CommentsIgnored) {
  15103. sse::SSEMessage msg;
  15104. int retry_ms = 3000;
  15105. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15106. EXPECT_EQ(msg.data, "");
  15107. EXPECT_EQ(msg.event, "message");
  15108. }
  15109. // Test: Colon in value
  15110. TEST_F(SSEParsingTest, ColonInValue) {
  15111. sse::SSEMessage msg;
  15112. int retry_ms = 3000;
  15113. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15114. EXPECT_EQ(msg.data, "hello:world:test");
  15115. }
  15116. // Test: Line with no colon (field name only)
  15117. TEST_F(SSEParsingTest, FieldNameOnly) {
  15118. sse::SSEMessage msg;
  15119. int retry_ms = 3000;
  15120. // According to SSE spec, this is treated as field name with empty value
  15121. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15122. // Since we don't recognize "data" without colon, data should be empty
  15123. EXPECT_EQ(msg.data, "");
  15124. }
  15125. // Test: Trailing \r handling
  15126. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15127. sse::SSEMessage msg;
  15128. int retry_ms = 3000;
  15129. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15130. EXPECT_EQ(msg.data, "hello");
  15131. }
  15132. // Test: Unknown fields ignored
  15133. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15134. sse::SSEMessage msg;
  15135. int retry_ms = 3000;
  15136. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15137. EXPECT_EQ(msg.data, "");
  15138. EXPECT_EQ(msg.event, "message");
  15139. }
  15140. // Test: Space after colon is optional
  15141. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15142. sse::SSEMessage msg1, msg2;
  15143. int retry_ms = 3000;
  15144. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15145. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15146. EXPECT_EQ(msg1.data, "hello");
  15147. EXPECT_EQ(msg2.data, "hello");
  15148. }
  15149. // Test: SSEMessage clear
  15150. TEST_F(SSEParsingTest, MessageClear) {
  15151. sse::SSEMessage msg;
  15152. msg.event = "custom";
  15153. msg.data = "some data";
  15154. msg.id = "123";
  15155. msg.clear();
  15156. EXPECT_EQ(msg.event, "message");
  15157. EXPECT_EQ(msg.data, "");
  15158. EXPECT_EQ(msg.id, "");
  15159. }
  15160. // Test: Complete event parsing
  15161. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15162. sse::SSEMessage msg;
  15163. int retry_ms = 3000;
  15164. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15165. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15166. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15167. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15168. // Blank line ends event
  15169. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15170. EXPECT_EQ(msg.event, "notification");
  15171. EXPECT_EQ(msg.id, "evt-42");
  15172. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15173. EXPECT_EQ(retry_ms, 1000);
  15174. }
  15175. //==============================================================================
  15176. // Integration Tests with Server
  15177. //==============================================================================
  15178. class SSEIntegrationTest : public ::testing::Test {
  15179. protected:
  15180. void SetUp() override {
  15181. stop_server_.store(false);
  15182. events_.clear();
  15183. server_ = httplib::detail::make_unique<Server>();
  15184. setup_server();
  15185. start_server();
  15186. }
  15187. void TearDown() override {
  15188. stop_server_.store(true);
  15189. event_cv_.notify_all();
  15190. server_->stop();
  15191. if (server_thread_.joinable()) { server_thread_.join(); }
  15192. }
  15193. void setup_server() {
  15194. // Simple SSE endpoint
  15195. server_->Get("/events", [this](const Request &req, Response &res) {
  15196. auto last_id = req.get_header_value("Last-Event-ID");
  15197. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15198. res.set_chunked_content_provider(
  15199. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15200. std::unique_lock<std::mutex> lock(event_mutex_);
  15201. if (event_cv_.wait_for(
  15202. lock, std::chrono::milliseconds(200), [this] {
  15203. return !events_.empty() || stop_server_.load();
  15204. })) {
  15205. if (stop_server_.load()) { return false; }
  15206. if (!events_.empty()) {
  15207. std::string event = events_.front();
  15208. events_.erase(events_.begin());
  15209. sink.write(event.data(), event.size());
  15210. return true;
  15211. }
  15212. }
  15213. return !stop_server_.load();
  15214. });
  15215. });
  15216. // Endpoint that returns error
  15217. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15218. res.status = 500;
  15219. res.set_content("Internal Server Error", "text/plain");
  15220. });
  15221. // Endpoint for custom event types
  15222. server_->Get("/custom-events", [](const Request &, Response &res) {
  15223. res.set_chunked_content_provider(
  15224. "text/event-stream", [](size_t offset, DataSink &sink) {
  15225. if (offset == 0) {
  15226. std::string event = "event: update\ndata: updated\n\n"
  15227. "event: delete\ndata: deleted\n\n";
  15228. sink.write(event.data(), event.size());
  15229. }
  15230. return false; // End stream after sending
  15231. });
  15232. });
  15233. }
  15234. void start_server() {
  15235. port_ = server_->bind_to_any_port(HOST);
  15236. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15237. // Wait for server to start
  15238. while (!server_->is_running()) {
  15239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15240. }
  15241. }
  15242. int get_port() const { return port_; }
  15243. void send_event(const std::string &event) {
  15244. std::lock_guard<std::mutex> lock(event_mutex_);
  15245. events_.push_back(event);
  15246. event_cv_.notify_all();
  15247. }
  15248. std::unique_ptr<Server> server_;
  15249. std::thread server_thread_;
  15250. std::mutex event_mutex_;
  15251. std::condition_variable event_cv_;
  15252. std::vector<std::string> events_;
  15253. std::atomic<bool> stop_server_{false};
  15254. std::string last_received_event_id_;
  15255. int port_ = 0;
  15256. };
  15257. // Test: Successful connection and on_open callback
  15258. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15259. // Add a simple endpoint that sends one event and closes
  15260. server_->Get("/simple-event", [](const Request &, Response &res) {
  15261. res.set_chunked_content_provider(
  15262. "text/event-stream", [](size_t offset, DataSink &sink) {
  15263. if (offset == 0) {
  15264. std::string event = "data: hello\n\n";
  15265. sink.write(event.data(), event.size());
  15266. }
  15267. return false; // Close stream after sending
  15268. });
  15269. });
  15270. Client client("localhost", get_port());
  15271. sse::SSEClient sse(client, "/simple-event");
  15272. std::atomic<bool> open_called{false};
  15273. std::atomic<bool> message_received{false};
  15274. sse.on_open([&open_called]() { open_called.store(true); });
  15275. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15276. if (msg.data == "hello") { message_received.store(true); }
  15277. });
  15278. sse.set_reconnect_interval(100);
  15279. sse.set_max_reconnect_attempts(1);
  15280. // Start async
  15281. sse.start_async();
  15282. // Wait for message to be processed
  15283. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15284. sse.stop();
  15285. EXPECT_TRUE(open_called.load());
  15286. EXPECT_TRUE(message_received.load());
  15287. }
  15288. // Test: on_message callback
  15289. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15290. // Endpoint that sends multiple events then closes
  15291. server_->Get("/multi-event", [](const Request &, Response &res) {
  15292. res.set_chunked_content_provider(
  15293. "text/event-stream", [](size_t offset, DataSink &sink) {
  15294. if (offset == 0) {
  15295. std::string events = "data: message1\n\ndata: message2\n\n";
  15296. sink.write(events.data(), events.size());
  15297. }
  15298. return false;
  15299. });
  15300. });
  15301. Client client("localhost", get_port());
  15302. sse::SSEClient sse(client, "/multi-event");
  15303. std::vector<std::string> received_messages;
  15304. std::mutex messages_mutex;
  15305. sse.on_message([&](const sse::SSEMessage &msg) {
  15306. std::lock_guard<std::mutex> lock(messages_mutex);
  15307. received_messages.push_back(msg.data);
  15308. });
  15309. sse.set_reconnect_interval(100);
  15310. sse.set_max_reconnect_attempts(1);
  15311. sse.start_async();
  15312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15313. sse.stop();
  15314. std::lock_guard<std::mutex> lock(messages_mutex);
  15315. EXPECT_GE(received_messages.size(), 2u);
  15316. if (received_messages.size() >= 2) {
  15317. EXPECT_EQ(received_messages[0], "message1");
  15318. EXPECT_EQ(received_messages[1], "message2");
  15319. }
  15320. }
  15321. // Test: on_event for specific types
  15322. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15323. Client client("localhost", get_port());
  15324. sse::SSEClient sse(client, "/custom-events");
  15325. std::atomic<bool> update_received{false};
  15326. std::atomic<bool> delete_received{false};
  15327. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15328. if (msg.data == "updated") { update_received.store(true); }
  15329. });
  15330. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15331. if (msg.data == "deleted") { delete_received.store(true); }
  15332. });
  15333. sse.set_max_reconnect_attempts(1);
  15334. sse.start_async();
  15335. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15336. sse.stop();
  15337. EXPECT_TRUE(update_received.load());
  15338. EXPECT_TRUE(delete_received.load());
  15339. }
  15340. // Test: on_error callback on connection failure
  15341. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15342. // Connect to a non-existent port
  15343. Client client("localhost", 59999);
  15344. sse::SSEClient sse(client, "/events");
  15345. std::atomic<bool> error_called{false};
  15346. Error received_error = Error::Success;
  15347. sse.on_error([&](Error err) {
  15348. error_called.store(true);
  15349. received_error = err;
  15350. });
  15351. sse.set_reconnect_interval(50);
  15352. sse.set_max_reconnect_attempts(1);
  15353. sse.start_async();
  15354. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15355. sse.stop();
  15356. EXPECT_TRUE(error_called.load());
  15357. EXPECT_NE(received_error, Error::Success);
  15358. }
  15359. // Test: Last-Event-ID header sent on reconnect
  15360. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15361. // Endpoint that sends event with ID
  15362. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15363. res.set_chunked_content_provider(
  15364. "text/event-stream", [](size_t offset, DataSink &sink) {
  15365. if (offset == 0) {
  15366. std::string event = "id: evt-123\ndata: test\n\n";
  15367. sink.write(event.data(), event.size());
  15368. }
  15369. return false;
  15370. });
  15371. });
  15372. Client client("localhost", get_port());
  15373. sse::SSEClient sse(client, "/event-with-id");
  15374. std::atomic<bool> id_received{false};
  15375. sse.on_message([&](const sse::SSEMessage &msg) {
  15376. if (!msg.id.empty()) { id_received.store(true); }
  15377. });
  15378. sse.set_reconnect_interval(100);
  15379. sse.set_max_reconnect_attempts(1);
  15380. sse.start_async();
  15381. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15382. sse.stop();
  15383. EXPECT_TRUE(id_received.load());
  15384. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15385. }
  15386. // Test: Manual stop
  15387. TEST_F(SSEIntegrationTest, ManualStop) {
  15388. // Endpoint that sends one event and stays open briefly
  15389. std::atomic<bool> handler_running{true};
  15390. server_->Get("/stay-open", [&handler_running](const Request &,
  15391. Response &res) {
  15392. res.set_chunked_content_provider(
  15393. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15394. if (offset == 0) {
  15395. std::string event = "data: connected\n\n";
  15396. sink.write(event.data(), event.size());
  15397. }
  15398. // Keep connection open while handler_running is true
  15399. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15400. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15401. }
  15402. return false;
  15403. });
  15404. });
  15405. Client client("localhost", get_port());
  15406. sse::SSEClient sse(client, "/stay-open");
  15407. std::atomic<bool> connected{false};
  15408. sse.on_open([&connected]() { connected.store(true); });
  15409. sse.set_reconnect_interval(100);
  15410. sse.set_max_reconnect_attempts(1);
  15411. sse.start_async();
  15412. // Wait for connection to establish
  15413. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15414. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15415. }
  15416. EXPECT_TRUE(connected.load());
  15417. EXPECT_TRUE(sse.is_connected());
  15418. // Signal handler to stop
  15419. handler_running.store(false);
  15420. // Stop SSE client
  15421. sse.stop();
  15422. EXPECT_FALSE(sse.is_connected());
  15423. }
  15424. // Test: SSEClient with custom headers
  15425. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15426. // Setup a server endpoint that checks for custom header
  15427. std::atomic<bool> header_received{false};
  15428. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15429. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15430. header_received.store(true);
  15431. }
  15432. res.set_chunked_content_provider("text/event-stream",
  15433. [](size_t, DataSink &) { return false; });
  15434. });
  15435. Client client("localhost", get_port());
  15436. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15437. sse::SSEClient sse(client, "/header-check", headers);
  15438. sse.set_max_reconnect_attempts(1);
  15439. sse.start_async();
  15440. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15441. sse.stop();
  15442. EXPECT_TRUE(header_received.load());
  15443. }
  15444. // Test: Reconnect interval configuration
  15445. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15446. Client client("localhost", get_port());
  15447. sse::SSEClient sse(client, "/events");
  15448. auto &result = sse.set_reconnect_interval(500);
  15449. // Builder pattern should return reference to self
  15450. EXPECT_EQ(&result, &sse);
  15451. }
  15452. // Test: Max reconnect attempts
  15453. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15454. // Connect to non-existent port to force reconnects
  15455. Client client("localhost", 59998);
  15456. sse::SSEClient sse(client, "/events");
  15457. std::atomic<int> error_count{0};
  15458. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15459. sse.set_reconnect_interval(50);
  15460. sse.set_max_reconnect_attempts(2);
  15461. auto start = std::chrono::steady_clock::now();
  15462. sse.start(); // Blocking call
  15463. auto end = std::chrono::steady_clock::now();
  15464. // Should have stopped after 2 failed attempts
  15465. EXPECT_GE(error_count.load(), 2);
  15466. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15467. auto duration =
  15468. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15469. #ifdef _WIN32
  15470. // Windows is much slower for socket connection failures
  15471. EXPECT_LT(duration.count(), 7000);
  15472. #else
  15473. EXPECT_LT(duration.count(), 1000);
  15474. #endif
  15475. }
  15476. // Test: Multi-line data in integration
  15477. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15478. // Endpoint with multi-line data
  15479. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15480. res.set_chunked_content_provider(
  15481. "text/event-stream", [](size_t offset, DataSink &sink) {
  15482. if (offset == 0) {
  15483. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15484. sink.write(event.data(), event.size());
  15485. }
  15486. return false;
  15487. });
  15488. });
  15489. Client client("localhost", get_port());
  15490. sse::SSEClient sse(client, "/multiline-data");
  15491. std::string received_data;
  15492. std::mutex data_mutex;
  15493. sse.on_message([&](const sse::SSEMessage &msg) {
  15494. std::lock_guard<std::mutex> lock(data_mutex);
  15495. received_data = msg.data;
  15496. });
  15497. sse.set_reconnect_interval(100);
  15498. sse.set_max_reconnect_attempts(1);
  15499. sse.start_async();
  15500. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15501. sse.stop();
  15502. std::lock_guard<std::mutex> lock(data_mutex);
  15503. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15504. }
  15505. // Test: Auto-reconnect after server disconnection
  15506. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15507. std::atomic<int> connection_count{0};
  15508. std::atomic<int> message_count{0};
  15509. // Endpoint that sends one event and closes, forcing reconnect
  15510. server_->Get("/reconnect-test",
  15511. [&connection_count](const Request &, Response &res) {
  15512. connection_count.fetch_add(1);
  15513. res.set_chunked_content_provider(
  15514. "text/event-stream", [](size_t offset, DataSink &sink) {
  15515. if (offset == 0) {
  15516. std::string event = "data: hello\n\n";
  15517. sink.write(event.data(), event.size());
  15518. }
  15519. return false; // Close connection after sending
  15520. });
  15521. });
  15522. Client client("localhost", get_port());
  15523. sse::SSEClient sse(client, "/reconnect-test");
  15524. sse.on_message([&message_count](const sse::SSEMessage &) {
  15525. message_count.fetch_add(1);
  15526. });
  15527. sse.set_reconnect_interval(100);
  15528. sse.set_max_reconnect_attempts(3);
  15529. sse.start_async();
  15530. // Wait long enough for multiple reconnects
  15531. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15532. sse.stop();
  15533. // Should have connected multiple times (initial + reconnects)
  15534. EXPECT_GE(connection_count.load(), 2);
  15535. // Should have received messages from multiple connections
  15536. EXPECT_GE(message_count.load(), 2);
  15537. }
  15538. // Test: Last-Event-ID sent on reconnect
  15539. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15540. std::atomic<int> connection_count{0};
  15541. std::vector<std::string> received_last_event_ids;
  15542. std::mutex id_mutex;
  15543. // Endpoint that checks Last-Event-ID header and sends event with ID
  15544. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15545. int conn = connection_count.fetch_add(1);
  15546. // Capture the Last-Event-ID header from each connection
  15547. {
  15548. std::lock_guard<std::mutex> lock(id_mutex);
  15549. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15550. }
  15551. res.set_chunked_content_provider(
  15552. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15553. if (offset == 0) {
  15554. std::string event =
  15555. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15556. sink.write(event.data(), event.size());
  15557. }
  15558. return false;
  15559. });
  15560. });
  15561. Client client("localhost", get_port());
  15562. sse::SSEClient sse(client, "/reconnect-with-id");
  15563. sse.set_reconnect_interval(100);
  15564. sse.set_max_reconnect_attempts(3);
  15565. sse.start_async();
  15566. // Wait for at least 2 connections
  15567. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15568. sse.stop();
  15569. // Verify behavior
  15570. std::lock_guard<std::mutex> lock(id_mutex);
  15571. EXPECT_GE(received_last_event_ids.size(), 2u);
  15572. // First connection should have no Last-Event-ID
  15573. if (!received_last_event_ids.empty()) {
  15574. EXPECT_EQ(received_last_event_ids[0], "");
  15575. }
  15576. // Second connection should have Last-Event-ID from first connection
  15577. if (received_last_event_ids.size() >= 2) {
  15578. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15579. }
  15580. }
  15581. // Test: set_headers updates headers used on reconnect
  15582. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15583. std::vector<std::string> received_tokens;
  15584. std::mutex token_mutex;
  15585. // Endpoint that captures Authorization header
  15586. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15587. {
  15588. std::lock_guard<std::mutex> lock(token_mutex);
  15589. received_tokens.push_back(req.get_header_value("Authorization"));
  15590. }
  15591. res.set_chunked_content_provider(
  15592. "text/event-stream", [](size_t offset, DataSink &sink) {
  15593. if (offset == 0) {
  15594. std::string event = "data: hello\n\n";
  15595. sink.write(event.data(), event.size());
  15596. }
  15597. return false; // Close connection to trigger reconnect
  15598. });
  15599. });
  15600. Client client("localhost", get_port());
  15601. Headers headers = {{"Authorization", "Bearer old-token"}};
  15602. sse::SSEClient sse(client, "/auth-check", headers);
  15603. // Update headers on each successful connection
  15604. sse.on_open(
  15605. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15606. sse.set_reconnect_interval(100);
  15607. sse.set_max_reconnect_attempts(3);
  15608. sse.start_async();
  15609. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15610. sse.stop();
  15611. std::lock_guard<std::mutex> lock(token_mutex);
  15612. ASSERT_GE(received_tokens.size(), 2u);
  15613. // First connection uses original header
  15614. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15615. // Second connection uses updated header from set_headers
  15616. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15617. }
  15618. // Test: 401 allows reconnection (so on_error can refresh headers)
  15619. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15620. std::atomic<int> connection_count{0};
  15621. // Endpoint: returns 401 on first attempt, 200 on second
  15622. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15623. int conn = connection_count.fetch_add(1);
  15624. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15625. res.status = StatusCode::Unauthorized_401;
  15626. res.set_content("Unauthorized", "text/plain");
  15627. return;
  15628. }
  15629. res.set_chunked_content_provider(
  15630. "text/event-stream", [](size_t offset, DataSink &sink) {
  15631. if (offset == 0) {
  15632. std::string event = "data: authenticated\n\n";
  15633. sink.write(event.data(), event.size());
  15634. }
  15635. return false;
  15636. });
  15637. });
  15638. Client client("localhost", get_port());
  15639. Headers headers = {{"Authorization", "Bearer expired"}};
  15640. sse::SSEClient sse(client, "/auth-retry", headers);
  15641. std::atomic<bool> message_received{false};
  15642. // Refresh token on error
  15643. sse.on_error(
  15644. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15645. sse.on_message([&](const sse::SSEMessage &msg) {
  15646. if (msg.data == "authenticated") { message_received.store(true); }
  15647. });
  15648. sse.set_reconnect_interval(100);
  15649. sse.set_max_reconnect_attempts(3);
  15650. sse.start_async();
  15651. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15652. sse.stop();
  15653. // Should have reconnected after 401 and succeeded with new token
  15654. EXPECT_GE(connection_count.load(), 2);
  15655. EXPECT_TRUE(message_received.load());
  15656. }
  15657. TEST(Issue2318Test, EmptyHostString) {
  15658. {
  15659. httplib::Client cli_empty("", PORT);
  15660. auto res = cli_empty.Get("/");
  15661. ASSERT_FALSE(res);
  15662. EXPECT_EQ(httplib::Error::Connection, res.error());
  15663. }
  15664. {
  15665. httplib::Client cli(" ", PORT);
  15666. auto res = cli.Get("/");
  15667. ASSERT_FALSE(res);
  15668. EXPECT_EQ(httplib::Error::Connection, res.error());
  15669. }
  15670. }
  15671. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15672. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15673. Server svr;
  15674. // Set a small payload limit (1KB)
  15675. svr.set_payload_max_length(1024);
  15676. svr.Post("/test", [&](const Request &req, Response &res) {
  15677. res.set_content("Body size: " + std::to_string(req.body.size()),
  15678. "text/plain");
  15679. });
  15680. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15681. auto se = detail::scope_exit([&] {
  15682. svr.stop();
  15683. listen_thread.join();
  15684. });
  15685. svr.wait_until_ready();
  15686. // Create data that compresses well but exceeds limit when decompressed
  15687. // 8KB of repeated null bytes compresses to a very small size
  15688. std::string original_data(8 * 1024, '\0');
  15689. // Compress the data using gzip
  15690. std::string compressed_data;
  15691. detail::gzip_compressor compressor;
  15692. compressor.compress(original_data.data(), original_data.size(), true,
  15693. [&](const char *data, size_t size) {
  15694. compressed_data.append(data, size);
  15695. return true;
  15696. });
  15697. // Verify compression worked (compressed should be much smaller)
  15698. ASSERT_LT(compressed_data.size(), original_data.size());
  15699. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15700. // Send compressed data with Content-Encoding: gzip
  15701. Client cli(HOST, PORT);
  15702. Headers headers = {{"Content-Encoding", "gzip"}};
  15703. auto res =
  15704. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15705. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15707. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15708. }
  15709. #endif
  15710. // ============================================================================
  15711. // OpenSSL-Specific Tests
  15712. // ============================================================================
  15713. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15714. X509 *readCertificate(const std::string &strFileName) {
  15715. std::ifstream inStream(strFileName);
  15716. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15717. std::istreambuf_iterator<char>());
  15718. if (strCertPEM.empty()) return (nullptr);
  15719. BIO *pbCert = BIO_new(BIO_s_mem());
  15720. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15721. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15722. BIO_free(pbCert);
  15723. return (pCert);
  15724. }
  15725. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15726. std::ifstream inStream(strFileName);
  15727. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15728. std::istreambuf_iterator<char>());
  15729. if (strPrivateKeyPEM.empty()) return (nullptr);
  15730. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15731. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15732. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15733. BIO_free(pbPrivKey);
  15734. return (pPrivateKey);
  15735. }
  15736. TEST(BindServerTest, UpdateCerts) {
  15737. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15738. int port = svr.bind_to_any_port("0.0.0.0");
  15739. ASSERT_TRUE(svr.is_valid());
  15740. ASSERT_TRUE(port > 0);
  15741. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15742. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15743. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15744. ASSERT_TRUE(cert != nullptr);
  15745. ASSERT_TRUE(ca_cert != nullptr);
  15746. ASSERT_TRUE(key != nullptr);
  15747. X509_STORE *cert_store = X509_STORE_new();
  15748. X509_STORE_add_cert(cert_store, ca_cert);
  15749. // svr.update_certs(cert, key, cert_store); // deprecated
  15750. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15751. CLIENT_CA_CERT_FILE);
  15752. ASSERT_TRUE(svr.is_valid());
  15753. svr.stop();
  15754. X509_STORE_free(cert_store);
  15755. X509_free(cert);
  15756. X509_free(ca_cert);
  15757. EVP_PKEY_free(key);
  15758. }
  15759. // Test that update_certs() updates client CA list correctly
  15760. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15761. // Start with file-based constructor
  15762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15763. ASSERT_TRUE(svr.is_valid());
  15764. // Initially no client CA list should be set
  15765. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15766. ASSERT_TRUE(ssl_ctx != nullptr);
  15767. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15768. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15769. EXPECT_EQ(0, count_before);
  15770. // Now update with client CA (PEM string)
  15771. std::string cert_pem, key_pem, ca_pem;
  15772. read_file(SERVER_CERT_FILE, cert_pem);
  15773. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15774. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15775. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15776. ASSERT_TRUE(svr.is_valid());
  15777. // Now client CA list should be set
  15778. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15779. ASSERT_TRUE(ca_list_after != nullptr);
  15780. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15781. }
  15782. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15783. // Test that the file-path SSLServer constructor properly sets the client CA
  15784. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15786. ASSERT_TRUE(svr.is_valid());
  15787. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15788. ASSERT_TRUE(ssl_ctx != nullptr);
  15789. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15790. ASSERT_TRUE(ca_list != nullptr);
  15791. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15792. }
  15793. #endif
  15794. // ============================================================================
  15795. // MbedTLS-Specific Tests
  15796. // ============================================================================
  15797. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15798. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15799. using namespace httplib::tls;
  15800. // Track if callback was invoked
  15801. bool callback_invoked = false;
  15802. // The callback receives void* ctx which is actually MbedTlsContext*
  15803. // We can access the mbedtls_ssl_config via the context
  15804. auto setup_callback = [&callback_invoked](void *ctx) {
  15805. callback_invoked = true;
  15806. // Cast to MbedTlsContext* to access the ssl config
  15807. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15808. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15809. // Use static variables to hold certificate data (simplified for test)
  15810. static mbedtls_x509_crt own_cert;
  15811. static mbedtls_pk_context own_key;
  15812. static mbedtls_x509_crt ca_chain;
  15813. static bool initialized = false;
  15814. if (!initialized) {
  15815. mbedtls_x509_crt_init(&own_cert);
  15816. mbedtls_pk_init(&own_key);
  15817. mbedtls_x509_crt_init(&ca_chain);
  15818. // Load server certificate
  15819. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15820. return false;
  15821. }
  15822. // Load server private key.
  15823. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15824. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15825. #if MBEDTLS_VERSION_MAJOR == 3
  15826. ,
  15827. mbedtls_ctr_drbg_random, nullptr
  15828. #endif
  15829. ) != 0) {
  15830. return false;
  15831. }
  15832. // Load CA chain for client verification
  15833. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15834. return false;
  15835. }
  15836. initialized = true;
  15837. }
  15838. // Configure the SSL config
  15839. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15840. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15841. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15842. // Set minimum TLS version using mbedTLS native API
  15843. #if MBEDTLS_VERSION_MAJOR >= 3
  15844. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15845. #else
  15846. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15847. MBEDTLS_SSL_MINOR_VERSION_3);
  15848. #endif
  15849. return true;
  15850. };
  15851. SSLServer svr(setup_callback);
  15852. ASSERT_TRUE(svr.is_valid());
  15853. ASSERT_TRUE(callback_invoked);
  15854. svr.Get("/test", [&](const Request &req, Response &res) {
  15855. res.set_content("test", "text/plain");
  15856. auto cert = req.peer_cert();
  15857. ASSERT_TRUE(static_cast<bool>(cert));
  15858. auto common_name = cert.subject_cn();
  15859. EXPECT_EQ("Common Name", common_name);
  15860. });
  15861. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15862. auto se = detail::scope_exit([&] {
  15863. svr.stop();
  15864. t.join();
  15865. ASSERT_FALSE(svr.is_running());
  15866. });
  15867. svr.wait_until_ready();
  15868. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15869. cli.enable_server_certificate_verification(false);
  15870. cli.set_connection_timeout(30);
  15871. auto res = cli.Get("/test");
  15872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15873. ASSERT_EQ(StatusCode::OK_200, res->status);
  15874. }
  15875. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15876. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15877. // keep-alive SSL session, which reads through that config in
  15878. // mbedtls_ssl_close_notify.
  15879. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15881. ASSERT_TRUE(svr.is_valid());
  15882. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15883. res.set_content("test", "text/plain");
  15884. });
  15885. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15886. auto se = detail::scope_exit([&] {
  15887. svr.stop();
  15888. t.join();
  15889. ASSERT_FALSE(svr.is_running());
  15890. });
  15891. svr.wait_until_ready();
  15892. {
  15893. SSLClient cli(HOST, PORT);
  15894. cli.enable_server_certificate_verification(false);
  15895. cli.set_keep_alive(true);
  15896. auto res = cli.Get("/test");
  15897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15898. ASSERT_EQ(StatusCode::OK_200, res->status);
  15899. // cli is destructed here with the keep-alive SSL session still open.
  15900. }
  15901. }
  15902. #endif
  15903. // WebSocket Tests
  15904. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15905. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15906. // defining the meaning of these bits has been negotiated.
  15907. auto make_frame = [](uint8_t first_byte) {
  15908. std::string frame;
  15909. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15910. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15911. frame += "Hello";
  15912. return frame;
  15913. };
  15914. // RSV1 set (0x40)
  15915. {
  15916. detail::BufferStream strm;
  15917. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15918. ws::Opcode opcode;
  15919. std::string payload;
  15920. bool fin;
  15921. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15922. false, 1024));
  15923. }
  15924. // RSV2 set (0x20)
  15925. {
  15926. detail::BufferStream strm;
  15927. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15928. ws::Opcode opcode;
  15929. std::string payload;
  15930. bool fin;
  15931. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15932. false, 1024));
  15933. }
  15934. // RSV3 set (0x10)
  15935. {
  15936. detail::BufferStream strm;
  15937. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15938. ws::Opcode opcode;
  15939. std::string payload;
  15940. bool fin;
  15941. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15942. false, 1024));
  15943. }
  15944. // No RSV bits set - should succeed
  15945. {
  15946. detail::BufferStream strm;
  15947. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15948. ws::Opcode opcode;
  15949. std::string payload;
  15950. bool fin;
  15951. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15952. false, 1024));
  15953. EXPECT_EQ(ws::Opcode::Text, opcode);
  15954. EXPECT_EQ("Hello", payload);
  15955. EXPECT_TRUE(fin);
  15956. }
  15957. }
  15958. TEST(WebSocketTest, ControlFrameValidation) {
  15959. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15960. // payload length <= 125.
  15961. // Ping with FIN=0 - must be rejected
  15962. {
  15963. detail::BufferStream strm;
  15964. std::string frame;
  15965. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15966. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15967. strm.write(frame.data(), frame.size());
  15968. ws::Opcode opcode;
  15969. std::string payload;
  15970. bool fin;
  15971. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15972. false, 1024));
  15973. }
  15974. // Close with FIN=0 - must be rejected
  15975. {
  15976. detail::BufferStream strm;
  15977. std::string frame;
  15978. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15979. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15980. strm.write(frame.data(), frame.size());
  15981. ws::Opcode opcode;
  15982. std::string payload;
  15983. bool fin;
  15984. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15985. false, 1024));
  15986. }
  15987. // Ping with payload_len=126 (extended length) - must be rejected
  15988. {
  15989. detail::BufferStream strm;
  15990. std::string frame;
  15991. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15992. frame += static_cast<char>(126); // payload_len=126 (>125)
  15993. frame += static_cast<char>(0x00); // extended length high byte
  15994. frame += static_cast<char>(126); // extended length low byte
  15995. frame += std::string(126, 'x');
  15996. strm.write(frame.data(), frame.size());
  15997. ws::Opcode opcode;
  15998. std::string payload;
  15999. bool fin;
  16000. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16001. false, 1024));
  16002. }
  16003. // Ping with FIN=1 and payload_len=125 - should succeed
  16004. {
  16005. detail::BufferStream strm;
  16006. std::string frame;
  16007. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16008. frame += static_cast<char>(125); // payload_len=125
  16009. frame += std::string(125, 'x');
  16010. strm.write(frame.data(), frame.size());
  16011. ws::Opcode opcode;
  16012. std::string payload;
  16013. bool fin;
  16014. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16015. false, 1024));
  16016. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16017. EXPECT_EQ(125u, payload.size());
  16018. EXPECT_TRUE(fin);
  16019. }
  16020. }
  16021. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16022. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16023. // length MUST be 0.
  16024. // MSB set - must be rejected
  16025. {
  16026. detail::BufferStream strm;
  16027. std::string frame;
  16028. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16029. frame += static_cast<char>(127); // 64-bit extended length
  16030. frame += static_cast<char>(0x80); // MSB set (invalid)
  16031. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16032. strm.write(frame.data(), frame.size());
  16033. ws::Opcode opcode;
  16034. std::string payload;
  16035. bool fin;
  16036. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16037. false, 1024));
  16038. }
  16039. // MSB clear - should pass length parsing (will be rejected by max_len,
  16040. // but that's a different check; use a small length to verify)
  16041. {
  16042. detail::BufferStream strm;
  16043. std::string frame;
  16044. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16045. frame += static_cast<char>(127); // 64-bit extended length
  16046. frame += std::string(7, '\0'); // high bytes = 0
  16047. frame += static_cast<char>(0x03); // length = 3
  16048. frame += "abc";
  16049. strm.write(frame.data(), frame.size());
  16050. ws::Opcode opcode;
  16051. std::string payload;
  16052. bool fin;
  16053. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16054. false, 1024));
  16055. EXPECT_EQ(ws::Opcode::Text, opcode);
  16056. EXPECT_EQ("abc", payload);
  16057. }
  16058. }
  16059. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16060. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16061. // Valid UTF-8
  16062. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16063. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16064. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16065. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16066. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16067. // Invalid UTF-8
  16068. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16069. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16070. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16071. EXPECT_FALSE(
  16072. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16073. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16074. }
  16075. TEST(WebSocketTest, ConnectAndDisconnect) {
  16076. Server svr;
  16077. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16078. std::string msg;
  16079. while (ws.read(msg)) {}
  16080. });
  16081. auto port = svr.bind_to_any_port(HOST);
  16082. std::thread t([&]() { svr.listen_after_bind(); });
  16083. svr.wait_until_ready();
  16084. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16085. ASSERT_TRUE(client.connect());
  16086. EXPECT_TRUE(client.is_open());
  16087. client.close();
  16088. EXPECT_FALSE(client.is_open());
  16089. svr.stop();
  16090. t.join();
  16091. }
  16092. TEST(WebSocketTest, ValidURL) {
  16093. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16094. EXPECT_TRUE(ws1.is_valid());
  16095. ws::WebSocketClient ws2("ws://example.com/path");
  16096. EXPECT_TRUE(ws2.is_valid());
  16097. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16098. EXPECT_TRUE(ws3.is_valid());
  16099. #ifdef CPPHTTPLIB_SSL_ENABLED
  16100. ws::WebSocketClient wss1("wss://example.com/path");
  16101. EXPECT_TRUE(wss1.is_valid());
  16102. ws::WebSocketClient wss2("wss://example.com:443/path");
  16103. EXPECT_TRUE(wss2.is_valid());
  16104. #endif
  16105. }
  16106. TEST(WebSocketTest, InvalidURL) {
  16107. // No scheme
  16108. ws::WebSocketClient ws1("localhost:8080/path");
  16109. EXPECT_FALSE(ws1.is_valid());
  16110. // No path
  16111. ws::WebSocketClient ws2("ws://localhost:8080");
  16112. EXPECT_FALSE(ws2.is_valid());
  16113. // Empty string
  16114. ws::WebSocketClient ws3("");
  16115. EXPECT_FALSE(ws3.is_valid());
  16116. // Missing host
  16117. ws::WebSocketClient ws4("ws://:8080/path");
  16118. EXPECT_FALSE(ws4.is_valid());
  16119. // Port number overflow — should not crash
  16120. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16121. EXPECT_FALSE(ws5.is_valid());
  16122. // Port out of range
  16123. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16124. EXPECT_FALSE(ws6.is_valid());
  16125. }
  16126. TEST(WebSocketTest, UnsupportedScheme) {
  16127. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16128. ws::WebSocketClient ws1("http://localhost:8080/path");
  16129. EXPECT_FALSE(ws1.is_valid());
  16130. ws::WebSocketClient ws2("https://localhost:8080/path");
  16131. EXPECT_FALSE(ws2.is_valid());
  16132. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16133. EXPECT_FALSE(ws3.is_valid());
  16134. #else
  16135. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16136. std::invalid_argument);
  16137. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16138. std::invalid_argument);
  16139. #endif
  16140. }
  16141. TEST(WebSocketTest, ConnectWhenInvalid) {
  16142. ws::WebSocketClient ws("not a valid url");
  16143. EXPECT_FALSE(ws.is_valid());
  16144. EXPECT_FALSE(ws.connect());
  16145. }
  16146. TEST(WebSocketTest, DefaultPort) {
  16147. ws::WebSocketClient ws1("ws://example.com/path");
  16148. EXPECT_TRUE(ws1.is_valid());
  16149. // ws:// defaults to port 80 (verified by successful parse)
  16150. #ifdef CPPHTTPLIB_SSL_ENABLED
  16151. ws::WebSocketClient ws2("wss://example.com/path");
  16152. EXPECT_TRUE(ws2.is_valid());
  16153. // wss:// defaults to port 443 (verified by successful parse)
  16154. #endif
  16155. }
  16156. TEST(WebSocketTest, IPv6LiteralAddress) {
  16157. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16158. EXPECT_TRUE(ws1.is_valid());
  16159. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16160. EXPECT_TRUE(ws2.is_valid());
  16161. }
  16162. TEST(WebSocketTest, ComplexPath) {
  16163. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16164. EXPECT_TRUE(ws1.is_valid());
  16165. ws::WebSocketClient ws2("ws://localhost:8080/");
  16166. EXPECT_TRUE(ws2.is_valid());
  16167. }
  16168. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16169. Server svr;
  16170. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16171. std::string msg;
  16172. while (ws.read(msg)) {}
  16173. });
  16174. auto port = svr.bind_to_any_port(HOST);
  16175. std::thread t([&]() { svr.listen_after_bind(); });
  16176. svr.wait_until_ready();
  16177. auto another_host = "example.com";
  16178. auto wrong_ip = "192.0.2.1";
  16179. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16180. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16181. ASSERT_TRUE(client.connect());
  16182. EXPECT_TRUE(client.is_open());
  16183. client.close();
  16184. svr.stop();
  16185. t.join();
  16186. }
  16187. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16188. Server svr;
  16189. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16190. std::string msg;
  16191. while (ws.read(msg)) {}
  16192. });
  16193. auto port = svr.bind_to_any_port(HOST);
  16194. std::thread t([&]() { svr.listen_after_bind(); });
  16195. svr.wait_until_ready();
  16196. auto wrong_ip = "192.0.2.1";
  16197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16198. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16199. client.set_connection_timeout(1);
  16200. client.set_read_timeout(1);
  16201. client.set_write_timeout(1);
  16202. EXPECT_FALSE(client.connect());
  16203. EXPECT_FALSE(client.is_open());
  16204. svr.stop();
  16205. t.join();
  16206. }
  16207. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16208. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16209. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16210. // (RFC 6761) is only a map key and the Host header value.
  16211. auto host = "target.invalid";
  16212. Server svr;
  16213. std::string received_host;
  16214. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16215. received_host = req.get_header_value("Host");
  16216. std::string msg;
  16217. while (ws.read(msg)) {}
  16218. });
  16219. auto port = svr.bind_to_any_port(HOST);
  16220. std::thread t([&]() { svr.listen_after_bind(); });
  16221. // ASSERT_* below returns from the test body, which would leave t joinable
  16222. // and make ~thread call std::terminate.
  16223. auto se = detail::scope_exit([&] {
  16224. svr.stop();
  16225. if (t.joinable()) { t.join(); }
  16226. });
  16227. svr.wait_until_ready();
  16228. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16229. std::to_string(port) + "/ws");
  16230. client.set_hostname_addr_map({{host, HOST}});
  16231. ASSERT_TRUE(client.connect());
  16232. EXPECT_TRUE(client.is_open());
  16233. client.close();
  16234. svr.stop();
  16235. t.join();
  16236. // The mapping only redirects the connection; the identity stays host_.
  16237. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16238. }
  16239. class WebSocketIntegrationTest : public ::testing::Test {
  16240. protected:
  16241. void SetUp() override {
  16242. server_ = httplib::detail::make_unique<Server>();
  16243. setup_server();
  16244. start_server();
  16245. }
  16246. void TearDown() override {
  16247. server_->stop();
  16248. if (server_thread_.joinable()) { server_thread_.join(); }
  16249. }
  16250. void setup_server() {
  16251. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16252. std::string msg;
  16253. ws::ReadResult ret;
  16254. while ((ret = ws.read(msg))) {
  16255. if (ret == ws::Binary) {
  16256. ws.send(msg.data(), msg.size());
  16257. } else {
  16258. ws.send(msg);
  16259. }
  16260. }
  16261. });
  16262. server_->WebSocket("/ws-echo-string",
  16263. [](const Request &, ws::WebSocket &ws) {
  16264. std::string msg;
  16265. while (ws.read(msg)) {
  16266. ws.send("echo: " + msg);
  16267. }
  16268. });
  16269. server_->WebSocket(
  16270. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16271. // Echo back request metadata
  16272. ws.send("path:" + req.path);
  16273. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16274. std::string msg;
  16275. while (ws.read(msg)) {}
  16276. });
  16277. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16278. std::string msg;
  16279. ws.read(msg); // wait for a message
  16280. ws.close();
  16281. });
  16282. server_->WebSocket("/ws-close-status",
  16283. [](const Request &, ws::WebSocket &ws) {
  16284. std::string msg;
  16285. ws.read(msg); // wait for a message
  16286. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16287. });
  16288. server_->WebSocket(
  16289. "/ws-subprotocol",
  16290. [](const Request &, ws::WebSocket &ws) {
  16291. std::string msg;
  16292. while (ws.read(msg)) {
  16293. ws.send(msg);
  16294. }
  16295. },
  16296. [](const std::vector<std::string> &protocols) -> std::string {
  16297. for (const auto &p : protocols) {
  16298. if (p == "graphql-ws") { return p; }
  16299. }
  16300. return "";
  16301. });
  16302. }
  16303. void start_server() {
  16304. port_ = server_->bind_to_any_port(HOST);
  16305. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16306. server_->wait_until_ready();
  16307. }
  16308. std::unique_ptr<Server> server_;
  16309. std::thread server_thread_;
  16310. int port_ = 0;
  16311. };
  16312. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16313. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16314. "/ws-echo");
  16315. ASSERT_TRUE(client.connect());
  16316. ASSERT_TRUE(client.is_open());
  16317. ASSERT_TRUE(client.send("Hello WebSocket"));
  16318. std::string msg;
  16319. EXPECT_EQ(ws::Text, client.read(msg));
  16320. EXPECT_EQ("Hello WebSocket", msg);
  16321. client.close();
  16322. }
  16323. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16324. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16325. "/ws-echo");
  16326. ASSERT_TRUE(client.connect());
  16327. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16328. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16329. std::string msg;
  16330. EXPECT_EQ(ws::Binary, client.read(msg));
  16331. EXPECT_EQ(binary_data, msg);
  16332. client.close();
  16333. }
  16334. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16336. "/ws-echo");
  16337. ASSERT_TRUE(client.connect());
  16338. for (int i = 0; i < 10; i++) {
  16339. auto text = "message " + std::to_string(i);
  16340. ASSERT_TRUE(client.send(text));
  16341. std::string msg;
  16342. ASSERT_TRUE(client.read(msg));
  16343. EXPECT_EQ(text, msg);
  16344. }
  16345. client.close();
  16346. }
  16347. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16348. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16349. "/ws-close");
  16350. ASSERT_TRUE(client.connect());
  16351. // Send a message to trigger the server to close
  16352. ASSERT_TRUE(client.send("trigger close"));
  16353. // The server will close, so read should return false
  16354. std::string msg;
  16355. EXPECT_FALSE(client.read(msg));
  16356. EXPECT_FALSE(client.is_open());
  16357. }
  16358. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16360. "/ws-echo");
  16361. ASSERT_TRUE(client.connect());
  16362. // 128KB message
  16363. std::string large_data(128 * 1024, 'X');
  16364. ASSERT_TRUE(client.send(large_data));
  16365. std::string msg;
  16366. ASSERT_TRUE(client.read(msg));
  16367. EXPECT_EQ(large_data, msg);
  16368. client.close();
  16369. }
  16370. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16371. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16372. "/ws-echo");
  16373. ASSERT_TRUE(client.connect());
  16374. const int num_threads = 4;
  16375. std::vector<std::thread> threads;
  16376. std::atomic<int> send_count{0};
  16377. for (int t = 0; t < num_threads; t++) {
  16378. threads.emplace_back([&client, &send_count, t]() {
  16379. for (int i = 0; i < 5; i++) {
  16380. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16381. if (client.send(text)) { send_count++; }
  16382. }
  16383. });
  16384. }
  16385. for (auto &th : threads) {
  16386. th.join();
  16387. }
  16388. int received = 0;
  16389. std::string msg;
  16390. while (received < send_count.load()) {
  16391. if (!client.read(msg)) { break; }
  16392. received++;
  16393. }
  16394. EXPECT_EQ(send_count.load(), received);
  16395. client.close();
  16396. }
  16397. TEST_F(WebSocketIntegrationTest, ReadString) {
  16398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16399. "/ws-echo-string");
  16400. ASSERT_TRUE(client.connect());
  16401. ASSERT_TRUE(client.send("hello"));
  16402. std::string msg;
  16403. ASSERT_TRUE(client.read(msg));
  16404. EXPECT_EQ("echo: hello", msg);
  16405. ASSERT_TRUE(client.send("world"));
  16406. ASSERT_TRUE(client.read(msg));
  16407. EXPECT_EQ("echo: world", msg);
  16408. client.close();
  16409. }
  16410. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16411. Headers headers = {{"X-Test-Header", "test-value"}};
  16412. ws::WebSocketClient client(
  16413. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16414. ASSERT_TRUE(client.connect());
  16415. std::string msg;
  16416. ASSERT_TRUE(client.read(msg));
  16417. EXPECT_EQ("path:/ws-request-info", msg);
  16418. ASSERT_TRUE(client.read(msg));
  16419. EXPECT_EQ("header:test-value", msg);
  16420. client.close();
  16421. }
  16422. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16423. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16424. "/ws-echo");
  16425. client.set_read_timeout(1, 0); // 1 second
  16426. ASSERT_TRUE(client.connect());
  16427. // Don't send anything — server echo handler waits for a message,
  16428. // so read() should time out and return false.
  16429. std::string msg;
  16430. EXPECT_FALSE(client.read(msg));
  16431. }
  16432. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16434. "/ws-echo");
  16435. client.set_read_timeout(5, 0);
  16436. ASSERT_TRUE(client.connect());
  16437. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16438. // The server should reject it and close the connection.
  16439. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16440. client.send(oversized);
  16441. // The server's read() should have failed due to payload limit,
  16442. // so our read() should return false (connection closed).
  16443. std::string msg;
  16444. EXPECT_FALSE(client.read(msg));
  16445. }
  16446. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16447. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16448. "/ws-echo");
  16449. client.set_read_timeout(10, 0);
  16450. ASSERT_TRUE(client.connect());
  16451. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16452. // This should succeed.
  16453. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16454. ASSERT_TRUE(client.send(at_limit));
  16455. std::string msg;
  16456. ASSERT_TRUE(client.read(msg));
  16457. EXPECT_EQ(at_limit.size(), msg.size());
  16458. client.close();
  16459. }
  16460. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16461. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16462. "/nonexistent");
  16463. EXPECT_FALSE(client.connect());
  16464. EXPECT_FALSE(client.is_open());
  16465. }
  16466. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16467. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16468. "/ws-echo");
  16469. ASSERT_TRUE(client.connect());
  16470. ASSERT_TRUE(client.send(""));
  16471. std::string msg;
  16472. EXPECT_EQ(ws::Text, client.read(msg));
  16473. EXPECT_EQ("", msg);
  16474. client.close();
  16475. }
  16476. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16477. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16478. "/ws-echo");
  16479. // First connection
  16480. ASSERT_TRUE(client.connect());
  16481. ASSERT_TRUE(client.send("first"));
  16482. std::string msg;
  16483. ASSERT_TRUE(client.read(msg));
  16484. EXPECT_EQ("first", msg);
  16485. client.close();
  16486. EXPECT_FALSE(client.is_open());
  16487. // Reconnect using the same client object
  16488. ASSERT_TRUE(client.connect());
  16489. ASSERT_TRUE(client.is_open());
  16490. ASSERT_TRUE(client.send("second"));
  16491. ASSERT_TRUE(client.read(msg));
  16492. EXPECT_EQ("second", msg);
  16493. client.close();
  16494. }
  16495. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16496. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16497. "/ws-close-status");
  16498. ASSERT_TRUE(client.connect());
  16499. // Trigger the server to close with GoingAway status
  16500. ASSERT_TRUE(client.send("trigger"));
  16501. // read() should return false after receiving the close frame
  16502. std::string msg;
  16503. EXPECT_FALSE(client.read(msg));
  16504. EXPECT_FALSE(client.is_open());
  16505. }
  16506. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16507. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16508. "/ws-echo");
  16509. ASSERT_TRUE(client.connect());
  16510. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16511. EXPECT_FALSE(client.is_open());
  16512. }
  16513. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16514. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16515. ws::WebSocketClient client(
  16516. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16517. ASSERT_TRUE(client.connect());
  16518. // Server should have selected graphql-ws
  16519. EXPECT_EQ("graphql-ws", client.subprotocol());
  16520. client.close();
  16521. }
  16522. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16523. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16524. ws::WebSocketClient client(
  16525. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16526. ASSERT_TRUE(client.connect());
  16527. // Server should not have selected any subprotocol
  16528. EXPECT_TRUE(client.subprotocol().empty());
  16529. client.close();
  16530. }
  16531. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16532. // Connect without requesting any subprotocol
  16533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16534. "/ws-subprotocol");
  16535. ASSERT_TRUE(client.connect());
  16536. EXPECT_TRUE(client.subprotocol().empty());
  16537. client.close();
  16538. }
  16539. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16541. "/ws-echo");
  16542. client.set_tcp_nodelay(true);
  16543. client.set_connection_timeout(3, 0);
  16544. bool socket_options_called = false;
  16545. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16546. ASSERT_TRUE(client.connect());
  16547. ASSERT_TRUE(client.is_open());
  16548. EXPECT_TRUE(socket_options_called);
  16549. ASSERT_TRUE(client.send("hello"));
  16550. std::string msg;
  16551. auto result = client.read(msg);
  16552. EXPECT_EQ(result, ws::ReadResult::Text);
  16553. EXPECT_EQ(msg, "hello");
  16554. client.close();
  16555. }
  16556. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16557. Server svr;
  16558. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16559. if (!req.has_header("Authorization")) {
  16560. res.status = StatusCode::Unauthorized_401;
  16561. res.set_content("Unauthorized", "text/plain");
  16562. return Server::HandlerResponse::Handled;
  16563. }
  16564. return Server::HandlerResponse::Unhandled;
  16565. });
  16566. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16567. std::string msg;
  16568. while (ws.read(msg)) {
  16569. ws.send(msg);
  16570. }
  16571. });
  16572. auto port = svr.bind_to_any_port("localhost");
  16573. std::thread t([&]() { svr.listen_after_bind(); });
  16574. svr.wait_until_ready();
  16575. // Without Authorization header - should be rejected before upgrade
  16576. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16577. EXPECT_FALSE(client1.connect());
  16578. // With Authorization header - should succeed
  16579. Headers headers = {{"Authorization", "Bearer token123"}};
  16580. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16581. headers);
  16582. ASSERT_TRUE(client2.connect());
  16583. ASSERT_TRUE(client2.send("hello"));
  16584. std::string msg;
  16585. ASSERT_TRUE(client2.read(msg));
  16586. EXPECT_EQ("hello", msg);
  16587. client2.close();
  16588. svr.stop();
  16589. t.join();
  16590. }
  16591. TEST(WebSocketTest, QueryStringInHandshake) {
  16592. Server svr;
  16593. std::mutex mtx;
  16594. std::string received_target;
  16595. std::string received_token;
  16596. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16597. {
  16598. std::lock_guard<std::mutex> lock(mtx);
  16599. received_target = req.target;
  16600. if (req.has_param("token")) {
  16601. received_token = req.get_param_value("token");
  16602. }
  16603. }
  16604. std::string msg;
  16605. while (ws.read(msg)) {
  16606. ws.send(msg);
  16607. }
  16608. });
  16609. auto port = svr.bind_to_any_port("localhost");
  16610. std::thread t([&]() { svr.listen_after_bind(); });
  16611. svr.wait_until_ready();
  16612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16613. "/ws?token=ABC&session=123");
  16614. ASSERT_TRUE(client.connect());
  16615. // Round-trip ensures the handler has run and captured the request.
  16616. ASSERT_TRUE(client.send("hello"));
  16617. std::string msg;
  16618. ASSERT_TRUE(client.read(msg));
  16619. EXPECT_EQ("hello", msg);
  16620. client.close();
  16621. {
  16622. std::lock_guard<std::mutex> lock(mtx);
  16623. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16624. EXPECT_EQ("ABC", received_token);
  16625. }
  16626. svr.stop();
  16627. t.join();
  16628. }
  16629. // Run a handshake against a throwaway server and hand the request the server
  16630. // received back to the caller, so tests can assert on the headers the client
  16631. // actually put on the wire.
  16632. static void capture_websocket_handshake_request(
  16633. const Headers &client_headers,
  16634. std::function<void(const Request &, int port)> verify) {
  16635. Server svr;
  16636. std::mutex mtx;
  16637. Request received;
  16638. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16639. {
  16640. std::lock_guard<std::mutex> lock(mtx);
  16641. received = req;
  16642. }
  16643. std::string msg;
  16644. while (ws.read(msg)) {
  16645. ws.send(msg);
  16646. }
  16647. });
  16648. auto port = svr.bind_to_any_port("localhost");
  16649. std::thread t([&]() { svr.listen_after_bind(); });
  16650. auto se = detail::scope_exit([&] {
  16651. svr.stop();
  16652. t.join();
  16653. });
  16654. svr.wait_until_ready();
  16655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  16656. client_headers);
  16657. ASSERT_TRUE(client.connect());
  16658. ASSERT_TRUE(client.send("hello"));
  16659. std::string msg;
  16660. ASSERT_TRUE(client.read(msg));
  16661. client.close();
  16662. {
  16663. std::lock_guard<std::mutex> lock(mtx);
  16664. verify(received, port);
  16665. }
  16666. }
  16667. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  16668. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  16669. // Non-default port must be present in the Host header. Default ports
  16670. // (80/443) are omitted; that logic is covered by
  16671. // MakeHostAndPortStringTest.
  16672. EXPECT_EQ("localhost:" + std::to_string(port),
  16673. req.get_header_value("Host"));
  16674. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  16675. req.get_header_value("User-Agent"));
  16676. EXPECT_FALSE(req.has_header("Accept"));
  16677. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  16678. EXPECT_FALSE(req.has_header("Content-Length"));
  16679. });
  16680. }
  16681. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  16682. capture_websocket_handshake_request(
  16683. {{"Host", "example.com"},
  16684. {"User-Agent", "custom-agent"},
  16685. {"X-Custom", "value"}},
  16686. [](const Request &req, int) {
  16687. EXPECT_EQ("example.com", req.get_header_value("Host"));
  16688. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  16689. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  16690. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  16691. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  16692. });
  16693. }
  16694. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  16695. capture_websocket_handshake_request(
  16696. {{"Upgrade", "bogus"},
  16697. {"Connection", "close"},
  16698. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  16699. {"Sec-WebSocket-Version", "8"}},
  16700. [](const Request &req, int) {
  16701. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  16702. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  16703. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  16704. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  16705. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  16706. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  16707. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  16708. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  16709. req.get_header_value("Sec-WebSocket-Key"));
  16710. });
  16711. }
  16712. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  16713. // A header the client refuses to send must abort the handshake before any
  16714. // part of it reaches the wire; a lone request line would otherwise sit in
  16715. // the peer's buffer as a truncated request.
  16716. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16717. ASSERT_NE(INVALID_SOCKET, srv);
  16718. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  16719. sockaddr_in addr{};
  16720. addr.sin_family = AF_INET;
  16721. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  16722. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16723. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16724. ASSERT_EQ(0, ::listen(srv, 1));
  16725. sockaddr_in bound{};
  16726. socklen_t bound_len = sizeof(bound);
  16727. ASSERT_EQ(
  16728. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  16729. auto port = ntohs(bound.sin_port);
  16730. ssize_t received = -1;
  16731. std::thread t([&] {
  16732. // Bound every blocking call so a regression fails the test with a bad
  16733. // value instead of hanging the suite.
  16734. fd_set rfds;
  16735. FD_ZERO(&rfds);
  16736. FD_SET(srv, &rfds);
  16737. timeval tv{5, 0};
  16738. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  16739. 0) {
  16740. return;
  16741. }
  16742. sockaddr_in cli_addr{};
  16743. socklen_t cli_len = sizeof(cli_addr);
  16744. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16745. if (cli == INVALID_SOCKET) { return; }
  16746. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  16747. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16748. char buf[4096];
  16749. received = ::recv(cli, buf, sizeof(buf), 0);
  16750. });
  16751. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  16752. // connect() has already shut the socket down by the time it returns false,
  16753. // so the peer sees EOF without waiting for the client to be destroyed.
  16754. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  16755. {{"X-Bad", "a\r\nInjected: 1"}});
  16756. EXPECT_FALSE(client.connect());
  16757. t.join();
  16758. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  16759. EXPECT_EQ(0, received);
  16760. }
  16761. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  16762. // The socket path doubles as the URL host, so it must not contain '/'.
  16763. const char *shard = getenv("GTEST_SHARD_INDEX");
  16764. const std::string sock_path =
  16765. shard ? std::string("httplib-ws-") + shard + ".sock"
  16766. : std::string("httplib-ws.sock");
  16767. std::remove(sock_path.c_str());
  16768. Server svr;
  16769. std::mutex mtx;
  16770. std::string received_host;
  16771. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16772. {
  16773. std::lock_guard<std::mutex> lock(mtx);
  16774. received_host = req.get_header_value("Host");
  16775. }
  16776. std::string msg;
  16777. while (ws.read(msg)) {
  16778. ws.send(msg);
  16779. }
  16780. });
  16781. svr.set_address_family(AF_UNIX);
  16782. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  16783. auto se = detail::scope_exit([&] {
  16784. svr.stop();
  16785. t.join();
  16786. std::remove(sock_path.c_str());
  16787. });
  16788. svr.wait_until_ready();
  16789. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  16790. client.set_address_family(AF_UNIX);
  16791. ASSERT_TRUE(client.connect());
  16792. ASSERT_TRUE(client.send("hello"));
  16793. std::string msg;
  16794. ASSERT_TRUE(client.read(msg));
  16795. client.close();
  16796. {
  16797. std::lock_guard<std::mutex> lock(mtx);
  16798. // There is no host:port for a Unix socket, so the same "localhost"
  16799. // placeholder the HTTP client uses is expected.
  16800. EXPECT_EQ("localhost", received_host);
  16801. }
  16802. }
  16803. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16804. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16805. protected:
  16806. void SetUp() override {
  16807. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16808. SERVER_PRIVATE_KEY_FILE);
  16809. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16810. std::string msg;
  16811. ws::ReadResult ret;
  16812. while ((ret = ws.read(msg))) {
  16813. if (ret == ws::Binary) {
  16814. ws.send(msg.data(), msg.size());
  16815. } else {
  16816. ws.send(msg);
  16817. }
  16818. }
  16819. });
  16820. port_ = server_->bind_to_any_port(HOST);
  16821. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16822. server_->wait_until_ready();
  16823. }
  16824. void TearDown() override {
  16825. server_->stop();
  16826. if (server_thread_.joinable()) { server_thread_.join(); }
  16827. }
  16828. std::unique_ptr<SSLServer> server_;
  16829. std::thread server_thread_;
  16830. int port_ = 0;
  16831. };
  16832. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16833. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16834. "/ws-echo");
  16835. client.enable_server_certificate_verification(false);
  16836. ASSERT_TRUE(client.connect());
  16837. ASSERT_TRUE(client.is_open());
  16838. ASSERT_TRUE(client.send("Hello WSS"));
  16839. std::string msg;
  16840. EXPECT_EQ(ws::Text, client.read(msg));
  16841. EXPECT_EQ("Hello WSS", msg);
  16842. client.close();
  16843. }
  16844. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16845. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16846. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16847. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16848. // client (without calling close() first) is the only path that runs
  16849. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16850. // bug exactly.
  16851. //
  16852. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16853. // when linked against an instrumented libssl; run under Valgrind to catch it
  16854. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16855. // suite (the freed session otherwise stalls on the close handshake) — this test
  16856. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16857. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16858. {
  16859. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16860. "/ws-echo");
  16861. client.enable_server_certificate_verification(false);
  16862. client.set_read_timeout(2, 0);
  16863. client.set_write_timeout(2, 0);
  16864. ASSERT_TRUE(client.connect());
  16865. ASSERT_TRUE(client.is_open());
  16866. ASSERT_TRUE(client.send("still open"));
  16867. // Intentionally do NOT call client.close(): leaving scope runs
  16868. // shutdown_and_close() with the WebSocket still open, which must send the
  16869. // close frame while the TLS session is still alive.
  16870. }
  16871. }
  16872. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16873. // shutdown_and_close() at the start of connect(), reproducing the same
  16874. // use-after-free within the test body rather than at scope exit. The second
  16875. // connect must succeed and echo, proving the close handshake ran over a live
  16876. // session. See the note above about memory-tool requirements.
  16877. TEST_F(WebSocketSSLIntegrationTest,
  16878. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16879. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16880. "/ws-echo");
  16881. client.enable_server_certificate_verification(false);
  16882. client.set_read_timeout(2, 0);
  16883. client.set_write_timeout(2, 0);
  16884. ASSERT_TRUE(client.connect());
  16885. ASSERT_TRUE(client.is_open());
  16886. ASSERT_TRUE(client.send("still open"));
  16887. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16888. // the still-open connection, which must not touch a freed TLS session.
  16889. ASSERT_TRUE(client.connect());
  16890. ASSERT_TRUE(client.is_open());
  16891. ASSERT_TRUE(client.send("after reconnect"));
  16892. std::string msg;
  16893. EXPECT_EQ(ws::Text, client.read(msg));
  16894. EXPECT_EQ("after reconnect", msg);
  16895. client.close();
  16896. }
  16897. #endif
  16898. #ifdef CPPHTTPLIB_SSL_ENABLED
  16899. class WebSocketSSLCATest : public ::testing::Test {
  16900. protected:
  16901. void SetUp() override {
  16902. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16903. SERVER_PRIVATE_KEY_FILE);
  16904. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16905. std::string msg;
  16906. while (ws.read(msg)) {
  16907. ws.send(msg);
  16908. }
  16909. });
  16910. port_ = server_->bind_to_any_port("127.0.0.1");
  16911. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16912. server_->wait_until_ready();
  16913. }
  16914. void TearDown() override {
  16915. server_->stop();
  16916. if (server_thread_.joinable()) { server_thread_.join(); }
  16917. }
  16918. std::string url() const {
  16919. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16920. }
  16921. std::unique_ptr<SSLServer> server_;
  16922. std::thread server_thread_;
  16923. int port_ = 0;
  16924. };
  16925. // A custom CA loaded as PEM verifies the server with full certificate
  16926. // verification enabled
  16927. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16928. ws::WebSocketClient client(url());
  16929. std::string cert;
  16930. read_file(SERVER_CERT2_FILE, cert);
  16931. client.load_ca_cert_store(cert.c_str(), cert.size());
  16932. ASSERT_TRUE(client.connect());
  16933. ASSERT_TRUE(client.send("hello"));
  16934. std::string msg;
  16935. EXPECT_EQ(ws::Text, client.read(msg));
  16936. EXPECT_EQ("hello", msg);
  16937. client.close();
  16938. }
  16939. // A custom CA that does not cover the server must fail verification (the
  16940. // custom CA is exclusive; system certs are not loaded alongside it)
  16941. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16942. ws::WebSocketClient client(url());
  16943. std::string cert;
  16944. read_file(CLIENT_CA_CERT_FILE, cert);
  16945. client.load_ca_cert_store(cert.c_str(), cert.size());
  16946. ASSERT_FALSE(client.connect());
  16947. }
  16948. // Regression test: reconnecting with a native custom CA store used to reuse
  16949. // a store handle the previous TLS context had already freed (use-after-free
  16950. // under the OpenSSL backend). The context now lives as long as the client.
  16951. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16952. ws::WebSocketClient client(url());
  16953. std::string cert;
  16954. read_file(SERVER_CERT2_FILE, cert);
  16955. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16956. ASSERT_TRUE(client.connect());
  16957. client.close();
  16958. ASSERT_TRUE(client.connect());
  16959. ASSERT_TRUE(client.send("again"));
  16960. std::string msg;
  16961. EXPECT_EQ(ws::Text, client.read(msg));
  16962. EXPECT_EQ("again", msg);
  16963. client.close();
  16964. }
  16965. // Regression test: a certificate with a trusted chain but no identity match
  16966. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16967. // verification entirely for IP hosts, so this connection succeeded there.
  16968. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16969. // chain verification while the identity check must still fail.
  16970. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16972. ASSERT_TRUE(svr.is_valid());
  16973. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16974. std::string msg;
  16975. while (ws.read(msg)) {
  16976. ws.send(msg);
  16977. }
  16978. });
  16979. auto port = svr.bind_to_any_port("127.0.0.1");
  16980. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16981. auto se = detail::scope_exit([&] {
  16982. svr.stop();
  16983. t.join();
  16984. });
  16985. svr.wait_until_ready();
  16986. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16987. "/echo");
  16988. std::string cert;
  16989. read_file(SERVER_CERT_FILE, cert);
  16990. client.load_ca_cert_store(cert.c_str(), cert.size());
  16991. ASSERT_FALSE(client.connect());
  16992. }
  16993. #endif
  16994. #if !defined(_WIN32)
  16995. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16996. auto secret_dir = std::string("./symlink_test_secret");
  16997. auto served_dir = std::string("./symlink_test_served");
  16998. auto secret_file = secret_dir + "/secret.txt";
  16999. auto symlink_path = served_dir + "/escape";
  17000. // Setup: create directories and files
  17001. mkdir(secret_dir.c_str(), 0755);
  17002. mkdir(served_dir.c_str(), 0755);
  17003. {
  17004. std::ofstream ofs(secret_file);
  17005. ofs << "SECRET_DATA";
  17006. }
  17007. // Create symlink using absolute path so it resolves correctly
  17008. #ifdef PATH_MAX
  17009. char abs_secret[PATH_MAX];
  17010. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17011. #else
  17012. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17013. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17014. ASSERT_NE(nullptr, abs_secret);
  17015. #endif
  17016. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17017. auto se = detail::scope_exit([&] {
  17018. unlink(symlink_path.c_str());
  17019. unlink(secret_file.c_str());
  17020. rmdir(served_dir.c_str());
  17021. rmdir(secret_dir.c_str());
  17022. });
  17023. Server svr;
  17024. svr.set_mount_point("/", served_dir);
  17025. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17026. auto se2 = detail::scope_exit([&] {
  17027. svr.stop();
  17028. listen_thread.join();
  17029. });
  17030. svr.wait_until_ready();
  17031. Client cli("localhost", PORT);
  17032. // Symlink pointing outside base dir should be blocked
  17033. auto res = cli.Get("/escape/secret.txt");
  17034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17035. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17036. }
  17037. #endif
  17038. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17039. // A GET request with Content-Length to a static file handler must have its
  17040. // body drained before the keep-alive connection is reused. Otherwise the
  17041. // unread body bytes are interpreted as the next HTTP request.
  17042. //
  17043. // The body is sent AFTER receiving the first response (as in the original
  17044. // PoC) so that the stream_line_reader cannot buffer it together with the
  17045. // headers of the first request.
  17046. Server svr;
  17047. svr.set_mount_point("/", "./www");
  17048. std::atomic<int> smuggled_count(0);
  17049. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17050. smuggled_count++;
  17051. res.set_content("oops", "text/plain");
  17052. });
  17053. auto port = svr.bind_to_any_port("localhost");
  17054. thread t = thread([&] { svr.listen_after_bind(); });
  17055. auto se = detail::scope_exit([&] {
  17056. svr.stop();
  17057. t.join();
  17058. });
  17059. svr.wait_until_ready();
  17060. auto error = Error::Success;
  17061. auto sock = detail::create_client_socket(
  17062. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17063. /*connection_timeout_sec=*/2, 0,
  17064. /*read_timeout_sec=*/2, 0,
  17065. /*write_timeout_sec=*/2, 0, std::string(), error);
  17066. ASSERT_NE(INVALID_SOCKET, sock);
  17067. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17068. // The "smuggled" request will be sent as the body of the outer GET
  17069. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17070. "Host: localhost\r\n"
  17071. "Connection: close\r\n"
  17072. "\r\n";
  17073. // Step 1: Send only the outer request headers (no body yet)
  17074. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17075. "Host: localhost\r\n"
  17076. "Content-Length: " +
  17077. std::to_string(smuggled.size()) +
  17078. "\r\n"
  17079. "\r\n";
  17080. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17081. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17082. // Step 2: Read the first response (server serves file without reading body)
  17083. std::string first_response;
  17084. char buf[4096];
  17085. for (;;) {
  17086. auto n = recv(sock, buf, sizeof(buf), 0);
  17087. if (n <= 0) break;
  17088. first_response.append(buf, static_cast<size_t>(n));
  17089. // Stop once we have a complete response (headers + body)
  17090. auto hdr_end = first_response.find("\r\n\r\n");
  17091. if (hdr_end != std::string::npos) {
  17092. // Check for Content-Length to know when the body is complete
  17093. auto cl_pos = first_response.find("Content-Length:");
  17094. if (cl_pos != std::string::npos) {
  17095. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17096. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17097. auto cl = std::stoul(
  17098. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17099. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17100. } else {
  17101. break; // No Content-Length, assume headers-only response
  17102. }
  17103. }
  17104. }
  17105. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17106. // Step 3: Now send the body, which looks like a new HTTP request.
  17107. // On a vulnerable server the keep-alive loop reads this as a second request.
  17108. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17109. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17110. // Step 4: Try to read a second response (should NOT exist after fix)
  17111. std::string second_response;
  17112. for (;;) {
  17113. auto n = recv(sock, buf, sizeof(buf), 0);
  17114. if (n <= 0) break;
  17115. second_response.append(buf, static_cast<size_t>(n));
  17116. }
  17117. // The smuggled request must NOT have been processed
  17118. EXPECT_EQ(0, smuggled_count.load());
  17119. }
  17120. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17121. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17122. // must be rejected with 400 Bad Request.
  17123. Server svr;
  17124. svr.Post("/test", [&](const Request &, Response &res) {
  17125. res.set_content("ok", "text/plain");
  17126. });
  17127. thread t = thread([&] { svr.listen(HOST, PORT); });
  17128. auto se = detail::scope_exit([&] {
  17129. svr.stop();
  17130. t.join();
  17131. ASSERT_FALSE(svr.is_running());
  17132. });
  17133. svr.wait_until_ready();
  17134. // Exact "chunked"
  17135. {
  17136. auto req = "POST /test HTTP/1.1\r\n"
  17137. "Host: localhost\r\n"
  17138. "Content-Length: 5\r\n"
  17139. "Transfer-Encoding: chunked\r\n"
  17140. "Connection: close\r\n"
  17141. "\r\n"
  17142. "hello";
  17143. std::string response;
  17144. ASSERT_TRUE(send_request(1, req, &response));
  17145. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17146. response.substr(0, response.find("\r\n")));
  17147. }
  17148. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17149. {
  17150. auto req = "POST /test HTTP/1.1\r\n"
  17151. "Host: localhost\r\n"
  17152. "Content-Length: 5\r\n"
  17153. "Transfer-Encoding: gzip, chunked\r\n"
  17154. "Connection: close\r\n"
  17155. "\r\n"
  17156. "hello";
  17157. std::string response;
  17158. ASSERT_TRUE(send_request(1, req, &response));
  17159. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17160. response.substr(0, response.find("\r\n")));
  17161. }
  17162. }
  17163. // Regression for issue #2450: a DELETE without Content-Length on a
  17164. // keep-alive connection must not let the post-response drain consume the
  17165. // next request's bytes.
  17166. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17167. Server svr;
  17168. std::atomic<int> delete_count(0);
  17169. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17170. delete_count++;
  17171. res.status = StatusCode::NoContent_204;
  17172. });
  17173. auto port = svr.bind_to_any_port(HOST);
  17174. thread t = thread([&] { svr.listen_after_bind(); });
  17175. auto se = detail::scope_exit([&] {
  17176. svr.stop();
  17177. t.join();
  17178. });
  17179. svr.wait_until_ready();
  17180. auto error = Error::Success;
  17181. auto sock = detail::create_client_socket(
  17182. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17183. /*connection_timeout_sec=*/2, 0,
  17184. /*read_timeout_sec=*/2, 0,
  17185. /*write_timeout_sec=*/2, 0, std::string(), error);
  17186. ASSERT_NE(INVALID_SOCKET, sock);
  17187. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17188. auto send_request_and_read_response = [&](const std::string &req,
  17189. std::string &out) -> bool {
  17190. auto sent = send(sock, req.data(), req.size(), 0);
  17191. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17192. char buf[4096];
  17193. for (;;) {
  17194. auto n = recv(sock, buf, sizeof(buf), 0);
  17195. if (n <= 0) { return !out.empty(); }
  17196. out.append(buf, static_cast<size_t>(n));
  17197. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17198. }
  17199. };
  17200. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17201. "Host: localhost\r\n"
  17202. "\r\n";
  17203. std::string resp1;
  17204. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17205. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17206. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17207. "Host: localhost\r\n"
  17208. "Connection: close\r\n"
  17209. "\r\n";
  17210. std::string resp2;
  17211. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17212. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17213. EXPECT_EQ(2, delete_count.load());
  17214. }
  17215. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17216. Server svr;
  17217. svr.Post("/ingest", [&](const Request &, Response &res,
  17218. const ContentReader &content_reader) {
  17219. auto consumed = content_reader([](const char *, size_t) { return false; });
  17220. EXPECT_FALSE(consumed);
  17221. res.status = StatusCode::Conflict_409;
  17222. res.set_header("Connection", "close");
  17223. });
  17224. auto port = svr.bind_to_any_port(HOST);
  17225. thread t = thread([&] { svr.listen_after_bind(); });
  17226. auto se = detail::scope_exit([&] {
  17227. svr.stop();
  17228. t.join();
  17229. });
  17230. svr.wait_until_ready();
  17231. auto error = Error::Success;
  17232. auto sock = detail::create_client_socket(
  17233. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17234. /*connection_timeout_sec=*/2, 0,
  17235. /*read_timeout_sec=*/1, 0,
  17236. /*write_timeout_sec=*/2, 0, std::string(), error);
  17237. ASSERT_NE(INVALID_SOCKET, sock);
  17238. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17239. std::string request = "POST /ingest HTTP/1.1\r\n"
  17240. "Host: localhost\r\n"
  17241. "Transfer-Encoding: chunked\r\n"
  17242. "\r\n"
  17243. "4\r\n"
  17244. "data\r\n";
  17245. auto sent = send(sock, request.data(), request.size(), 0);
  17246. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17247. std::string response;
  17248. ssize_t received = 0;
  17249. do {
  17250. char buf[4096];
  17251. received = recv(sock, buf, sizeof(buf), 0);
  17252. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17253. } while (received > 0);
  17254. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17255. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17256. EXPECT_EQ(0, received);
  17257. }
  17258. namespace no_proxy_test {
  17259. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17260. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17261. // calling listen().
  17262. class ScopedServer {
  17263. public:
  17264. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17265. ~ScopedServer() {
  17266. svr_.stop();
  17267. if (th_.joinable()) { th_.join(); }
  17268. }
  17269. Server &svr() { return svr_; }
  17270. int port() const { return port_; }
  17271. void listen() {
  17272. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17273. svr_.wait_until_ready();
  17274. }
  17275. private:
  17276. Server svr_;
  17277. std::thread th_;
  17278. int port_ = 0;
  17279. };
  17280. class ProxyAndTargetServers {
  17281. public:
  17282. ProxyAndTargetServers() {
  17283. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17284. proxy_hits_++;
  17285. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17286. res.set_content("via-proxy", "text/plain");
  17287. });
  17288. target_.Get(".*", [this](const Request &req, Response &res) {
  17289. target_hits_++;
  17290. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17291. res.set_content("direct", "text/plain");
  17292. });
  17293. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17294. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17295. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17296. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17297. proxy_mock_.wait_until_ready();
  17298. target_.wait_until_ready();
  17299. }
  17300. ~ProxyAndTargetServers() {
  17301. proxy_mock_.stop();
  17302. target_.stop();
  17303. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17304. if (target_thread_.joinable()) { target_thread_.join(); }
  17305. }
  17306. Server &proxy_mock() { return proxy_mock_; }
  17307. Server &target() { return target_; }
  17308. int proxy_port() const { return proxy_port_; }
  17309. int target_port() const { return target_port_; }
  17310. int proxy_hits() const { return proxy_hits_.load(); }
  17311. int target_hits() const { return target_hits_.load(); }
  17312. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17313. void reset_counters() {
  17314. proxy_hits_ = 0;
  17315. target_hits_ = 0;
  17316. last_had_proxy_authz_ = false;
  17317. }
  17318. private:
  17319. Server proxy_mock_;
  17320. Server target_;
  17321. std::thread proxy_thread_;
  17322. std::thread target_thread_;
  17323. int proxy_port_ = 0;
  17324. int target_port_ = 0;
  17325. std::atomic<int> proxy_hits_{0};
  17326. std::atomic<int> target_hits_{0};
  17327. std::atomic<bool> last_had_proxy_authz_{false};
  17328. };
  17329. inline std::unique_ptr<Client> make_client(const std::string &host,
  17330. ProxyAndTargetServers &s) {
  17331. auto cli = detail::make_unique<Client>(host, s.target_port());
  17332. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17333. cli->set_proxy("127.0.0.1", s.proxy_port());
  17334. return cli;
  17335. }
  17336. } // namespace no_proxy_test
  17337. using no_proxy_test::make_client;
  17338. using no_proxy_test::ProxyAndTargetServers;
  17339. TEST(NoProxyTest, ExactHostnameBypasses) {
  17340. ProxyAndTargetServers s;
  17341. auto cli = make_client("example.com", s);
  17342. cli->set_no_proxy({"example.com"});
  17343. auto res = cli->Get("/");
  17344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17345. EXPECT_EQ(0, s.proxy_hits());
  17346. EXPECT_EQ(1, s.target_hits());
  17347. }
  17348. TEST(NoProxyTest, SubdomainBypasses) {
  17349. ProxyAndTargetServers s;
  17350. auto cli = make_client("foo.example.com", s);
  17351. cli->set_no_proxy({"example.com"});
  17352. auto res = cli->Get("/");
  17353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17354. EXPECT_EQ(0, s.proxy_hits());
  17355. EXPECT_EQ(1, s.target_hits());
  17356. }
  17357. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17358. // Regression guard: "evilexample.com" must not be considered a subdomain
  17359. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17360. // check would let traffic bypass the proxy and leak credentials direct
  17361. // to the attacker host.
  17362. ProxyAndTargetServers s;
  17363. auto cli = make_client("evilexample.com", s);
  17364. cli->set_no_proxy({"example.com"});
  17365. auto res = cli->Get("/");
  17366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17367. EXPECT_GE(s.proxy_hits(), 1);
  17368. EXPECT_EQ(0, s.target_hits());
  17369. }
  17370. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17371. ProxyAndTargetServers s;
  17372. auto cli = make_client("example.com.evil.com", s);
  17373. cli->set_no_proxy({"example.com"});
  17374. auto res = cli->Get("/");
  17375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17376. EXPECT_GE(s.proxy_hits(), 1);
  17377. EXPECT_EQ(0, s.target_hits());
  17378. }
  17379. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17380. ProxyAndTargetServers s;
  17381. auto cli = make_client("example.com", s);
  17382. cli->set_no_proxy({".example.com"});
  17383. auto res = cli->Get("/");
  17384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17385. EXPECT_EQ(0, s.proxy_hits());
  17386. EXPECT_EQ(1, s.target_hits());
  17387. }
  17388. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17389. ProxyAndTargetServers s;
  17390. auto cli = make_client("Example.COM", s);
  17391. cli->set_no_proxy({"EXAMPLE.com"});
  17392. auto res = cli->Get("/");
  17393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17394. EXPECT_EQ(0, s.proxy_hits());
  17395. EXPECT_EQ(1, s.target_hits());
  17396. }
  17397. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17398. ProxyAndTargetServers s;
  17399. auto cli = make_client("example.com.", s);
  17400. cli->set_no_proxy({"example.com"});
  17401. auto res = cli->Get("/");
  17402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17403. EXPECT_EQ(0, s.proxy_hits());
  17404. EXPECT_EQ(1, s.target_hits());
  17405. }
  17406. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17407. // Trailing dots must be normalized on BOTH sides — host and entry.
  17408. // An implementation that only strips the host-side trailing dot would
  17409. // fail to match host "example.com" against entry "example.com." because
  17410. // a literal substring search would compare 11 chars against 12.
  17411. ProxyAndTargetServers s;
  17412. auto cli = make_client("example.com", s);
  17413. cli->set_no_proxy({"example.com."});
  17414. auto res = cli->Get("/");
  17415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17416. EXPECT_EQ(0, s.proxy_hits());
  17417. EXPECT_EQ(1, s.target_hits());
  17418. }
  17419. TEST(NoProxyTest, WildcardBypassesEverything) {
  17420. ProxyAndTargetServers s;
  17421. auto cli = make_client("anything.invalid.test", s);
  17422. cli->set_no_proxy({"*"});
  17423. auto res = cli->Get("/");
  17424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17425. EXPECT_EQ(0, s.proxy_hits());
  17426. EXPECT_EQ(1, s.target_hits());
  17427. }
  17428. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17429. ProxyAndTargetServers s;
  17430. Client cli("127.0.0.1", s.target_port());
  17431. cli.set_proxy("127.0.0.1", s.proxy_port());
  17432. cli.set_no_proxy({"127.0.0.1"});
  17433. auto res = cli.Get("/");
  17434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17435. EXPECT_EQ(0, s.proxy_hits());
  17436. EXPECT_EQ(1, s.target_hits());
  17437. }
  17438. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17439. ProxyAndTargetServers s;
  17440. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17441. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17442. cli.set_proxy("127.0.0.1", s.proxy_port());
  17443. cli.set_no_proxy({"::1"});
  17444. auto res = cli.Get("/");
  17445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17446. EXPECT_EQ(0, s.proxy_hits());
  17447. EXPECT_EQ(1, s.target_hits());
  17448. }
  17449. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17450. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17451. // must still be recognized as IPv6 for CIDR matching. Implementations
  17452. // that detect IPv6 only when the host begins with '[' would parse the
  17453. // host as a hostname and miss the match.
  17454. ProxyAndTargetServers s;
  17455. Client cli("fe80::1", s.target_port());
  17456. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17457. cli.set_proxy("127.0.0.1", s.proxy_port());
  17458. cli.set_no_proxy({"fe80::/10"});
  17459. auto res = cli.Get("/");
  17460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17461. EXPECT_EQ(0, s.proxy_hits());
  17462. EXPECT_EQ(1, s.target_hits());
  17463. }
  17464. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17465. ProxyAndTargetServers s;
  17466. Client cli("::1", s.target_port());
  17467. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17468. cli.set_proxy("127.0.0.1", s.proxy_port());
  17469. cli.set_no_proxy({"[::1]"});
  17470. auto res = cli.Get("/");
  17471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17472. EXPECT_EQ(0, s.proxy_hits());
  17473. EXPECT_EQ(1, s.target_hits());
  17474. }
  17475. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17476. ProxyAndTargetServers s;
  17477. Client cli("fe80::1", s.target_port());
  17478. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17479. cli.set_proxy("127.0.0.1", s.proxy_port());
  17480. cli.set_no_proxy({"[fe80::]/10"});
  17481. auto res = cli.Get("/");
  17482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17483. EXPECT_EQ(0, s.proxy_hits());
  17484. EXPECT_EQ(1, s.target_hits());
  17485. }
  17486. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17487. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17488. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17489. // tricks via address-family conversion.
  17490. ProxyAndTargetServers s;
  17491. Client cli("::ffff:127.0.0.1", s.target_port());
  17492. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17493. cli.set_proxy("127.0.0.1", s.proxy_port());
  17494. cli.set_no_proxy({"127.0.0.1"});
  17495. auto res = cli.Get("/");
  17496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17497. EXPECT_GE(s.proxy_hits(), 1);
  17498. EXPECT_EQ(0, s.target_hits());
  17499. }
  17500. TEST(NoProxyTest, IPv4CidrMatch) {
  17501. ProxyAndTargetServers s;
  17502. Client cli("127.0.0.1", s.target_port());
  17503. cli.set_proxy("127.0.0.1", s.proxy_port());
  17504. cli.set_no_proxy({"127.0.0.0/8"});
  17505. auto res = cli.Get("/");
  17506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17507. EXPECT_EQ(0, s.proxy_hits());
  17508. EXPECT_EQ(1, s.target_hits());
  17509. }
  17510. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17511. ProxyAndTargetServers s;
  17512. Client cli("127.0.0.1", s.target_port());
  17513. cli.set_proxy("127.0.0.1", s.proxy_port());
  17514. cli.set_no_proxy({"10.0.0.0/8"});
  17515. auto res = cli.Get("/");
  17516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17517. EXPECT_GE(s.proxy_hits(), 1);
  17518. EXPECT_EQ(0, s.target_hits());
  17519. }
  17520. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17521. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17522. // IPv4 target matches.
  17523. ProxyAndTargetServers s;
  17524. Client cli("127.0.0.1", s.target_port());
  17525. cli.set_proxy("127.0.0.1", s.proxy_port());
  17526. cli.set_no_proxy({"0.0.0.0/0"});
  17527. auto res = cli.Get("/");
  17528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17529. EXPECT_EQ(0, s.proxy_hits());
  17530. EXPECT_EQ(1, s.target_hits());
  17531. }
  17532. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17533. ProxyAndTargetServers s;
  17534. Client cli("127.0.0.1", s.target_port());
  17535. cli.set_proxy("127.0.0.1", s.proxy_port());
  17536. cli.set_no_proxy({"127.0.0.1"});
  17537. auto res = cli.Get("/");
  17538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17539. EXPECT_EQ(0, s.proxy_hits());
  17540. EXPECT_EQ(1, s.target_hits());
  17541. }
  17542. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17543. ProxyAndTargetServers s;
  17544. Client cli("127.0.0.1", s.target_port());
  17545. cli.set_proxy("127.0.0.1", s.proxy_port());
  17546. cli.set_no_proxy({"127.0.0.0/33"});
  17547. auto res = cli.Get("/");
  17548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17549. EXPECT_GE(s.proxy_hits(), 1);
  17550. EXPECT_EQ(0, s.target_hits());
  17551. }
  17552. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17553. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17554. ProxyAndTargetServers s;
  17555. Client cli("127.0.0.1", s.target_port());
  17556. cli.set_proxy("127.0.0.1", s.proxy_port());
  17557. cli.set_no_proxy({"127.0.0.1/"});
  17558. auto res = cli.Get("/");
  17559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17560. EXPECT_GE(s.proxy_hits(), 1);
  17561. EXPECT_EQ(0, s.target_hits());
  17562. }
  17563. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17564. ProxyAndTargetServers s;
  17565. auto cli = make_client("internal.corp", s);
  17566. cli->set_proxy_basic_auth("u", "p");
  17567. cli->set_no_proxy({"internal.corp"});
  17568. auto res = cli->Get("/");
  17569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17570. EXPECT_EQ(1, s.target_hits());
  17571. EXPECT_EQ(0, s.proxy_hits());
  17572. EXPECT_FALSE(s.last_had_proxy_authz())
  17573. << "Proxy-Authorization must not be sent direct to the target";
  17574. }
  17575. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17576. ProxyAndTargetServers s;
  17577. auto cli = make_client("public.example", s);
  17578. cli->set_proxy_basic_auth("u", "p");
  17579. cli->set_no_proxy({"internal.corp"}); // does not match
  17580. auto res = cli->Get("/");
  17581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17582. EXPECT_GE(s.proxy_hits(), 1);
  17583. EXPECT_TRUE(s.last_had_proxy_authz());
  17584. }
  17585. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17586. ProxyAndTargetServers s;
  17587. auto cli = make_client("anything.test", s);
  17588. auto res = cli->Get("/");
  17589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17590. EXPECT_GE(s.proxy_hits(), 1);
  17591. EXPECT_EQ(0, s.target_hits());
  17592. }
  17593. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17594. ProxyAndTargetServers s;
  17595. auto cli = make_client("example.com", s);
  17596. cli->set_no_proxy({"example.com:8080"});
  17597. auto res = cli->Get("/");
  17598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17599. EXPECT_GE(s.proxy_hits(), 1);
  17600. EXPECT_EQ(0, s.target_hits());
  17601. }
  17602. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17603. ProxyAndTargetServers s;
  17604. auto cli = make_client("anything.test", s);
  17605. cli->set_no_proxy({"", " ", "\t"});
  17606. auto res = cli->Get("/");
  17607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17608. EXPECT_GE(s.proxy_hits(), 1);
  17609. EXPECT_EQ(0, s.target_hits());
  17610. }
  17611. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17612. // An entry with leading/trailing whitespace must still match — env-style
  17613. // values are commonly pasted with stray spaces and an implementation
  17614. // that feeds the raw token directly to inet_pton would fail to match
  17615. // valid CIDRs because of the spaces.
  17616. ProxyAndTargetServers s;
  17617. Client cli("127.0.0.1", s.target_port());
  17618. cli.set_proxy("127.0.0.1", s.proxy_port());
  17619. cli.set_no_proxy({" 127.0.0.0/8 "});
  17620. auto res = cli.Get("/");
  17621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17622. EXPECT_EQ(0, s.proxy_hits());
  17623. EXPECT_EQ(1, s.target_hits());
  17624. }
  17625. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17626. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17627. // go direct and must NOT carry Proxy-Authorization.
  17628. std::atomic<int> proxy_hits{0};
  17629. std::atomic<int> target_hits{0};
  17630. std::atomic<bool> target_saw_authz{false};
  17631. no_proxy_test::ScopedServer proxy_mock, target;
  17632. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17633. proxy_hits++;
  17634. res.status = 302;
  17635. res.set_header("Location", "http://127.0.0.1:" +
  17636. std::to_string(target.port()) + "/landed");
  17637. });
  17638. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17639. target_hits++;
  17640. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17641. res.set_content("direct", "text/plain");
  17642. });
  17643. proxy_mock.listen();
  17644. target.listen();
  17645. Client cli("public.example", target.port());
  17646. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17647. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17648. cli.set_proxy_basic_auth("u", "p");
  17649. cli.set_no_proxy({"127.0.0.1"});
  17650. cli.set_follow_location(true);
  17651. auto res = cli.Get("/redir");
  17652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17653. EXPECT_GE(proxy_hits.load(), 1);
  17654. EXPECT_GE(target_hits.load(), 1);
  17655. EXPECT_FALSE(target_saw_authz.load());
  17656. }
  17657. #ifdef CPPHTTPLIB_SSL_ENABLED
  17658. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17659. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17660. // proxy creds would be sent to the (possibly hostile) origin.
  17661. std::atomic<int> target_hits{0};
  17662. std::atomic<bool> target_saw_proxy_authz{false};
  17663. no_proxy_test::ScopedServer target;
  17664. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17665. target_hits++;
  17666. if (req.has_header("Proxy-Authorization")) {
  17667. target_saw_proxy_authz = true;
  17668. }
  17669. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17670. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17671. "nonce=\"abc\", algorithm=MD5");
  17672. });
  17673. target.listen();
  17674. // The proxy address is set to the target's port: the bypass MUST kick in;
  17675. // if it doesn't, the test still routes "via proxy" to the same server and
  17676. // the Proxy-Authorization assertion below catches the leak.
  17677. Client cli("evil.example", target.port());
  17678. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17679. cli.set_proxy("127.0.0.1", target.port());
  17680. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17681. cli.set_no_proxy({"evil.example"});
  17682. auto res = cli.Get("/x");
  17683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17684. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17685. EXPECT_EQ(1, target_hits.load());
  17686. EXPECT_FALSE(target_saw_proxy_authz.load());
  17687. }
  17688. #endif
  17689. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17690. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17691. std::atomic<int> proxy_hits{0};
  17692. std::atomic<int> bypass_hits{0};
  17693. std::atomic<bool> proxy_saw_c_url{false};
  17694. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17695. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17696. proxy_hits++;
  17697. if (req.path.find("/start") != std::string::npos) {
  17698. res.status = 302;
  17699. res.set_header("Location", "http://127.0.0.1:" +
  17700. std::to_string(bypass_server.port()) +
  17701. "/middle");
  17702. return;
  17703. }
  17704. if (req.path.find("/end") != std::string::npos) {
  17705. proxy_saw_c_url = true;
  17706. res.set_content("c-via-proxy", "text/plain");
  17707. return;
  17708. }
  17709. res.set_content("unexpected", "text/plain");
  17710. });
  17711. // public.example's "advertised" port is arbitrary (the request never lands
  17712. // there — it goes through the proxy), but use a dynamic value to stay
  17713. // friendly with sharded parallel runs.
  17714. int public_port = bypass_server.port();
  17715. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17716. bypass_hits++;
  17717. res.status = 302;
  17718. res.set_header("Location", "http://public.example:" +
  17719. std::to_string(public_port) + "/end");
  17720. });
  17721. proxy_mock.listen();
  17722. bypass_server.listen();
  17723. Client cli("public.example", public_port);
  17724. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17725. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17726. cli.set_no_proxy({"127.0.0.1"});
  17727. cli.set_follow_location(true);
  17728. auto res = cli.Get("/start");
  17729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17730. EXPECT_EQ(StatusCode::OK_200, res->status);
  17731. EXPECT_EQ("c-via-proxy", res->body);
  17732. EXPECT_GE(proxy_hits.load(), 2);
  17733. EXPECT_GE(bypass_hits.load(), 1);
  17734. EXPECT_TRUE(proxy_saw_c_url.load());
  17735. }
  17736. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17737. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17738. // request reconnects to the correct endpoint.
  17739. std::atomic<int> proxy_hits{0};
  17740. std::atomic<int> target_hits{0};
  17741. no_proxy_test::ScopedServer proxy_mock, target;
  17742. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17743. proxy_hits++;
  17744. res.set_content("via-proxy", "text/plain");
  17745. });
  17746. target.svr().Get(".*", [&](const Request &, Response &res) {
  17747. target_hits++;
  17748. res.set_content("direct", "text/plain");
  17749. });
  17750. proxy_mock.listen();
  17751. target.listen();
  17752. Client cli("public.example", target.port());
  17753. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17754. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17755. cli.set_keep_alive(true);
  17756. auto res1 = cli.Get("/a");
  17757. ASSERT_TRUE(res1);
  17758. EXPECT_EQ("via-proxy", res1->body);
  17759. EXPECT_EQ(1, proxy_hits.load());
  17760. EXPECT_EQ(0, target_hits.load());
  17761. cli.set_no_proxy({"public.example"});
  17762. auto res2 = cli.Get("/b");
  17763. ASSERT_TRUE(res2);
  17764. EXPECT_EQ("direct", res2->body);
  17765. EXPECT_EQ(1, proxy_hits.load());
  17766. EXPECT_EQ(1, target_hits.load());
  17767. }
  17768. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17769. namespace proxy_tunnel_test {
  17770. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17771. class ScopedSSLServer {
  17772. public:
  17773. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17774. port_ = svr_.bind_to_any_port("127.0.0.1");
  17775. }
  17776. ~ScopedSSLServer() {
  17777. svr_.stop();
  17778. if (th_.joinable()) { th_.join(); }
  17779. }
  17780. SSLServer &svr() { return svr_; }
  17781. int port() const { return port_; }
  17782. void listen() {
  17783. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17784. svr_.wait_until_ready();
  17785. }
  17786. private:
  17787. SSLServer svr_;
  17788. std::thread th_;
  17789. int port_ = 0;
  17790. };
  17791. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17792. class ScopedConnectProxy {
  17793. public:
  17794. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17795. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17796. if (listen_fd_ < 0) { return; }
  17797. int yes = 1;
  17798. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17799. sockaddr_in a{};
  17800. a.sin_family = AF_INET;
  17801. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17802. a.sin_port = 0;
  17803. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17804. return;
  17805. }
  17806. socklen_t alen = sizeof(a);
  17807. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17808. 0) {
  17809. return;
  17810. }
  17811. port_ = ntohs(a.sin_port);
  17812. if (::listen(listen_fd_, 1) != 0) { return; }
  17813. th_ = std::thread([this] { run(); });
  17814. }
  17815. ~ScopedConnectProxy() {
  17816. stop_ = true;
  17817. if (listen_fd_ >= 0) {
  17818. ::shutdown(listen_fd_, SHUT_RDWR);
  17819. ::close(listen_fd_);
  17820. }
  17821. if (th_.joinable()) { th_.join(); }
  17822. }
  17823. int port() const { return port_; }
  17824. int connect_hits() const { return connect_hits_.load(); }
  17825. private:
  17826. void run() {
  17827. while (!stop_.load()) {
  17828. fd_set rfds;
  17829. FD_ZERO(&rfds);
  17830. FD_SET(listen_fd_, &rfds);
  17831. timeval tv{0, 100 * 1000};
  17832. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17833. if (sel <= 0) { continue; }
  17834. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17835. if (client_fd < 0) { continue; }
  17836. std::string req;
  17837. char buf[2048];
  17838. while (req.find("\r\n\r\n") == std::string::npos) {
  17839. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17840. if (n <= 0) { break; }
  17841. req.append(buf, static_cast<size_t>(n));
  17842. }
  17843. if (req.compare(0, 7, "CONNECT") != 0) {
  17844. ::close(client_fd);
  17845. continue;
  17846. }
  17847. connect_hits_++;
  17848. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17849. ::send(client_fd, ok, std::strlen(ok), 0);
  17850. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17851. sockaddr_in o{};
  17852. o.sin_family = AF_INET;
  17853. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17854. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17855. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17856. 0) {
  17857. ::close(client_fd);
  17858. ::close(origin_fd);
  17859. continue;
  17860. }
  17861. auto forward = [](int from, int to) {
  17862. char b[8192];
  17863. for (;;) {
  17864. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17865. if (n <= 0) { break; }
  17866. ssize_t off = 0;
  17867. while (off < n) {
  17868. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17869. if (s <= 0) {
  17870. off = n;
  17871. break;
  17872. }
  17873. off += s;
  17874. }
  17875. }
  17876. ::shutdown(to, SHUT_WR);
  17877. };
  17878. std::thread t1([&] { forward(client_fd, origin_fd); });
  17879. std::thread t2([&] { forward(origin_fd, client_fd); });
  17880. t1.join();
  17881. t2.join();
  17882. ::close(client_fd);
  17883. ::close(origin_fd);
  17884. }
  17885. }
  17886. int forward_port_ = -1;
  17887. int listen_fd_ = -1;
  17888. int port_ = 0;
  17889. std::thread th_;
  17890. std::atomic<bool> stop_{false};
  17891. std::atomic<int> connect_hits_{0};
  17892. };
  17893. } // namespace proxy_tunnel_test
  17894. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17895. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17896. // retry; otherwise proxy creds would be sent to the origin.
  17897. std::atomic<int> origin_hits{0};
  17898. std::atomic<bool> origin_saw_proxy_authz{false};
  17899. proxy_tunnel_test::ScopedSSLServer origin;
  17900. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17901. origin_hits++;
  17902. if (req.has_header("Proxy-Authorization")) {
  17903. origin_saw_proxy_authz = true;
  17904. }
  17905. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17906. res.set_header("Proxy-Authenticate",
  17907. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17908. "algorithm=MD5");
  17909. });
  17910. origin.listen();
  17911. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17912. ASSERT_NE(0, proxy.port());
  17913. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  17914. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  17915. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  17916. // and answer with its own status, making this test flaky.
  17917. SSLClient cli("127.0.0.1", origin.port());
  17918. cli.enable_server_certificate_verification(false);
  17919. cli.set_proxy("127.0.0.1", proxy.port());
  17920. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17921. auto res = cli.Get("/x");
  17922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17923. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17924. EXPECT_EQ(1, origin_hits.load());
  17925. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17926. EXPECT_EQ(1, proxy.connect_hits());
  17927. }
  17928. #endif