test.cc 843 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098
  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. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Valid cases should still work
  898. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  899. EXPECT_EQ(result.size(), 1U);
  900. EXPECT_EQ(result[0], "*/*");
  901. EXPECT_TRUE(detail::parse_accept_header("*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*");
  904. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "text/*");
  907. }
  908. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  909. // elements, so a leading, trailing or doubled comma is a legal Accept value
  910. // and must not be answered with 400 Bad Request.
  911. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  912. struct {
  913. const char *value;
  914. std::vector<std::string> expected;
  915. } cases[] = {
  916. {",application/json", {"application/json"}},
  917. {"text/html,", {"text/html"}},
  918. {"text/html,,*/*", {"text/html", "*/*"}},
  919. // An empty element may be spelled with whitespace in it
  920. {"text/html, , application/json", {"text/html", "application/json"}},
  921. // Nothing but empty elements is an empty list, which means the same
  922. // thing as no Accept header at all
  923. {",,,", {}},
  924. // Quality values still apply across ignored empty elements
  925. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  926. };
  927. for (const auto &c : cases) {
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  930. << "value: " << c.value;
  931. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  932. }
  933. // An invalid entry is still rejected when empty elements surround it
  934. std::vector<std::string> result;
  935. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  936. }
  937. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  938. Server svr;
  939. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  940. EXPECT_EQ(req.accept_content_types.size(), 3U);
  941. EXPECT_EQ(req.accept_content_types[0], "application/json");
  942. EXPECT_EQ(req.accept_content_types[1], "text/html");
  943. EXPECT_EQ(req.accept_content_types[2], "*/*");
  944. res.set_content("ok", "text/plain");
  945. });
  946. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  947. EXPECT_TRUE(false);
  948. res.set_content("bad request", "text/plain");
  949. });
  950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  951. auto se = detail::scope_exit([&] {
  952. svr.stop();
  953. listen_thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. });
  956. svr.wait_until_ready();
  957. Client cli("localhost", PORT);
  958. {
  959. auto res = cli.Get(
  960. "/accept_ok",
  961. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  963. EXPECT_EQ(StatusCode::OK_200, res->status);
  964. }
  965. {
  966. auto res = cli.Get("/accept_bad_request",
  967. Headers{{"Accept", "text/html;q=abc,application/json"}});
  968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  970. }
  971. }
  972. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  973. Server svr;
  974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  975. res.set_content("ok", "text/plain");
  976. });
  977. std::atomic<int> start_count{0};
  978. std::atomic<bool> running_when_called{false};
  979. svr.set_start_handler([&]() {
  980. running_when_called = svr.is_running();
  981. start_count++;
  982. });
  983. auto port = svr.bind_to_any_port(HOST);
  984. std::thread t([&]() { svr.listen_after_bind(); });
  985. auto se = detail::scope_exit([&] {
  986. svr.stop();
  987. t.join();
  988. ASSERT_FALSE(svr.is_running());
  989. });
  990. svr.wait_until_ready();
  991. // A successful request proves the accept loop is running, which the start
  992. // handler precedes; so by now the handler must have run exactly once.
  993. Client cli(HOST, port);
  994. cli.set_connection_timeout(std::chrono::seconds(5));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  997. EXPECT_EQ(StatusCode::OK_200, res->status);
  998. EXPECT_EQ(1, start_count.load());
  999. EXPECT_TRUE(running_when_called.load());
  1000. }
  1001. TEST(DivideTest, DivideStringTests) {
  1002. auto divide = [](const std::string &str, char d) {
  1003. std::string lhs;
  1004. std::string rhs;
  1005. detail::divide(str, d,
  1006. [&](const char *lhs_data, std::size_t lhs_size,
  1007. const char *rhs_data, std::size_t rhs_size) {
  1008. lhs.assign(lhs_data, lhs_size);
  1009. rhs.assign(rhs_data, rhs_size);
  1010. });
  1011. return std::make_pair(std::move(lhs), std::move(rhs));
  1012. };
  1013. {
  1014. const auto res = divide("", '=');
  1015. EXPECT_EQ(res.first, "");
  1016. EXPECT_EQ(res.second, "");
  1017. }
  1018. {
  1019. const auto res = divide("=", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide(" ", '=');
  1025. EXPECT_EQ(res.first, " ");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide("a", '=');
  1030. EXPECT_EQ(res.first, "a");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a=", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("=b", '=');
  1040. EXPECT_EQ(res.first, "");
  1041. EXPECT_EQ(res.second, "b");
  1042. }
  1043. {
  1044. const auto res = divide("a=b", '=');
  1045. EXPECT_EQ(res.first, "a");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b=", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b=");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=c", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=c");
  1057. }
  1058. }
  1059. TEST(SplitTest, ParseQueryString) {
  1060. string s = "key1=val1&key2=val2&key3=val3";
  1061. Params dic;
  1062. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1063. [&](const char *b, const char *e) {
  1064. string key, val;
  1065. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1066. if (key.empty()) {
  1067. key.assign(b2, e2);
  1068. } else {
  1069. val.assign(b2, e2);
  1070. }
  1071. });
  1072. dic.emplace(key, val);
  1073. });
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. TEST(SplitTest, ParseInvalidQueryTests) {
  1079. {
  1080. string s = " ";
  1081. Params dict;
  1082. detail::parse_query_text(s, dict);
  1083. EXPECT_TRUE(dict.empty());
  1084. }
  1085. {
  1086. string s = " = =";
  1087. Params dict;
  1088. detail::parse_query_text(s, dict);
  1089. EXPECT_TRUE(dict.empty());
  1090. }
  1091. }
  1092. TEST(ParseQueryTest, ParseQueryString) {
  1093. {
  1094. std::string s = "key1=val1&key2=val2&key3=val3";
  1095. Params dic;
  1096. detail::parse_query_text(s, dic);
  1097. EXPECT_EQ("val1", dic.find("key1")->second);
  1098. EXPECT_EQ("val2", dic.find("key2")->second);
  1099. EXPECT_EQ("val3", dic.find("key3")->second);
  1100. }
  1101. {
  1102. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1103. Params dic;
  1104. detail::parse_query_text(s, dic);
  1105. EXPECT_EQ("", dic.find("key1")->second);
  1106. EXPECT_EQ("val1", dic.find("key2")->second);
  1107. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1108. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1109. }
  1110. }
  1111. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1112. Params dic;
  1113. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1114. dic.emplace("key1", "val1");
  1115. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1116. dic.emplace("key2", "val2");
  1117. dic.emplace("key3", "val3");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1119. }
  1120. // Joins every entry of a Headers or Params into "key=value " so a whole
  1121. // traversal can be compared in one assertion. Both are instantiations of the
  1122. // same insertion-ordered container, so one helper serves both.
  1123. template <typename Map> static std::string entries_to_string(const Map &m) {
  1124. std::string s;
  1125. for (const auto &entry : m) {
  1126. s += entry.first + "=" + entry.second + " ";
  1127. }
  1128. return s;
  1129. }
  1130. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1131. // Params used to be a std::multimap, which sorted by name and handed the
  1132. // caller's query back alphabetised. A client signing its query string could
  1133. // not reproduce the order it asked for.
  1134. Params dic;
  1135. dic.emplace("zulu", "1");
  1136. dic.emplace("alpha", "2");
  1137. dic.emplace("mike", "3");
  1138. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1139. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1140. }
  1141. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1142. Params dic;
  1143. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1144. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1145. }
  1146. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1147. Request req;
  1148. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1149. req.params);
  1150. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1151. EXPECT_EQ("first", req.get_param_value("tag"));
  1152. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1153. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1154. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1155. EXPECT_EQ("", req.get_param_value("tag", 3));
  1156. }
  1157. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1158. // Params shares its container with Headers, which matches field names
  1159. // case-insensitively. Parameter names must not pick that up.
  1160. Params dic;
  1161. dic.emplace("Key", "upper");
  1162. dic.emplace("key", "lower");
  1163. EXPECT_EQ(2U, dic.size());
  1164. EXPECT_EQ(1U, dic.count("Key"));
  1165. EXPECT_EQ(1U, dic.count("key"));
  1166. EXPECT_EQ("upper", dic.find("Key")->second);
  1167. EXPECT_EQ("lower", dic.find("key")->second);
  1168. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1169. }
  1170. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1171. Server svr;
  1172. std::string order;
  1173. svr.Get("/order", [&](const Request &req, Response &res) {
  1174. order = entries_to_string(req.params);
  1175. res.set_content("ok", "text/plain");
  1176. });
  1177. auto port = svr.bind_to_any_port(HOST);
  1178. thread t = thread([&] { svr.listen_after_bind(); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. t.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. svr.wait_until_ready();
  1185. Client cli(HOST, port);
  1186. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1189. }
  1190. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1191. Server svr;
  1192. std::string field_order, file_order;
  1193. svr.Post("/order", [&](const Request &req, Response &res) {
  1194. for (const auto &field : req.form.fields) {
  1195. field_order += field.first + "=" + field.second.content + " ";
  1196. }
  1197. for (const auto &file : req.form.files) {
  1198. file_order += file.first + "=" + file.second.filename + " ";
  1199. }
  1200. res.set_content("ok", "text/plain");
  1201. });
  1202. auto port = svr.bind_to_any_port(HOST);
  1203. thread t = thread([&] { svr.listen_after_bind(); });
  1204. auto se = detail::scope_exit([&] {
  1205. svr.stop();
  1206. t.join();
  1207. ASSERT_FALSE(svr.is_running());
  1208. });
  1209. svr.wait_until_ready();
  1210. UploadFormDataItems items = {
  1211. {"zulu", "1", "", ""},
  1212. {"alpha", "2", "", ""},
  1213. {"mike", "3", "", ""},
  1214. {"zebra", "z", "z.txt", "text/plain"},
  1215. {"apple", "a", "a.txt", "text/plain"},
  1216. };
  1217. Client cli(HOST, port);
  1218. auto res = cli.Post("/order", items);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1221. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1222. }
  1223. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1224. Server svr;
  1225. std::vector<std::string> values;
  1226. std::string first, second, out_of_range, order;
  1227. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1228. values = req.form.get_fields("tag");
  1229. first = req.form.get_field("tag", 0);
  1230. second = req.form.get_field("tag", 1);
  1231. out_of_range = req.form.get_field("tag", 2);
  1232. for (const auto &field : req.form.fields) {
  1233. order += field.first + "=" + field.second.content + " ";
  1234. }
  1235. res.set_content("ok", "text/plain");
  1236. });
  1237. auto port = svr.bind_to_any_port(HOST);
  1238. thread t = thread([&] { svr.listen_after_bind(); });
  1239. auto se = detail::scope_exit([&] {
  1240. svr.stop();
  1241. t.join();
  1242. ASSERT_FALSE(svr.is_running());
  1243. });
  1244. svr.wait_until_ready();
  1245. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1246. // not adjacent in the container.
  1247. UploadFormDataItems items = {
  1248. {"tag", "first", "", ""},
  1249. {"other", "x", "", ""},
  1250. {"tag", "second", "", ""},
  1251. };
  1252. Client cli(HOST, port);
  1253. auto res = cli.Post("/repeated", items);
  1254. ASSERT_TRUE(res);
  1255. ASSERT_EQ(2U, values.size());
  1256. EXPECT_EQ("first", values[0]);
  1257. EXPECT_EQ("second", values[1]);
  1258. EXPECT_EQ("first", first);
  1259. EXPECT_EQ("second", second);
  1260. // std::multimap already kept entries sharing a name in insertion order, so
  1261. // everything above passes without this change too. The whole traversal is
  1262. // what tells the two apart: sorting by name would hoist "other" to the front
  1263. // and the two "tag" parts would end up adjacent.
  1264. EXPECT_EQ("tag=first other=x tag=second ", order);
  1265. // Advancing past the last entry of a name used to run off the container;
  1266. // the container's saturating increment makes it return the default instead.
  1267. EXPECT_EQ("", out_of_range);
  1268. }
  1269. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1270. // Server::read_content() keeps a FormFields::iterator alive across the
  1271. // content callbacks that fill the part it points at. The container is
  1272. // vector-backed, so a later emplace can reallocate and invalidate an older
  1273. // iterator; 64 parts grow the vector through seven reallocations, which
  1274. // checks that every part's content still lands in its own entry.
  1275. const size_t part_count = 64;
  1276. // One formula for both the parts sent and the values expected back, so the
  1277. // two cannot drift apart.
  1278. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1279. auto content_of = [](size_t i) {
  1280. return std::string(64, static_cast<char>('a' + (i % 26)));
  1281. };
  1282. Server svr;
  1283. std::vector<std::pair<std::string, std::string>> received;
  1284. svr.Post("/many", [&](const Request &req, Response &res) {
  1285. for (const auto &field : req.form.fields) {
  1286. received.emplace_back(field.first, field.second.content);
  1287. }
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. auto port = svr.bind_to_any_port(HOST);
  1291. thread t = thread([&] { svr.listen_after_bind(); });
  1292. auto se = detail::scope_exit([&] {
  1293. svr.stop();
  1294. t.join();
  1295. ASSERT_FALSE(svr.is_running());
  1296. });
  1297. svr.wait_until_ready();
  1298. UploadFormDataItems items;
  1299. for (size_t i = 0; i < part_count; i++) {
  1300. items.push_back({name_of(i), content_of(i), "", ""});
  1301. }
  1302. Client cli(HOST, port);
  1303. auto res = cli.Post("/many", items);
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(part_count, received.size());
  1306. for (size_t i = 0; i < part_count; i++) {
  1307. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1308. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1309. }
  1310. }
  1311. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1312. string content_type = "multipart/form-data; boundary=something";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "something");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1319. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1320. string boundary;
  1321. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1322. EXPECT_TRUE(ret);
  1323. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1324. }
  1325. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1326. string content_type =
  1327. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1328. string boundary;
  1329. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1330. EXPECT_TRUE(ret);
  1331. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1334. string content_type =
  1335. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1336. string boundary;
  1337. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1338. EXPECT_TRUE(ret);
  1339. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1340. }
  1341. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1342. const string boundary(70, 'a');
  1343. string content_type = "multipart/form-data; boundary=" + boundary;
  1344. string parsed;
  1345. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1346. EXPECT_TRUE(ret);
  1347. EXPECT_EQ(parsed, boundary);
  1348. }
  1349. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1350. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1351. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1352. string parsed;
  1353. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1354. EXPECT_FALSE(ret);
  1355. }
  1356. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1357. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1358. // is 72 characters on the wire and still valid.
  1359. const string boundary(70, 'a');
  1360. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1361. string parsed;
  1362. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1363. EXPECT_EQ(parsed, boundary);
  1364. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1365. parsed.clear();
  1366. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1367. }
  1368. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1369. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1370. // The parameter parser must not treat that '=' as the key/value separator.
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1373. "charset=UTF-8";
  1374. string parsed;
  1375. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1376. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1379. // A ';' inside the quoted-string is part of the value, not a parameter
  1380. // separator, so it must not truncate the boundary.
  1381. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1382. string parsed;
  1383. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1384. EXPECT_EQ(parsed, "a;b");
  1385. }
  1386. TEST(ParseDispositionParamsTest, QuotedValues) {
  1387. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1388. // ';' and '=' are ordinary characters inside one.
  1389. struct {
  1390. const char *value;
  1391. std::vector<std::pair<const char *, const char *>> expected;
  1392. } cases[] = {
  1393. {"name=\"file1\"; filename=\"a.txt\"",
  1394. {{"name", "file1"}, {"filename", "a.txt"}}},
  1395. // Whitespace around '=' and ';' is still trimmed
  1396. {"name=\"file2\" ;filename = \"a.html\"",
  1397. {{"name", "file2"}, {"filename", "a.html"}}},
  1398. // '=' inside the value used to leave only the text after the last one
  1399. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1400. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1401. {"name=\"x=y\"", {{"name", "x=y"}}},
  1402. // ';' inside the value used to truncate the pair and leave a bogus one
  1403. {"name=\"file3\"; filename=\"a;b.txt\"",
  1404. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1405. // An unquoted value keeps working, and so does filename*
  1406. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1407. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1408. // A parameter with no key is dropped rather than turned into one whose
  1409. // key is the value
  1410. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1411. };
  1412. for (const auto &c : cases) {
  1413. Params params;
  1414. detail::parse_disposition_params(c.value, params);
  1415. for (const auto &kv : c.expected) {
  1416. auto it = params.find(kv.first);
  1417. ASSERT_NE(it, params.end())
  1418. << "value: " << c.value << ", key: " << kv.first;
  1419. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1420. }
  1421. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1422. }
  1423. }
  1424. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1425. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1426. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1427. Server svr;
  1428. std::string field_value, file_name, file_filename;
  1429. bool has_field = false, has_file = false;
  1430. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1431. has_field = req.form.has_field("x=y");
  1432. field_value = req.form.get_field("x=y");
  1433. has_file = req.form.has_file("file1");
  1434. const auto &file = req.form.get_file("file1");
  1435. file_name = file.name;
  1436. file_filename = file.filename;
  1437. res.set_content("ok", "text/plain");
  1438. });
  1439. auto port = svr.bind_to_any_port(HOST);
  1440. thread t = thread([&] { svr.listen_after_bind(); });
  1441. auto se = detail::scope_exit([&] {
  1442. svr.stop();
  1443. t.join();
  1444. ASSERT_FALSE(svr.is_running());
  1445. });
  1446. svr.wait_until_ready();
  1447. UploadFormDataItems items = {
  1448. {"x=y", "field-value", "", ""},
  1449. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1450. };
  1451. Client cli(HOST, port);
  1452. auto res = cli.Post("/quoted", items);
  1453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1454. ASSERT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_TRUE(has_field);
  1456. EXPECT_EQ("field-value", field_value);
  1457. EXPECT_TRUE(has_file);
  1458. EXPECT_EQ("file1", file_name);
  1459. EXPECT_EQ("a;b=report.pdf", file_filename);
  1460. }
  1461. TEST(GetHeaderValueTest, DefaultValue) {
  1462. Headers headers = {{"Dummy", "Dummy"}};
  1463. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1464. EXPECT_STREQ("text/plain", val);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValueInt) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1469. EXPECT_EQ(100ull, val);
  1470. }
  1471. TEST(GetHeaderValueTest, RegularValue) {
  1472. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1474. EXPECT_STREQ("text/html", val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, SetContent) {
  1482. Response res;
  1483. res.set_content("html", "text/html");
  1484. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1485. res.set_content("text", "text/plain");
  1486. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1487. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1488. }
  1489. TEST(GetHeaderValueTest, RegularValueInt) {
  1490. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1491. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1492. EXPECT_EQ(100ull, val);
  1493. }
  1494. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1495. Headers headers = {{"Content-Length", "x"}};
  1496. auto is_invalid_value = false;
  1497. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1498. is_invalid_value);
  1499. EXPECT_EQ(0ull, val);
  1500. EXPECT_TRUE(is_invalid_value);
  1501. }
  1502. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1503. // An all-digit value that overflows size_t must be reported as invalid, not
  1504. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1505. // a large length to a small one on 32-bit builds, leaving the framing length
  1506. // wrong while is_invalid_value stayed false.
  1507. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1508. auto is_invalid_value = false;
  1509. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1510. is_invalid_value);
  1511. EXPECT_TRUE(is_invalid_value);
  1512. // A well-formed length is unaffected.
  1513. Headers ok = {{"Content-Length", "1234"}};
  1514. is_invalid_value = false;
  1515. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1516. is_invalid_value);
  1517. EXPECT_EQ(1234ull, val);
  1518. EXPECT_FALSE(is_invalid_value);
  1519. }
  1520. TEST(GetHeaderValueTest, Range) {
  1521. {
  1522. Headers headers = {make_range_header({{1, -1}})};
  1523. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1524. EXPECT_STREQ("bytes=1-", val);
  1525. }
  1526. {
  1527. Headers headers = {make_range_header({{-1, 1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=-1", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{1, 10}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=1-10", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10, 100-", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=0-0, -1", val);
  1550. }
  1551. }
  1552. TEST(BearerTokenAuthTest, SchemeValidation) {
  1553. // A value shorter than "Bearer " must not throw from the fixed-length
  1554. // substr, and a non-Bearer scheme must not be reported as a token.
  1555. struct {
  1556. const char *value;
  1557. const char *expected;
  1558. } cases[] = {
  1559. {"x", ""},
  1560. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1561. {"Bearer abc123", "abc123"},
  1562. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1563. };
  1564. for (const auto &c : cases) {
  1565. Request req;
  1566. req.set_header("Authorization", c.value);
  1567. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1568. }
  1569. }
  1570. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1571. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1572. // to depend on the standard library (libstdc++ handed back duplicates in
  1573. // reverse insertion order, libc++ in insertion order).
  1574. Request req;
  1575. req.set_header("Accept-Encoding", "gzip");
  1576. req.set_header("Accept-Encoding", "deflate");
  1577. req.set_header("Accept-Encoding", "br");
  1578. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1579. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1580. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1581. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1582. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1583. }
  1584. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1585. Request req;
  1586. req.set_header("X-Test", "only");
  1587. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1588. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1589. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1590. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1591. }
  1592. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1593. Headers headers;
  1594. headers.emplace("Host", "example.com");
  1595. headers.emplace("Accept-Encoding", "gzip");
  1596. headers.emplace("User-Agent", "test");
  1597. headers.emplace("Accept-Encoding", "deflate");
  1598. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1599. "Accept-Encoding=deflate ",
  1600. entries_to_string(headers));
  1601. }
  1602. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1603. Headers headers = {{"Content-Type", "text/html"},
  1604. {"CONTENT-TYPE", "text/xml"}};
  1605. EXPECT_EQ(2U, headers.count("content-type"));
  1606. auto it = headers.find("content-type");
  1607. ASSERT_TRUE(it != headers.end());
  1608. EXPECT_EQ("text/html", it->second);
  1609. }
  1610. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1611. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1612. // drop only those fields and leave everything positioned between them.
  1613. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1614. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1615. auto rng = headers.equal_range("a");
  1616. headers.erase(rng.first, rng.second);
  1617. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1618. }
  1619. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1620. Headers headers = {
  1621. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1622. EXPECT_EQ(3U, headers.erase("A"));
  1623. EXPECT_EQ(0U, headers.count("A"));
  1624. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1625. }
  1626. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1627. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1628. headers.emplace_front("Host", "example.com");
  1629. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1630. entries_to_string(headers));
  1631. }
  1632. TEST(ParseHeaderValueTest, Range) {
  1633. {
  1634. Ranges ranges;
  1635. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1636. EXPECT_TRUE(ret);
  1637. EXPECT_EQ(1u, ranges.size());
  1638. EXPECT_EQ(1u, ranges[0].first);
  1639. EXPECT_EQ(-1, ranges[0].second);
  1640. }
  1641. {
  1642. Ranges ranges;
  1643. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1644. EXPECT_TRUE(ret);
  1645. EXPECT_EQ(1u, ranges.size());
  1646. EXPECT_EQ(-1, ranges[0].first);
  1647. EXPECT_EQ(1u, ranges[0].second);
  1648. }
  1649. {
  1650. Ranges ranges;
  1651. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1652. EXPECT_TRUE(ret);
  1653. EXPECT_EQ(1u, ranges.size());
  1654. EXPECT_EQ(1u, ranges[0].first);
  1655. EXPECT_EQ(10u, ranges[0].second);
  1656. }
  1657. {
  1658. Ranges ranges;
  1659. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1660. EXPECT_FALSE(ret);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(2u, ranges.size());
  1667. EXPECT_EQ(1u, ranges[0].first);
  1668. EXPECT_EQ(10u, ranges[0].second);
  1669. EXPECT_EQ(100u, ranges[1].first);
  1670. EXPECT_EQ(-1, ranges[1].second);
  1671. }
  1672. {
  1673. Ranges ranges;
  1674. auto ret =
  1675. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1676. EXPECT_TRUE(ret);
  1677. EXPECT_EQ(3u, ranges.size());
  1678. EXPECT_EQ(1u, ranges[0].first);
  1679. EXPECT_EQ(10u, ranges[0].second);
  1680. EXPECT_EQ(100u, ranges[1].first);
  1681. EXPECT_EQ(200u, ranges[1].second);
  1682. EXPECT_EQ(300u, ranges[2].first);
  1683. EXPECT_EQ(400u, ranges[2].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1688. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1689. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1690. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1700. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1701. EXPECT_FALSE(
  1702. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1703. EXPECT_TRUE(ranges.empty());
  1704. }
  1705. {
  1706. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1707. // remainder of the representation, so it stays accepted.
  1708. Ranges ranges;
  1709. auto ret =
  1710. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1711. EXPECT_TRUE(ret);
  1712. ASSERT_EQ(1u, ranges.size());
  1713. EXPECT_EQ(0, ranges[0].first);
  1714. EXPECT_EQ(-1, ranges[0].second);
  1715. }
  1716. }
  1717. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1718. Request req;
  1719. req.set_header("Accept-Encoding", "gzip");
  1720. Response res;
  1721. res.set_header("Content-Type", "text/plain");
  1722. auto ret = detail::encoding_type(req, res);
  1723. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1724. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1725. #else
  1726. EXPECT_TRUE(ret == detail::EncodingType::None);
  1727. #endif
  1728. }
  1729. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1730. Request req;
  1731. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1732. Response res;
  1733. res.set_header("Content-Type", "text/plain");
  1734. auto ret = detail::encoding_type(req, res);
  1735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1736. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1737. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1738. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1739. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1740. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1741. #else
  1742. EXPECT_TRUE(ret == detail::EncodingType::None);
  1743. #endif
  1744. }
  1745. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1746. Request req;
  1747. req.set_header("Accept-Encoding",
  1748. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1749. Response res;
  1750. res.set_header("Content-Type", "text/plain");
  1751. auto ret = detail::encoding_type(req, res);
  1752. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1753. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1754. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1755. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1756. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1757. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1758. #else
  1759. EXPECT_TRUE(ret == detail::EncodingType::None);
  1760. #endif
  1761. }
  1762. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1763. // All supported encodings rejected with q=0 should return None
  1764. Request req;
  1765. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1766. Response res;
  1767. res.set_header("Content-Type", "text/plain");
  1768. auto ret = detail::encoding_type(req, res);
  1769. EXPECT_TRUE(ret == detail::EncodingType::None);
  1770. }
  1771. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1772. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1773. Request req;
  1774. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1775. Response res;
  1776. res.set_header("Content-Type", "text/plain");
  1777. auto ret = detail::encoding_type(req, res);
  1778. EXPECT_TRUE(ret == detail::EncodingType::None);
  1779. }
  1780. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1781. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1782. Request req;
  1783. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1784. Response res;
  1785. res.set_header("Content-Type", "text/plain");
  1786. auto ret = detail::encoding_type(req, res);
  1787. EXPECT_TRUE(ret == detail::EncodingType::None);
  1788. }
  1789. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1790. // RFC 7231: Accept-Encoding values are case-insensitive
  1791. Request req;
  1792. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1793. Response res;
  1794. res.set_header("Content-Type", "text/plain");
  1795. auto ret = detail::encoding_type(req, res);
  1796. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1797. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1798. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1799. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1800. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1801. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1802. #else
  1803. EXPECT_TRUE(ret == detail::EncodingType::None);
  1804. #endif
  1805. }
  1806. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1807. // q value should determine priority, not hardcoded order
  1808. Request req;
  1809. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1810. Response res;
  1811. res.set_header("Content-Type", "text/plain");
  1812. auto ret = detail::encoding_type(req, res);
  1813. // gzip has highest q=1.0, so it should be selected even though
  1814. // br and zstd are also supported
  1815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1816. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1817. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1818. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1819. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1820. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1821. #else
  1822. EXPECT_TRUE(ret == detail::EncodingType::None);
  1823. #endif
  1824. }
  1825. TEST(BufferStreamTest, read) {
  1826. detail::BufferStream strm1;
  1827. Stream &strm = strm1;
  1828. EXPECT_EQ(5, strm.write("hello"));
  1829. char buf[512];
  1830. EXPECT_EQ(2, strm.read(buf, 2));
  1831. EXPECT_EQ('h', buf[0]);
  1832. EXPECT_EQ('e', buf[1]);
  1833. EXPECT_EQ(2, strm.read(buf, 2));
  1834. EXPECT_EQ('l', buf[0]);
  1835. EXPECT_EQ('l', buf[1]);
  1836. EXPECT_EQ(1, strm.read(buf, 1));
  1837. EXPECT_EQ('o', buf[0]);
  1838. EXPECT_EQ(0, strm.read(buf, 1));
  1839. }
  1840. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1841. auto host = "www.httpwatch.com";
  1842. auto ip = hosted_at(host);
  1843. EXPECT_EQ("23.96.13.243", ip);
  1844. std::vector<std::string> addrs;
  1845. hosted_at(host, addrs);
  1846. EXPECT_EQ(1u, addrs.size());
  1847. }
  1848. #if 0 // It depends on each test environment...
  1849. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1850. auto host = "www.youtube.com";
  1851. std::vector<std::string> addrs;
  1852. hosted_at(host, addrs);
  1853. EXPECT_EQ(20u, addrs.size());
  1854. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1855. EXPECT_TRUE(it != addrs.end());
  1856. }
  1857. #endif
  1858. class ChunkedEncodingTest : public ::testing::Test {
  1859. protected:
  1860. ChunkedEncodingTest()
  1861. : cli_(HOST, PORT)
  1862. #ifdef CPPHTTPLIB_SSL_ENABLED
  1863. ,
  1864. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1865. #endif
  1866. {
  1867. cli_.set_connection_timeout(2);
  1868. #ifdef CPPHTTPLIB_SSL_ENABLED
  1869. cli_.enable_server_certificate_verification(false);
  1870. #endif
  1871. }
  1872. virtual void SetUp() {
  1873. read_file("./image.jpg", image_data_);
  1874. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("Hello World!", "text/plain");
  1876. });
  1877. svr_.Get(
  1878. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1879. res.set_chunked_content_provider(
  1880. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1881. size_t remaining = image_data_.size() - offset;
  1882. if (remaining == 0) {
  1883. sink.done();
  1884. } else {
  1885. constexpr size_t CHUNK_SIZE = 1024;
  1886. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1887. sink.write(&image_data_[offset], send_size);
  1888. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1889. }
  1890. return true;
  1891. });
  1892. });
  1893. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1894. svr_.wait_until_ready();
  1895. }
  1896. virtual void TearDown() {
  1897. svr_.stop();
  1898. if (!request_threads_.empty()) {
  1899. std::this_thread::sleep_for(std::chrono::seconds(1));
  1900. for (auto &t : request_threads_) {
  1901. t.join();
  1902. }
  1903. }
  1904. t_.join();
  1905. }
  1906. #ifdef CPPHTTPLIB_SSL_ENABLED
  1907. SSLClient cli_;
  1908. SSLServer svr_;
  1909. #else
  1910. Client cli_;
  1911. Server svr_;
  1912. #endif
  1913. thread t_;
  1914. std::vector<thread> request_threads_;
  1915. std::string image_data_;
  1916. };
  1917. TEST_F(ChunkedEncodingTest, NormalGet) {
  1918. auto res = cli_.Get("/chunked");
  1919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1920. std::string out;
  1921. read_file("./image.jpg", out);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. EXPECT_EQ(out, res->body);
  1924. }
  1925. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1926. std::string body;
  1927. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1928. body.append(data, data_length);
  1929. return true;
  1930. });
  1931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1932. std::string out;
  1933. read_file("./image.jpg", out);
  1934. EXPECT_EQ(StatusCode::OK_200, res->status);
  1935. EXPECT_EQ(out, body);
  1936. }
  1937. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1938. std::string body;
  1939. auto res = cli_.Get(
  1940. "/chunked",
  1941. [&](const Response &response) {
  1942. EXPECT_EQ(StatusCode::OK_200, response.status);
  1943. return true;
  1944. },
  1945. [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1950. std::string out;
  1951. read_file("./image.jpg", out);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. EXPECT_EQ(out, body);
  1954. }
  1955. TEST(RangeTest, FromHTTPBin_Online) {
  1956. auto host = "httpbingo.org";
  1957. auto path = std::string{"/range/32"};
  1958. #ifdef CPPHTTPLIB_SSL_ENABLED
  1959. auto port = 443;
  1960. SSLClient cli(host, port);
  1961. #else
  1962. auto port = 80;
  1963. Client cli(host, port);
  1964. #endif
  1965. cli.set_connection_timeout(5);
  1966. {
  1967. auto res = cli.Get(path);
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1970. EXPECT_EQ(StatusCode::OK_200, res->status);
  1971. }
  1972. {
  1973. Headers headers = {make_range_header({{1, -1}})};
  1974. auto res = cli.Get(path, headers);
  1975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1976. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1978. }
  1979. {
  1980. Headers headers = {make_range_header({{1, 10}})};
  1981. auto res = cli.Get(path, headers);
  1982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1983. EXPECT_EQ("bcdefghijk", res->body);
  1984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1985. }
  1986. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1987. // entire resource, while the original httpbin returned 200. Both are
  1988. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1989. {
  1990. Headers headers = {make_range_header({{0, 31}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1994. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1995. res->status == StatusCode::PartialContent_206);
  1996. }
  1997. {
  1998. Headers headers = {make_range_header({{0, -1}})};
  1999. auto res = cli.Get(path, headers);
  2000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2001. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2002. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2003. res->status == StatusCode::PartialContent_206);
  2004. }
  2005. // go-httpbin returns 206 with clamped range for over-range requests,
  2006. // while the original httpbin returned 416. Both behaviors are observed
  2007. // in real servers, so we only verify the request succeeds.
  2008. {
  2009. Headers headers = {make_range_header({{0, 32}})};
  2010. auto res = cli.Get(path, headers);
  2011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2012. }
  2013. }
  2014. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2015. auto host = "unresolvableaddress.local";
  2016. auto path = std::string{"/"};
  2017. #ifdef CPPHTTPLIB_SSL_ENABLED
  2018. auto port = 443;
  2019. SSLClient cli(host, port);
  2020. #else
  2021. auto port = 80;
  2022. Client cli(host, port);
  2023. #endif
  2024. cli.set_connection_timeout(1);
  2025. {
  2026. auto res = cli.Get(path);
  2027. ASSERT_FALSE(res);
  2028. }
  2029. std::this_thread::sleep_for(std::chrono::seconds(8));
  2030. }
  2031. #if defined(__linux__) && defined(__GLIBC__) && \
  2032. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2033. // Forward declaration: in split builds split.py strips `inline` and moves the
  2034. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2035. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2036. // against the symbol in both header-only and split builds.
  2037. namespace httplib {
  2038. namespace detail {
  2039. int getaddrinfo_with_timeout(const char *node, const char *service,
  2040. const struct addrinfo *hints,
  2041. struct addrinfo **res, time_t timeout_sec);
  2042. } // namespace detail
  2043. } // namespace httplib
  2044. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2045. //
  2046. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2047. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2048. // gai_suspend() call hits the connection timeout the function calls
  2049. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2050. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2051. // still alive and still references the now-destroyed stack frame.
  2052. //
  2053. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2054. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2055. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2056. // and runs them in a container.
  2057. namespace {
  2058. bool should_run_issue_2431_tests() {
  2059. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2060. return v && *v && std::string(v) != "0";
  2061. }
  2062. std::string unique_unresolvable_host(int n) {
  2063. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2064. // glibc still asks the configured nameserver — which is exactly the path
  2065. // we want to exercise. A unique label per call avoids the resolver cache.
  2066. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2067. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2068. std::to_string(n) + ".invalid";
  2069. }
  2070. } // namespace
  2071. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2072. if (!should_run_issue_2431_tests()) {
  2073. GTEST_SKIP()
  2074. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2075. }
  2076. for (int i = 0; i < 8; ++i) {
  2077. struct addrinfo hints;
  2078. memset(&hints, 0, sizeof(hints));
  2079. hints.ai_family = AF_UNSPEC;
  2080. hints.ai_socktype = SOCK_STREAM;
  2081. auto host = unique_unresolvable_host(i);
  2082. struct addrinfo *result = nullptr;
  2083. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2084. &result, /*timeout_sec=*/1);
  2085. if (rc == 0 && result) { freeaddrinfo(result); }
  2086. }
  2087. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2088. // stack region they still believe holds their gaicb.
  2089. std::this_thread::sleep_for(std::chrono::seconds(3));
  2090. }
  2091. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2092. if (!should_run_issue_2431_tests()) {
  2093. GTEST_SKIP()
  2094. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2095. }
  2096. std::atomic<bool> stop{false};
  2097. std::vector<std::thread> threads;
  2098. for (int t = 0; t < 8; ++t) {
  2099. threads.emplace_back([t, &stop] {
  2100. int i = 0;
  2101. while (!stop.load(std::memory_order_relaxed)) {
  2102. struct addrinfo hints;
  2103. memset(&hints, 0, sizeof(hints));
  2104. hints.ai_family = AF_UNSPEC;
  2105. hints.ai_socktype = SOCK_STREAM;
  2106. auto host = unique_unresolvable_host(t * 100000 + i++);
  2107. struct addrinfo *result = nullptr;
  2108. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2109. &result, /*timeout_sec=*/1);
  2110. if (rc == 0 && result) { freeaddrinfo(result); }
  2111. }
  2112. });
  2113. }
  2114. std::this_thread::sleep_for(std::chrono::seconds(8));
  2115. stop.store(true, std::memory_order_relaxed);
  2116. for (auto &th : threads) {
  2117. th.join();
  2118. }
  2119. std::this_thread::sleep_for(std::chrono::seconds(3));
  2120. }
  2121. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2122. if (!should_run_issue_2431_tests()) {
  2123. GTEST_SKIP()
  2124. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2125. }
  2126. std::atomic<bool> stop{false};
  2127. std::vector<std::thread> threads;
  2128. for (int t = 0; t < 8; ++t) {
  2129. threads.emplace_back([t, &stop] {
  2130. int i = 0;
  2131. while (!stop.load(std::memory_order_relaxed)) {
  2132. auto host = unique_unresolvable_host(t * 100000 + i++);
  2133. Client cli(host, 80);
  2134. cli.set_connection_timeout(1, 0);
  2135. cli.set_read_timeout(1, 0);
  2136. cli.set_write_timeout(1, 0);
  2137. (void)cli.Get("/");
  2138. }
  2139. });
  2140. }
  2141. std::this_thread::sleep_for(std::chrono::seconds(8));
  2142. stop.store(true, std::memory_order_relaxed);
  2143. for (auto &th : threads) {
  2144. th.join();
  2145. }
  2146. std::this_thread::sleep_for(std::chrono::seconds(3));
  2147. }
  2148. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2149. TEST(ConnectionErrorTest, InvalidHost) {
  2150. auto host = "-abcde.com";
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. auto port = 443;
  2153. SSLClient cli(host, port);
  2154. #else
  2155. auto port = 80;
  2156. Client cli(host, port);
  2157. #endif
  2158. cli.set_connection_timeout(std::chrono::seconds(2));
  2159. auto res = cli.Get("/");
  2160. ASSERT_TRUE(!res);
  2161. EXPECT_EQ(Error::Connection, res.error());
  2162. }
  2163. TEST(ConnectionErrorTest, InvalidHost2) {
  2164. auto host = "httpcan.org/";
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. SSLClient cli(host);
  2167. #else
  2168. Client cli(host);
  2169. #endif
  2170. cli.set_connection_timeout(std::chrono::seconds(2));
  2171. auto res = cli.Get("/");
  2172. ASSERT_TRUE(!res);
  2173. EXPECT_EQ(Error::Connection, res.error());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2176. auto host = "httpcan.org/";
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. SSLClient cli(host);
  2179. #else
  2180. Client cli(host);
  2181. #endif
  2182. cli.set_connection_timeout(std::chrono::seconds(2));
  2183. auto res = cli.Get("/");
  2184. ASSERT_TRUE(!res);
  2185. stringstream s;
  2186. s << "error code: " << res.error();
  2187. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2188. }
  2189. TEST(ConnectionErrorTest, InvalidPort) {
  2190. auto host = "localhost";
  2191. auto port = 44380;
  2192. #ifdef CPPHTTPLIB_SSL_ENABLED
  2193. SSLClient cli(host, port);
  2194. #else
  2195. Client cli(host, port);
  2196. #endif
  2197. cli.set_connection_timeout(std::chrono::seconds(2));
  2198. auto res = cli.Get("/");
  2199. ASSERT_TRUE(!res);
  2200. EXPECT_TRUE(Error::Connection == res.error() ||
  2201. Error::ConnectionTimeout == res.error());
  2202. }
  2203. TEST(ConnectionErrorTest, Timeout_Online) {
  2204. auto host = "google.com";
  2205. #ifdef CPPHTTPLIB_SSL_ENABLED
  2206. auto port = 44380;
  2207. SSLClient cli(host, port);
  2208. #else
  2209. auto port = 8080;
  2210. Client cli(host, port);
  2211. #endif
  2212. cli.set_connection_timeout(std::chrono::seconds(2));
  2213. // only probe one address type so that the error reason
  2214. // correlates to the timed-out IPv4, not the unsupported
  2215. // IPv6 connection attempt
  2216. cli.set_address_family(AF_INET);
  2217. auto res = cli.Get("/");
  2218. ASSERT_TRUE(!res);
  2219. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2220. }
  2221. TEST(CancelTest, NoCancel_Online) {
  2222. auto host = "httpbingo.org";
  2223. auto path = std::string{"/range/32"};
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. auto port = 443;
  2226. SSLClient cli(host, port);
  2227. #else
  2228. auto port = 80;
  2229. Client cli(host, port);
  2230. #endif
  2231. cli.set_connection_timeout(std::chrono::seconds(5));
  2232. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. }
  2237. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2238. // Use /bytes with a large payload so that the DownloadProgress callback
  2239. // (which only fires for Content-Length responses) is invoked before the
  2240. // entire body is received, giving cancellation a chance to fire.
  2241. auto host = "httpbingo.org";
  2242. auto path = std::string{"/bytes/524288"};
  2243. #ifdef CPPHTTPLIB_SSL_ENABLED
  2244. auto port = 443;
  2245. SSLClient cli(host, port);
  2246. #else
  2247. auto port = 80;
  2248. Client cli(host, port);
  2249. #endif
  2250. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2251. cli.set_connection_timeout(std::chrono::seconds(5));
  2252. ASSERT_TRUE(!res);
  2253. EXPECT_EQ(Error::Canceled, res.error());
  2254. }
  2255. TEST(CancelTest, WithCancelLargePayload_Online) {
  2256. auto host = "httpbingo.org";
  2257. auto path = std::string{"/bytes/524288"};
  2258. #ifdef CPPHTTPLIB_SSL_ENABLED
  2259. auto port = 443;
  2260. SSLClient cli(host, port);
  2261. #else
  2262. auto port = 80;
  2263. Client cli(host, port);
  2264. #endif
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. uint32_t count = 0;
  2267. auto res =
  2268. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2269. ASSERT_TRUE(!res);
  2270. EXPECT_EQ(Error::Canceled, res.error());
  2271. }
  2272. TEST(CancelTest, NoCancelPost) {
  2273. Server svr;
  2274. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2275. res.set_content("Hello World!", "text/plain");
  2276. });
  2277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2278. auto se = detail::scope_exit([&] {
  2279. svr.stop();
  2280. thread.join();
  2281. ASSERT_FALSE(svr.is_running());
  2282. });
  2283. svr.wait_until_ready();
  2284. Client cli(HOST, PORT);
  2285. cli.set_connection_timeout(std::chrono::seconds(5));
  2286. auto res =
  2287. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2288. "application/json", [](uint64_t, uint64_t) { return true; });
  2289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2290. EXPECT_EQ("Hello World!", res->body);
  2291. EXPECT_EQ(StatusCode::OK_200, res->status);
  2292. }
  2293. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2294. Server svr;
  2295. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2296. res.set_content("Hello World!", "text/plain");
  2297. });
  2298. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2299. auto se = detail::scope_exit([&] {
  2300. svr.stop();
  2301. thread.join();
  2302. ASSERT_FALSE(svr.is_running());
  2303. });
  2304. svr.wait_until_ready();
  2305. Client cli(HOST, PORT);
  2306. cli.set_connection_timeout(std::chrono::seconds(5));
  2307. auto res =
  2308. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2309. "application/json", [](uint64_t, uint64_t) { return false; });
  2310. ASSERT_TRUE(!res);
  2311. EXPECT_EQ(Error::Canceled, res.error());
  2312. }
  2313. TEST(CancelTest, WithCancelLargePayloadPost) {
  2314. Server svr;
  2315. svr.set_payload_max_length(200 * 1024 * 1024);
  2316. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2317. res.set_content(LARGE_DATA, "text/plain");
  2318. });
  2319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2320. auto se = detail::scope_exit([&] {
  2321. svr.stop();
  2322. thread.join();
  2323. ASSERT_FALSE(svr.is_running());
  2324. });
  2325. svr.wait_until_ready();
  2326. Client cli(HOST, PORT);
  2327. cli.set_payload_max_length(200 * 1024 * 1024);
  2328. cli.set_connection_timeout(std::chrono::seconds(5));
  2329. auto res =
  2330. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2331. "application/json", [](uint64_t, uint64_t) { return false; });
  2332. ASSERT_TRUE(!res);
  2333. EXPECT_EQ(Error::Canceled, res.error());
  2334. }
  2335. TEST(CancelTest, NoCancelPut) {
  2336. Server svr;
  2337. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2338. res.set_content("Hello World!", "text/plain");
  2339. });
  2340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2341. auto se = detail::scope_exit([&] {
  2342. svr.stop();
  2343. thread.join();
  2344. ASSERT_FALSE(svr.is_running());
  2345. });
  2346. svr.wait_until_ready();
  2347. Client cli(HOST, PORT);
  2348. cli.set_connection_timeout(std::chrono::seconds(5));
  2349. auto res =
  2350. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2351. "application/json", [](uint64_t, uint64_t) { return true; });
  2352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2353. EXPECT_EQ("Hello World!", res->body);
  2354. EXPECT_EQ(StatusCode::OK_200, res->status);
  2355. }
  2356. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2357. Server svr;
  2358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2359. res.set_content("Hello World!", "text/plain");
  2360. });
  2361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2362. auto se = detail::scope_exit([&] {
  2363. svr.stop();
  2364. thread.join();
  2365. ASSERT_FALSE(svr.is_running());
  2366. });
  2367. svr.wait_until_ready();
  2368. Client cli(HOST, PORT);
  2369. cli.set_connection_timeout(std::chrono::seconds(5));
  2370. auto res =
  2371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2372. "application/json", [](uint64_t, uint64_t) { return false; });
  2373. ASSERT_TRUE(!res);
  2374. EXPECT_EQ(Error::Canceled, res.error());
  2375. }
  2376. TEST(CancelTest, WithCancelLargePayloadPut) {
  2377. Server svr;
  2378. svr.set_payload_max_length(200 * 1024 * 1024);
  2379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2380. res.set_content(LARGE_DATA, "text/plain");
  2381. });
  2382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2383. auto se = detail::scope_exit([&] {
  2384. svr.stop();
  2385. thread.join();
  2386. ASSERT_FALSE(svr.is_running());
  2387. });
  2388. svr.wait_until_ready();
  2389. Client cli(HOST, PORT);
  2390. cli.set_payload_max_length(200 * 1024 * 1024);
  2391. cli.set_connection_timeout(std::chrono::seconds(5));
  2392. auto res =
  2393. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2394. "application/json", [](uint64_t, uint64_t) { return false; });
  2395. ASSERT_TRUE(!res);
  2396. EXPECT_EQ(Error::Canceled, res.error());
  2397. }
  2398. TEST(CancelTest, NoCancelPatch) {
  2399. Server svr;
  2400. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2401. res.set_content("Hello World!", "text/plain");
  2402. });
  2403. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2404. auto se = detail::scope_exit([&] {
  2405. svr.stop();
  2406. thread.join();
  2407. ASSERT_FALSE(svr.is_running());
  2408. });
  2409. svr.wait_until_ready();
  2410. Client cli(HOST, PORT);
  2411. cli.set_connection_timeout(std::chrono::seconds(5));
  2412. auto res =
  2413. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2414. "application/json", [](uint64_t, uint64_t) { return true; });
  2415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2416. EXPECT_EQ("Hello World!", res->body);
  2417. EXPECT_EQ(StatusCode::OK_200, res->status);
  2418. }
  2419. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2420. Server svr;
  2421. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2422. res.set_content("Hello World!", "text/plain");
  2423. });
  2424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2425. auto se = detail::scope_exit([&] {
  2426. svr.stop();
  2427. thread.join();
  2428. ASSERT_FALSE(svr.is_running());
  2429. });
  2430. svr.wait_until_ready();
  2431. Client cli(HOST, PORT);
  2432. cli.set_connection_timeout(std::chrono::seconds(5));
  2433. auto res =
  2434. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2435. "application/json", [](uint64_t, uint64_t) { return false; });
  2436. ASSERT_TRUE(!res);
  2437. EXPECT_EQ(Error::Canceled, res.error());
  2438. }
  2439. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2440. Server svr;
  2441. svr.set_payload_max_length(200 * 1024 * 1024);
  2442. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2443. res.set_content(LARGE_DATA, "text/plain");
  2444. });
  2445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2446. auto se = detail::scope_exit([&] {
  2447. svr.stop();
  2448. thread.join();
  2449. ASSERT_FALSE(svr.is_running());
  2450. });
  2451. svr.wait_until_ready();
  2452. Client cli(HOST, PORT);
  2453. cli.set_payload_max_length(200 * 1024 * 1024);
  2454. cli.set_connection_timeout(std::chrono::seconds(5));
  2455. auto res =
  2456. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2457. "application/json", [](uint64_t, uint64_t) { return false; });
  2458. ASSERT_TRUE(!res);
  2459. EXPECT_EQ(Error::Canceled, res.error());
  2460. }
  2461. TEST(CancelTest, NoCancelDelete) {
  2462. Server svr;
  2463. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2464. res.set_content("Hello World!", "text/plain");
  2465. });
  2466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2467. auto se = detail::scope_exit([&] {
  2468. svr.stop();
  2469. thread.join();
  2470. ASSERT_FALSE(svr.is_running());
  2471. });
  2472. svr.wait_until_ready();
  2473. Client cli(HOST, PORT);
  2474. cli.set_connection_timeout(std::chrono::seconds(5));
  2475. auto res =
  2476. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2477. "application/json", [](uint64_t, uint64_t) { return true; });
  2478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2479. EXPECT_EQ("Hello World!", res->body);
  2480. EXPECT_EQ(StatusCode::OK_200, res->status);
  2481. }
  2482. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2483. Server svr;
  2484. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2485. res.set_content("Hello World!", "text/plain");
  2486. });
  2487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2488. auto se = detail::scope_exit([&] {
  2489. svr.stop();
  2490. thread.join();
  2491. ASSERT_FALSE(svr.is_running());
  2492. });
  2493. svr.wait_until_ready();
  2494. Client cli(HOST, PORT);
  2495. cli.set_connection_timeout(std::chrono::seconds(5));
  2496. auto res =
  2497. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2498. "application/json", [](uint64_t, uint64_t) { return false; });
  2499. ASSERT_TRUE(!res);
  2500. EXPECT_EQ(Error::Canceled, res.error());
  2501. }
  2502. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2503. Server svr;
  2504. svr.set_payload_max_length(200 * 1024 * 1024);
  2505. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2506. res.set_content(LARGE_DATA, "text/plain");
  2507. });
  2508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. thread.join();
  2512. ASSERT_FALSE(svr.is_running());
  2513. });
  2514. svr.wait_until_ready();
  2515. Client cli(HOST, PORT);
  2516. cli.set_payload_max_length(200 * 1024 * 1024);
  2517. cli.set_connection_timeout(std::chrono::seconds(5));
  2518. auto res =
  2519. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2520. "application/json", [](uint64_t, uint64_t) { return false; });
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::Canceled, res.error());
  2523. }
  2524. static std::string remove_whitespace(const std::string &input) {
  2525. std::string output;
  2526. output.reserve(input.size());
  2527. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2528. [](unsigned char c) { return !std::isspace(c); });
  2529. return output;
  2530. }
  2531. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2532. auto host = "httpbingo.org";
  2533. auto path = std::string{"/basic-auth/hello/world"};
  2534. #ifdef CPPHTTPLIB_SSL_ENABLED
  2535. auto port = 443;
  2536. SSLClient cli(host, port);
  2537. #else
  2538. auto port = 80;
  2539. Client cli(host, port);
  2540. #endif
  2541. {
  2542. auto res = cli.Get(path);
  2543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2544. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2545. }
  2546. {
  2547. auto res = cli.Get(
  2548. path, Headers{make_basic_authentication_header("hello", "world")});
  2549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2550. auto body = remove_whitespace(res->body);
  2551. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2552. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. {
  2556. cli.set_basic_auth("hello", "world");
  2557. auto res = cli.Get(path);
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. auto body = remove_whitespace(res->body);
  2560. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2561. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. }
  2564. {
  2565. cli.set_basic_auth("hello", "bad");
  2566. auto res = cli.Get(path);
  2567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2568. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2569. }
  2570. {
  2571. cli.set_basic_auth("bad", "world");
  2572. auto res = cli.Get(path);
  2573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2574. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2575. }
  2576. }
  2577. #ifdef CPPHTTPLIB_SSL_ENABLED
  2578. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2579. auto host = "httpbingo.org";
  2580. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2581. auto paths = std::vector<std::string>{
  2582. "/digest-auth/auth/hello/world/MD5",
  2583. "/digest-auth/auth/hello/world/SHA-256",
  2584. };
  2585. auto port = 443;
  2586. SSLClient cli(host, port);
  2587. {
  2588. auto res = cli.Get(unauth_path);
  2589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2590. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2591. }
  2592. {
  2593. cli.set_digest_auth("hello", "world");
  2594. for (const auto &path : paths) {
  2595. auto res = cli.Get(path.c_str());
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. auto body = remove_whitespace(res->body);
  2598. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2599. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2600. EXPECT_EQ(StatusCode::OK_200, res->status);
  2601. }
  2602. cli.set_digest_auth("hello", "bad");
  2603. for (const auto &path : paths) {
  2604. auto res = cli.Get(path.c_str());
  2605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2606. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2607. }
  2608. }
  2609. }
  2610. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2611. // comma-separated list of challenges, and each challenge may itself carry a
  2612. // comma-separated auth-param list, so a server can legally offer Basic
  2613. // before Digest, either as two field lines or packed into one. Runs one 401
  2614. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2615. // value() joins them in receipt order) and checks that the retry carries a
  2616. // well-formed Digest Authorization header naming expected_realm.
  2617. static void
  2618. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2619. const std::string &expected_realm) {
  2620. std::atomic<int> hits{0};
  2621. Server svr;
  2622. svr.Get("/x", [&](const Request &req, Response &res) {
  2623. if (++hits == 1) {
  2624. res.status = StatusCode::Unauthorized_401;
  2625. for (const auto &challenge : challenges) {
  2626. res.set_header("WWW-Authenticate", challenge);
  2627. }
  2628. } else {
  2629. auto authorization = req.get_header_value("Authorization");
  2630. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2631. EXPECT_NE(std::string::npos,
  2632. authorization.find("realm=\"" + expected_realm + "\""));
  2633. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2634. res.set_content("ok", "text/plain");
  2635. }
  2636. });
  2637. auto port = svr.bind_to_any_port(HOST);
  2638. std::thread t([&]() { svr.listen_after_bind(); });
  2639. auto se = detail::scope_exit([&] {
  2640. svr.stop();
  2641. t.join();
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, port);
  2645. cli.set_digest_auth("hello", "world");
  2646. auto res = cli.Get("/x");
  2647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2648. EXPECT_EQ(2, hits.load());
  2649. }
  2650. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2651. static const char *kDigestChallenge =
  2652. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2653. "algorithm=MD5";
  2654. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2655. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2656. "testrealm");
  2657. }
  2658. // Same challenge list with the schemes in the opposite order, to make sure
  2659. // the fix above didn't just special-case "Basic first".
  2660. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2661. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2662. "testrealm");
  2663. }
  2664. // A comma inside a quoted auth-param value must not be mistaken for the
  2665. // separator between two challenges (or two auth-params).
  2666. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2667. run_digest_challenge_list_test(
  2668. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2669. "algorithm=MD5"},
  2670. "test,realm");
  2671. }
  2672. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2673. // make_digest_authentication_header() dereferences both unconditionally, so
  2674. // a server sending a challenge missing either one must not be treated as
  2675. // usable -- doing so used to crash the client with std::out_of_range.
  2676. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2677. Server svr;
  2678. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2679. res.status = StatusCode::Unauthorized_401;
  2680. res.set_header("WWW-Authenticate", challenge);
  2681. });
  2682. auto port = svr.bind_to_any_port(HOST);
  2683. std::thread t([&]() { svr.listen_after_bind(); });
  2684. auto se = detail::scope_exit([&] {
  2685. svr.stop();
  2686. t.join();
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, port);
  2690. cli.set_digest_auth("hello", "world");
  2691. auto res = cli.Get("/x");
  2692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2694. }
  2695. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2696. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2697. }
  2698. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2699. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2700. }
  2701. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2702. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2703. }
  2704. #endif
  2705. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2706. auto host = "google.com";
  2707. auto another_host = "example.com";
  2708. auto wrong_ip = "0.0.0.0";
  2709. #ifdef CPPHTTPLIB_SSL_ENABLED
  2710. SSLClient cli(host);
  2711. #else
  2712. Client cli(host);
  2713. #endif
  2714. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2715. auto res = cli.Get("/");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2718. }
  2719. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2720. auto host = "google.com";
  2721. auto wrong_ip = "0.0.0.0";
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. SSLClient cli(host);
  2724. #else
  2725. Client cli(host);
  2726. #endif
  2727. cli.set_hostname_addr_map({{host, wrong_ip}});
  2728. auto res = cli.Get("/");
  2729. ASSERT_TRUE(!res);
  2730. EXPECT_EQ(Error::Connection, res.error());
  2731. }
  2732. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2733. // A mapped value that is not an IP literal must be resolved. "localhost"
  2734. // resolves from the hosts file, so this test needs no external DNS.
  2735. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2736. auto host = "target.invalid";
  2737. Server svr;
  2738. std::string received_host;
  2739. svr.Get("/hi", [&](const Request &req, Response &res) {
  2740. received_host = req.get_header_value("Host");
  2741. res.set_content("Hello World!", "text/plain");
  2742. });
  2743. auto port = svr.bind_to_any_port(HOST);
  2744. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2745. auto se = detail::scope_exit([&] {
  2746. svr.stop();
  2747. thread.join();
  2748. ASSERT_FALSE(svr.is_running());
  2749. });
  2750. svr.wait_until_ready();
  2751. Client cli(host, port);
  2752. cli.set_hostname_addr_map({{host, HOST}});
  2753. auto res = cli.Get("/hi");
  2754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. // The mapping only redirects the connection; the identity stays host_.
  2757. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2758. }
  2759. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2760. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2761. auto host = "target.invalid";
  2762. Server svr;
  2763. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto port = svr.bind_to_any_port("127.0.0.1");
  2767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2768. auto se = detail::scope_exit([&] {
  2769. svr.stop();
  2770. thread.join();
  2771. ASSERT_FALSE(svr.is_running());
  2772. });
  2773. svr.wait_until_ready();
  2774. Client cli(host, port);
  2775. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2776. auto res = cli.Get("/hi");
  2777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2778. EXPECT_EQ(StatusCode::OK_200, res->status);
  2779. }
  2780. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2781. // An empty mapped value must leave host_ as the connection target. Without
  2782. // that guard the empty value would become the host argument, getaddrinfo
  2783. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2784. // loopback - silently connecting somewhere the caller never asked for.
  2785. // The server listens on loopback, so such a fallback would succeed and is
  2786. // therefore observable as a failure of this test.
  2787. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2788. Server svr;
  2789. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2790. res.set_content("Hello World!", "text/plain");
  2791. });
  2792. auto port = svr.bind_to_any_port(HOST);
  2793. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. thread.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. Client cli(blackhole, port);
  2801. cli.set_hostname_addr_map({{blackhole, ""}});
  2802. cli.set_connection_timeout(1);
  2803. auto res = cli.Get("/hi");
  2804. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2805. }
  2806. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2807. auto host = "httpbingo.org";
  2808. auto path = std::string{"/absolute-redirect/3"};
  2809. #ifdef CPPHTTPLIB_SSL_ENABLED
  2810. SSLClient cli(host);
  2811. #else
  2812. Client cli(host);
  2813. #endif
  2814. cli.set_follow_location(true);
  2815. auto res = cli.Get(path);
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ(StatusCode::OK_200, res->status);
  2818. }
  2819. TEST(RedirectTest, Redirect_Online) {
  2820. auto host = "httpbingo.org";
  2821. auto path = std::string{"/redirect/3"};
  2822. #ifdef CPPHTTPLIB_SSL_ENABLED
  2823. SSLClient cli(host);
  2824. #else
  2825. Client cli(host);
  2826. #endif
  2827. cli.set_follow_location(true);
  2828. auto res = cli.Get(path);
  2829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2830. EXPECT_EQ(StatusCode::OK_200, res->status);
  2831. }
  2832. TEST(RelativeRedirectTest, Redirect_Online) {
  2833. auto host = "httpbingo.org";
  2834. auto path = std::string{"/relative-redirect/3"};
  2835. #ifdef CPPHTTPLIB_SSL_ENABLED
  2836. SSLClient cli(host);
  2837. #else
  2838. Client cli(host);
  2839. #endif
  2840. cli.set_follow_location(true);
  2841. auto res = cli.Get(path);
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. EXPECT_EQ(StatusCode::OK_200, res->status);
  2844. }
  2845. TEST(TooManyRedirectTest, Redirect_Online) {
  2846. auto host = "httpbingo.org";
  2847. auto path = std::string{"/redirect/21"};
  2848. #ifdef CPPHTTPLIB_SSL_ENABLED
  2849. SSLClient cli(host);
  2850. #else
  2851. Client cli(host);
  2852. #endif
  2853. cli.set_follow_location(true);
  2854. auto res = cli.Get(path);
  2855. ASSERT_TRUE(!res);
  2856. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2857. }
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. TEST(YahooRedirectTest, Redirect_Online) {
  2860. Client cli("yahoo.com");
  2861. auto res = cli.Get("/");
  2862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2863. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2864. cli.set_follow_location(true);
  2865. res = cli.Get("/");
  2866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2867. EXPECT_EQ(StatusCode::OK_200, res->status);
  2868. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2869. }
  2870. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2871. #define REDIR_HOST "httpbingo.org"
  2872. #define REDIR_PATH "/redirect-to"
  2873. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2874. SSLClient cli(REDIR_HOST);
  2875. cli.set_follow_location(true);
  2876. auto res =
  2877. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2882. SSLClient cli(REDIR_HOST);
  2883. cli.set_follow_location(true);
  2884. Params params;
  2885. params.emplace("url", "http://example.com");
  2886. params.emplace("status_code", "302");
  2887. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2898. EXPECT_EQ(StatusCode::OK_200, res->status);
  2899. }
  2900. TEST(UrlWithSpace, Redirect_Online) {
  2901. SSLClient cli("edge.forgecdn.net");
  2902. cli.set_follow_location(true);
  2903. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::OK_200, res->status);
  2906. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2907. }
  2908. #endif
  2909. #if !defined(_WIN32) && !defined(_WIN64)
  2910. TEST(ReceiveSignals, Signal) {
  2911. auto setupSignalHandlers = []() {
  2912. struct sigaction act;
  2913. sigemptyset(&act.sa_mask);
  2914. act.sa_flags = SA_SIGINFO;
  2915. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2916. switch (sig) {
  2917. case SIGINT:
  2918. default: break;
  2919. }
  2920. };
  2921. ::sigaction(SIGINT, &act, nullptr);
  2922. };
  2923. Server svr;
  2924. int port = 0;
  2925. auto thread = std::thread([&]() {
  2926. setupSignalHandlers();
  2927. port = svr.bind_to_any_port(HOST);
  2928. svr.listen_after_bind();
  2929. });
  2930. auto se = detail::scope_exit([&] {
  2931. svr.stop();
  2932. thread.join();
  2933. ASSERT_FALSE(svr.is_running());
  2934. });
  2935. svr.wait_until_ready();
  2936. ASSERT_TRUE(svr.is_running());
  2937. pthread_kill(thread.native_handle(), SIGINT);
  2938. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2939. ASSERT_TRUE(svr.is_running());
  2940. }
  2941. #endif
  2942. TEST(RedirectToDifferentPort, Redirect) {
  2943. Server svr1;
  2944. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2945. res.set_content("Hello World!", "text/plain");
  2946. });
  2947. int svr1_port = 0;
  2948. auto thread1 = std::thread([&]() {
  2949. svr1_port = svr1.bind_to_any_port(HOST);
  2950. svr1.listen_after_bind();
  2951. });
  2952. Server svr2;
  2953. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2954. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2955. });
  2956. int svr2_port = 0;
  2957. auto thread2 = std::thread([&]() {
  2958. svr2_port = svr2.bind_to_any_port(HOST);
  2959. svr2.listen_after_bind();
  2960. });
  2961. auto se = detail::scope_exit([&] {
  2962. svr2.stop();
  2963. thread2.join();
  2964. svr1.stop();
  2965. thread1.join();
  2966. ASSERT_FALSE(svr2.is_running());
  2967. ASSERT_FALSE(svr1.is_running());
  2968. });
  2969. svr1.wait_until_ready();
  2970. svr2.wait_until_ready();
  2971. Client cli("localhost", svr2_port);
  2972. cli.set_follow_location(true);
  2973. auto res = cli.Get("/2");
  2974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2975. EXPECT_EQ(StatusCode::OK_200, res->status);
  2976. EXPECT_EQ("Hello World!", res->body);
  2977. }
  2978. static void
  2979. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2980. Server svr1;
  2981. std::string captured_authorization;
  2982. svr1.Get("/target", [&](const Request &req, Response &res) {
  2983. captured_authorization = req.get_header_value("Authorization");
  2984. res.set_content("OK", "text/plain");
  2985. });
  2986. int svr1_port = 0;
  2987. auto thread1 = std::thread([&]() {
  2988. svr1_port = svr1.bind_to_any_port(HOST);
  2989. svr1.listen_after_bind();
  2990. });
  2991. Server svr2;
  2992. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2993. res.set_redirect(
  2994. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2995. });
  2996. int svr2_port = 0;
  2997. auto thread2 = std::thread([&]() {
  2998. svr2_port = svr2.bind_to_any_port(HOST);
  2999. svr2.listen_after_bind();
  3000. });
  3001. auto se = detail::scope_exit([&] {
  3002. svr2.stop();
  3003. thread2.join();
  3004. svr1.stop();
  3005. thread1.join();
  3006. ASSERT_FALSE(svr2.is_running());
  3007. ASSERT_FALSE(svr1.is_running());
  3008. });
  3009. svr1.wait_until_ready();
  3010. svr2.wait_until_ready();
  3011. Client cli("localhost", svr2_port);
  3012. cli.set_follow_location(true);
  3013. set_auth(cli);
  3014. auto res = cli.Get("/redir");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(StatusCode::OK_200, res->status);
  3017. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3018. EXPECT_TRUE(captured_authorization.empty());
  3019. }
  3020. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3021. TestDoNotForwardCredentialsOnRedirect(
  3022. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3023. }
  3024. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3025. TestDoNotForwardCredentialsOnRedirect(
  3026. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3027. }
  3028. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3029. Server svr1;
  3030. std::string captured_cookie;
  3031. bool target_hit = false;
  3032. svr1.Get("/target", [&](const Request &req, Response &res) {
  3033. captured_cookie = req.get_header_value("Cookie");
  3034. target_hit = true;
  3035. res.set_content("OK", "text/plain");
  3036. });
  3037. int svr1_port = 0;
  3038. auto thread1 = std::thread([&]() {
  3039. svr1_port = svr1.bind_to_any_port(HOST);
  3040. svr1.listen_after_bind();
  3041. });
  3042. Server svr2;
  3043. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3044. res.set_redirect(
  3045. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3046. });
  3047. int svr2_port = 0;
  3048. auto thread2 = std::thread([&]() {
  3049. svr2_port = svr2.bind_to_any_port(HOST);
  3050. svr2.listen_after_bind();
  3051. });
  3052. auto se = detail::scope_exit([&] {
  3053. svr2.stop();
  3054. thread2.join();
  3055. svr1.stop();
  3056. thread1.join();
  3057. ASSERT_FALSE(svr2.is_running());
  3058. ASSERT_FALSE(svr1.is_running());
  3059. });
  3060. svr1.wait_until_ready();
  3061. svr2.wait_until_ready();
  3062. Client cli("localhost", svr2_port);
  3063. cli.set_follow_location(true);
  3064. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3065. auto res = cli.Get("/redir", headers);
  3066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3067. EXPECT_EQ(StatusCode::OK_200, res->status);
  3068. EXPECT_TRUE(target_hit);
  3069. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3070. EXPECT_TRUE(captured_cookie.empty());
  3071. }
  3072. TEST(RedirectToSamePort, ForwardCookie) {
  3073. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3074. // header so that ordinary session flows keep working.
  3075. Server svr;
  3076. std::string captured_cookie;
  3077. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3078. res.set_redirect("/target", 302);
  3079. });
  3080. svr.Get("/target", [&](const Request &req, Response &res) {
  3081. captured_cookie = req.get_header_value("Cookie");
  3082. res.set_content("OK", "text/plain");
  3083. });
  3084. auto port = svr.bind_to_any_port(HOST);
  3085. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3086. auto se = detail::scope_exit([&] {
  3087. svr.stop();
  3088. thread.join();
  3089. ASSERT_FALSE(svr.is_running());
  3090. });
  3091. svr.wait_until_ready();
  3092. Client cli(HOST, port);
  3093. cli.set_follow_location(true);
  3094. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3095. auto res = cli.Get("/redir", headers);
  3096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3097. EXPECT_EQ(StatusCode::OK_200, res->status);
  3098. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3099. }
  3100. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3101. Server svr;
  3102. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3103. // Port number that overflows int — should not crash
  3104. res.set_redirect("http://localhost:99999999999999999999/target");
  3105. });
  3106. auto port = svr.bind_to_any_port(HOST);
  3107. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3108. auto se = detail::scope_exit([&] {
  3109. svr.stop();
  3110. thread.join();
  3111. ASSERT_FALSE(svr.is_running());
  3112. });
  3113. svr.wait_until_ready();
  3114. Client cli(HOST, port);
  3115. cli.set_follow_location(true);
  3116. auto res = cli.Get("/redir");
  3117. // Should fail gracefully, not crash (no valid response due to bad port)
  3118. EXPECT_FALSE(res);
  3119. }
  3120. TEST(RedirectFromPageWithContent, Redirect) {
  3121. Server svr;
  3122. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3123. res.set_content("___", "text/plain");
  3124. res.set_redirect("/2");
  3125. });
  3126. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3127. res.set_content("Hello World!", "text/plain");
  3128. });
  3129. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3130. auto se = detail::scope_exit([&] {
  3131. svr.stop();
  3132. th.join();
  3133. ASSERT_FALSE(svr.is_running());
  3134. });
  3135. svr.wait_until_ready();
  3136. {
  3137. Client cli("localhost", PORT);
  3138. cli.set_follow_location(true);
  3139. std::string body;
  3140. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3141. body.append(data, data_length);
  3142. return true;
  3143. });
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ("Hello World!", body);
  3147. }
  3148. {
  3149. Client cli("localhost", PORT);
  3150. std::string body;
  3151. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3152. body.append(data, data_length);
  3153. return true;
  3154. });
  3155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3156. EXPECT_EQ(StatusCode::Found_302, res->status);
  3157. EXPECT_EQ("___", body);
  3158. }
  3159. }
  3160. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3161. Server svr;
  3162. auto port_str = std::to_string(PORT);
  3163. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3164. auto expected_host = "[::1]:" + port_str;
  3165. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3166. res.set_content("___", "text/plain");
  3167. // res.set_redirect("/2");
  3168. res.set_redirect(redirect_url);
  3169. });
  3170. svr.Get("/2", [&](const Request &req, Response &res) {
  3171. auto host_header = req.headers.find("Host");
  3172. ASSERT_TRUE(host_header != req.headers.end());
  3173. EXPECT_EQ(expected_host, host_header->second);
  3174. res.set_content("Hello World!", "text/plain");
  3175. });
  3176. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3177. auto se = detail::scope_exit([&] {
  3178. svr.stop();
  3179. th.join();
  3180. ASSERT_FALSE(svr.is_running());
  3181. });
  3182. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3183. // actually starts anything, so the condition !svr.is_running() will
  3184. // always remain true, and the loop never stops.
  3185. // This basically counts how many milliseconds have passed since the
  3186. // call to svr.listen(), and if after 5 seconds nothing started yet
  3187. // aborts the test.
  3188. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3189. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3190. ASSERT_LT(milliseconds, 5000U);
  3191. }
  3192. {
  3193. Client cli("::1", PORT);
  3194. cli.set_follow_location(true);
  3195. std::string body;
  3196. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3197. body.append(data, data_length);
  3198. return true;
  3199. });
  3200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3201. EXPECT_EQ(StatusCode::OK_200, res->status);
  3202. EXPECT_EQ("Hello World!", body);
  3203. }
  3204. {
  3205. Client cli("::1", PORT);
  3206. std::string body;
  3207. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3208. body.append(data, data_length);
  3209. return true;
  3210. });
  3211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3212. EXPECT_EQ(StatusCode::Found_302, res->status);
  3213. EXPECT_EQ("___", body);
  3214. }
  3215. }
  3216. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3217. Server svr;
  3218. svr.Get("/foo", [](const Request &req, Response &res) {
  3219. auto a = req.params.find("a");
  3220. if (a != req.params.end()) {
  3221. res.set_content((*a).second, "text/plain");
  3222. res.status = StatusCode::OK_200;
  3223. } else {
  3224. res.status = StatusCode::BadRequest_400;
  3225. }
  3226. });
  3227. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3228. auto se = detail::scope_exit([&] {
  3229. svr.stop();
  3230. thread.join();
  3231. ASSERT_FALSE(svr.is_running());
  3232. });
  3233. svr.wait_until_ready();
  3234. {
  3235. Client cli(HOST, PORT);
  3236. cli.set_path_encode(false);
  3237. auto res = cli.Get("/foo?a=explicitly+encoded");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::OK_200, res->status);
  3240. // This expects it back with a space, as the `+` won't have been
  3241. // url-encoded, and server-side the params get decoded turning `+`
  3242. // into spaces.
  3243. EXPECT_EQ("explicitly encoded", res->body);
  3244. }
  3245. }
  3246. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3247. // When path encoding is disabled the client must transmit the supplied
  3248. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3249. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3250. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3251. // than a space (0x20). Assert on the raw wire target to catch this.
  3252. Server svr;
  3253. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3254. svr.Get("/foo", [&](const Request &req, Response &res) {
  3255. EXPECT_EQ(expected_target, req.target);
  3256. res.status = StatusCode::OK_200;
  3257. });
  3258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3259. auto se = detail::scope_exit([&] {
  3260. svr.stop();
  3261. thread.join();
  3262. ASSERT_FALSE(svr.is_running());
  3263. });
  3264. svr.wait_until_ready();
  3265. {
  3266. Client cli(HOST, PORT);
  3267. cli.set_path_encode(false);
  3268. auto res = cli.Get(expected_target.c_str());
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. }
  3273. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3274. // `open_stream()` used to skip the path encoding that the buffered send
  3275. // path applies, so the same `path` produced different bytes in the request
  3276. // line depending on which API was used. Assert the two agree.
  3277. Server svr;
  3278. std::string target;
  3279. svr.Get(".*", [&](const Request &req, Response &res) {
  3280. target = req.target;
  3281. res.status = StatusCode::OK_200;
  3282. });
  3283. auto port = svr.bind_to_any_port(HOST);
  3284. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3285. auto se = detail::scope_exit([&] {
  3286. svr.stop();
  3287. thread.join();
  3288. ASSERT_FALSE(svr.is_running());
  3289. });
  3290. svr.wait_until_ready();
  3291. struct {
  3292. const char *path;
  3293. const char *expected;
  3294. } cases[] = {
  3295. {"/a b?x=1", "/a%20b?x=1"},
  3296. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3297. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3298. };
  3299. for (const auto &c : cases) {
  3300. Client cli(HOST, port);
  3301. target.clear();
  3302. auto res = cli.Get(c.path);
  3303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3304. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3305. auto buffered_target = target;
  3306. target.clear();
  3307. auto handle = cli.open_stream("GET", c.path);
  3308. EXPECT_TRUE(handle.is_valid())
  3309. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3310. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3311. }
  3312. }
  3313. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3314. // The `set_path_encode(false)` contract — transmit the supplied target
  3315. // verbatim — must hold for the streaming API too.
  3316. Server svr;
  3317. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3318. std::string target;
  3319. svr.Get("/foo", [&](const Request &req, Response &res) {
  3320. target = req.target;
  3321. res.status = StatusCode::OK_200;
  3322. });
  3323. auto port = svr.bind_to_any_port(HOST);
  3324. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3325. auto se = detail::scope_exit([&] {
  3326. svr.stop();
  3327. thread.join();
  3328. ASSERT_FALSE(svr.is_running());
  3329. });
  3330. svr.wait_until_ready();
  3331. {
  3332. Client cli(HOST, port);
  3333. cli.set_path_encode(false);
  3334. auto handle = cli.open_stream("GET", expected_target);
  3335. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3336. EXPECT_EQ(expected_target, target);
  3337. }
  3338. }
  3339. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3340. // With path encoding enabled a CR/LF in the target is percent-encoded
  3341. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3342. // write_request_line still backstops `set_path_encode(false)`, which is
  3343. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3344. Server svr;
  3345. // Captured before routing: the decoded path contains a newline, which a
  3346. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3347. std::string target;
  3348. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3349. target = req.target;
  3350. res.status = StatusCode::OK_200;
  3351. return Server::HandlerResponse::Handled;
  3352. });
  3353. auto port = svr.bind_to_any_port(HOST);
  3354. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3355. auto se = detail::scope_exit([&] {
  3356. svr.stop();
  3357. thread.join();
  3358. ASSERT_FALSE(svr.is_running());
  3359. });
  3360. svr.wait_until_ready();
  3361. {
  3362. Client cli(HOST, port);
  3363. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3364. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3365. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3366. }
  3367. }
  3368. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3369. // Nothing may reach the wire: a raw CR/LF target would split the request
  3370. // line and inject headers.
  3371. Server svr;
  3372. // Pre-routing so that "not called" means nothing reached the server at all,
  3373. // rather than merely failing to match a handler pattern.
  3374. auto handler_called = false;
  3375. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3376. handler_called = true;
  3377. res.status = StatusCode::OK_200;
  3378. return Server::HandlerResponse::Handled;
  3379. });
  3380. auto port = svr.bind_to_any_port(HOST);
  3381. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3382. auto se = detail::scope_exit([&] {
  3383. svr.stop();
  3384. thread.join();
  3385. ASSERT_FALSE(svr.is_running());
  3386. });
  3387. svr.wait_until_ready();
  3388. {
  3389. Client cli(HOST, port);
  3390. cli.set_path_encode(false);
  3391. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3392. EXPECT_FALSE(handle.is_valid());
  3393. EXPECT_EQ(Error::Write, handle.error);
  3394. EXPECT_FALSE(handler_called);
  3395. }
  3396. }
  3397. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3398. // Which of the two branches runs is decided by whether the query component
  3399. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3400. // an empty query and must still fall back to building one from
  3401. // `req.params`, while a non-empty query must win over `req.params`.
  3402. Server svr;
  3403. std::string target;
  3404. svr.Get("/foo", [&](const Request &req, Response &res) {
  3405. target = req.target;
  3406. res.status = StatusCode::OK_200;
  3407. });
  3408. auto port = svr.bind_to_any_port(HOST);
  3409. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3410. auto se = detail::scope_exit([&] {
  3411. svr.stop();
  3412. thread.join();
  3413. ASSERT_FALSE(svr.is_running());
  3414. });
  3415. svr.wait_until_ready();
  3416. {
  3417. // Trailing `?` -> empty query component -> `req.params` is used.
  3418. Client cli(HOST, port);
  3419. Request req;
  3420. req.method = "GET";
  3421. req.path = "/foo?";
  3422. req.params.emplace("a", "1");
  3423. target.clear();
  3424. auto res = cli.send(req);
  3425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3426. EXPECT_EQ("/foo?a=1", target);
  3427. }
  3428. {
  3429. // Non-empty query in `req.path` -> `req.params` is not appended.
  3430. Client cli(HOST, port);
  3431. Request req;
  3432. req.method = "GET";
  3433. req.path = "/foo?b=2";
  3434. req.params.emplace("a", "1");
  3435. target.clear();
  3436. auto res = cli.send(req);
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ("/foo?b=2", target);
  3439. }
  3440. }
  3441. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3442. Server svr;
  3443. svr.Get("/", [](const Request &req, Response &) {
  3444. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3445. });
  3446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3447. auto se = detail::scope_exit([&] {
  3448. svr.stop();
  3449. thread.join();
  3450. ASSERT_FALSE(svr.is_running());
  3451. });
  3452. svr.wait_until_ready();
  3453. {
  3454. Client cli(HOST, PORT);
  3455. cli.set_path_encode(false);
  3456. auto res = cli.Get("/?something=%0A");
  3457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. }
  3460. }
  3461. TEST(BindServerTest, BindDualStack) {
  3462. Server svr;
  3463. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3464. res.set_content("Hello World!", "text/plain");
  3465. });
  3466. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3467. auto se = detail::scope_exit([&] {
  3468. svr.stop();
  3469. thread.join();
  3470. ASSERT_FALSE(svr.is_running());
  3471. });
  3472. svr.wait_until_ready();
  3473. {
  3474. Client cli("127.0.0.1", PORT);
  3475. auto res = cli.Get("/1");
  3476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3477. EXPECT_EQ(StatusCode::OK_200, res->status);
  3478. EXPECT_EQ("Hello World!", res->body);
  3479. }
  3480. {
  3481. Client cli("::1", PORT);
  3482. auto res = cli.Get("/1");
  3483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3484. EXPECT_EQ(StatusCode::OK_200, res->status);
  3485. EXPECT_EQ("Hello World!", res->body);
  3486. }
  3487. }
  3488. TEST(BindServerTest, BindAndListenSeparately) {
  3489. Server svr;
  3490. int port = svr.bind_to_any_port("0.0.0.0");
  3491. ASSERT_TRUE(svr.is_valid());
  3492. ASSERT_TRUE(port > 0);
  3493. svr.stop();
  3494. }
  3495. // Reports whether anything is still listening on a loopback port. A plain
  3496. // connect() is used instead of a Client request because a socket left bound by
  3497. // mistake accepts the connection into its backlog and never answers, which
  3498. // would hang the test instead of failing it.
  3499. static bool is_loopback_port_accepting(int port) {
  3500. sockaddr_in addr{};
  3501. addr.sin_family = AF_INET;
  3502. addr.sin_port = htons(static_cast<uint16_t>(port));
  3503. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3504. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3505. EXPECT_NE(sock, INVALID_SOCKET);
  3506. if (sock == INVALID_SOCKET) { return false; }
  3507. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3508. static_cast<socklen_t>(sizeof(addr)));
  3509. detail::close_socket(sock);
  3510. return ret == 0;
  3511. }
  3512. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3513. Server svr;
  3514. auto port = svr.bind_to_any_port("127.0.0.1");
  3515. ASSERT_TRUE(port > 0);
  3516. svr.stop();
  3517. // bind_to_any_port() already called listen(2), so until stop() closed the
  3518. // descriptor the port kept accepting connections into the backlog. ASSERT
  3519. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3520. // below blocks forever in the accept loop.
  3521. ASSERT_FALSE(is_loopback_port_accepting(port));
  3522. // Nothing is left to accept on, so listen_after_bind() must report failure
  3523. // instead of returning success without ever serving.
  3524. EXPECT_FALSE(svr.listen_after_bind());
  3525. // The failed listen marks the server decommissioned, so a waiter returns
  3526. // instead of spinning forever.
  3527. svr.wait_until_ready();
  3528. }
  3529. #ifdef CPPHTTPLIB_SSL_ENABLED
  3530. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3532. CLIENT_CA_CERT_DIR);
  3533. int port = svr.bind_to_any_port("0.0.0.0");
  3534. ASSERT_TRUE(svr.is_valid());
  3535. ASSERT_TRUE(port > 0);
  3536. svr.stop();
  3537. }
  3538. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3539. // or a rejected CustomRoute() registration would not stop the server binding.
  3540. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3542. CLIENT_CA_CERT_DIR);
  3543. ASSERT_TRUE(svr.is_valid());
  3544. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3545. EXPECT_FALSE(svr.is_valid());
  3546. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3547. }
  3548. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3549. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3550. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3551. int port = svr.bind_to_any_port("0.0.0.0");
  3552. ASSERT_TRUE(svr.is_valid());
  3553. ASSERT_TRUE(port > 0);
  3554. svr.stop();
  3555. }
  3556. TEST(BindServerTest, UpdateCertsPem) {
  3557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3558. int port = svr.bind_to_any_port("0.0.0.0");
  3559. ASSERT_TRUE(svr.is_valid());
  3560. ASSERT_TRUE(port > 0);
  3561. // Read PEM files
  3562. std::string cert_pem, key_pem, ca_pem;
  3563. read_file(SERVER_CERT_FILE, cert_pem);
  3564. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3565. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3566. // Update server certificates using PEM API
  3567. ASSERT_TRUE(
  3568. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3569. ASSERT_TRUE(svr.is_valid());
  3570. svr.stop();
  3571. }
  3572. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3573. // Start server with client CA (enables client auth)
  3574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3575. ASSERT_TRUE(svr.is_valid());
  3576. bool handler_called = false;
  3577. svr.Get("/test", [&](const Request &req, Response &res) {
  3578. handler_called = true;
  3579. // Verify client certificate is present
  3580. auto cert = req.peer_cert();
  3581. EXPECT_TRUE(static_cast<bool>(cert));
  3582. res.set_content("ok", "text/plain");
  3583. });
  3584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3585. auto se = detail::scope_exit([&] {
  3586. svr.stop();
  3587. t.join();
  3588. ASSERT_FALSE(svr.is_running());
  3589. });
  3590. svr.wait_until_ready();
  3591. // Read PEM files
  3592. std::string cert_pem, key_pem, ca_pem;
  3593. read_file(SERVER_CERT_FILE, cert_pem);
  3594. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3595. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3596. // Update server certificates and client CA using PEM API while server running
  3597. ASSERT_TRUE(
  3598. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3599. // Connect with client certificate
  3600. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3601. cli.enable_server_certificate_verification(false);
  3602. cli.set_connection_timeout(30);
  3603. auto res = cli.Get("/test");
  3604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3605. ASSERT_EQ(StatusCode::OK_200, res->status);
  3606. ASSERT_TRUE(handler_called);
  3607. EXPECT_EQ("ok", res->body);
  3608. }
  3609. #endif
  3610. TEST(ErrorHandlerTest, ContentLength) {
  3611. Server svr;
  3612. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3613. res.status = StatusCode::OK_200;
  3614. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3615. "text/html"); // <= Content-Length still 13
  3616. });
  3617. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3618. res.set_content("Hello World!\n", "text/plain");
  3619. res.status = 524;
  3620. });
  3621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. thread.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. svr.wait_until_ready();
  3628. {
  3629. Client cli(HOST, PORT);
  3630. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3634. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3635. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3636. }
  3637. }
  3638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3639. TEST(ExceptionTest, WithoutExceptionHandler) {
  3640. Server svr;
  3641. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3642. throw std::runtime_error("exception...");
  3643. });
  3644. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3645. throw std::runtime_error("exception\r\n...");
  3646. });
  3647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3648. auto se = detail::scope_exit([&] {
  3649. svr.stop();
  3650. listen_thread.join();
  3651. ASSERT_FALSE(svr.is_running());
  3652. });
  3653. svr.wait_until_ready();
  3654. Client cli("localhost", PORT);
  3655. {
  3656. auto res = cli.Get("/exception");
  3657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3658. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3659. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3660. }
  3661. {
  3662. auto res = cli.Get("/unknown");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3665. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3666. }
  3667. }
  3668. TEST(ExceptionTest, WithExceptionHandler) {
  3669. Server svr;
  3670. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3671. std::exception_ptr ep) {
  3672. EXPECT_FALSE(ep == nullptr);
  3673. try {
  3674. std::rethrow_exception(ep);
  3675. } catch (std::exception &e) {
  3676. EXPECT_EQ("abc", std::string(e.what()));
  3677. } catch (...) {}
  3678. res.status = StatusCode::InternalServerError_500;
  3679. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3680. "text/html"); // <= Content-Length still 13 at this point
  3681. });
  3682. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3683. res.set_content("Hello World!\n", "text/plain");
  3684. throw std::runtime_error("abc");
  3685. });
  3686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3687. auto se = detail::scope_exit([&] {
  3688. svr.stop();
  3689. thread.join();
  3690. ASSERT_FALSE(svr.is_running());
  3691. });
  3692. svr.wait_until_ready();
  3693. for (size_t i = 0; i < 10; i++) {
  3694. Client cli(HOST, PORT);
  3695. for (size_t j = 0; j < 100; j++) {
  3696. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3698. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3699. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3700. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3701. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3702. }
  3703. cli.set_keep_alive(true);
  3704. for (size_t j = 0; j < 100; j++) {
  3705. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3708. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3709. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3710. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3711. }
  3712. }
  3713. }
  3714. TEST(ExceptionTest, AndErrorHandler) {
  3715. Server svr;
  3716. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3717. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3718. });
  3719. svr.set_exception_handler(
  3720. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3721. EXPECT_FALSE(ep == nullptr);
  3722. try {
  3723. std::rethrow_exception(ep);
  3724. } catch (std::exception &e) {
  3725. res.set_content(e.what(), "text/html");
  3726. } catch (...) {}
  3727. res.status = StatusCode::InternalServerError_500;
  3728. });
  3729. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3730. throw std::runtime_error("EXCEPTION");
  3731. });
  3732. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3733. res.set_content("ERROR", "text/html");
  3734. res.status = StatusCode::InternalServerError_500;
  3735. });
  3736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. Client cli(HOST, PORT);
  3744. {
  3745. auto res = cli.Get("/exception");
  3746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3747. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3748. EXPECT_EQ("EXCEPTION", res->body);
  3749. }
  3750. {
  3751. auto res = cli.Get("/error");
  3752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3753. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3754. EXPECT_EQ("ERROR", res->body);
  3755. }
  3756. {
  3757. auto res = cli.Get("/invalid");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3760. EXPECT_EQ("NOT_FOUND", res->body);
  3761. }
  3762. }
  3763. #endif
  3764. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3765. // process_request() wraps only routing() in a try/catch, so an exception from
  3766. // any other user callback used to unwind into the task queue - which does not
  3767. // catch - and terminate the process. Each test below runs the server on a
  3768. // single worker thread: a guard that catches the exception but still loses the
  3769. // thread would otherwise be hidden by a spare worker serving the follow-up
  3770. // request. Note that a regression here aborts the whole test binary rather
  3771. // than failing one test.
  3772. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3773. Server svr;
  3774. svr.new_task_queue = [] { return new ThreadPool(1); };
  3775. std::atomic<int> reported{0};
  3776. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3777. if (err == Error::UserCallbackException) { reported++; }
  3778. });
  3779. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3780. res.set_content_provider(
  3781. 1024, "text/plain",
  3782. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3783. sink.write("hello", 5);
  3784. throw std::runtime_error("from the content provider");
  3785. });
  3786. });
  3787. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3788. res.set_content("ok", "text/plain");
  3789. });
  3790. auto port = svr.bind_to_any_port(HOST);
  3791. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3792. auto se = detail::scope_exit([&] {
  3793. svr.stop();
  3794. listen_thread.join();
  3795. ASSERT_FALSE(svr.is_running());
  3796. });
  3797. svr.wait_until_ready();
  3798. {
  3799. Client cli(HOST, port);
  3800. cli.set_read_timeout(5, 0);
  3801. EXPECT_FALSE(cli.Get("/throw"));
  3802. }
  3803. EXPECT_TRUE(svr.is_running());
  3804. EXPECT_EQ(1, reported.load());
  3805. // A request on a fresh connection is still served.
  3806. {
  3807. Client cli(HOST, port);
  3808. auto res = cli.Get("/ok");
  3809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3810. EXPECT_EQ(StatusCode::OK_200, res->status);
  3811. EXPECT_EQ("ok", res->body);
  3812. }
  3813. }
  3814. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3815. Server svr;
  3816. svr.new_task_queue = [] { return new ThreadPool(1); };
  3817. std::atomic<bool> should_throw{true};
  3818. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3819. res.set_content("hi", "text/plain");
  3820. });
  3821. svr.set_post_routing_handler(
  3822. [&](const Request & /*req*/, Response & /*res*/) {
  3823. if (should_throw) {
  3824. throw std::runtime_error("from the post-routing handler");
  3825. }
  3826. });
  3827. auto port = svr.bind_to_any_port(HOST);
  3828. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3829. auto se = detail::scope_exit([&] {
  3830. svr.stop();
  3831. listen_thread.join();
  3832. ASSERT_FALSE(svr.is_running());
  3833. });
  3834. svr.wait_until_ready();
  3835. {
  3836. Client cli(HOST, port);
  3837. cli.set_read_timeout(5, 0);
  3838. EXPECT_FALSE(cli.Get("/hi"));
  3839. }
  3840. EXPECT_TRUE(svr.is_running());
  3841. should_throw = false;
  3842. {
  3843. Client cli(HOST, port);
  3844. auto res = cli.Get("/hi");
  3845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3846. EXPECT_EQ(StatusCode::OK_200, res->status);
  3847. EXPECT_EQ("hi", res->body);
  3848. }
  3849. }
  3850. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3851. // The guard reports the caught exception through the error logger, which is
  3852. // a user callback too. A logger that throws has to be contained as well, or
  3853. // the process would terminate from inside the catch.
  3854. Server svr;
  3855. svr.new_task_queue = [] { return new ThreadPool(1); };
  3856. std::atomic<int> reported{0};
  3857. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3858. if (err == Error::UserCallbackException) {
  3859. reported++;
  3860. throw std::runtime_error("from the error logger");
  3861. }
  3862. });
  3863. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3864. res.set_content_provider(
  3865. 1024, "text/plain",
  3866. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3867. sink.write("hello", 5);
  3868. throw std::runtime_error("from the content provider");
  3869. });
  3870. });
  3871. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3872. res.set_content("ok", "text/plain");
  3873. });
  3874. auto port = svr.bind_to_any_port(HOST);
  3875. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3876. auto se = detail::scope_exit([&] {
  3877. svr.stop();
  3878. listen_thread.join();
  3879. ASSERT_FALSE(svr.is_running());
  3880. });
  3881. svr.wait_until_ready();
  3882. {
  3883. Client cli(HOST, port);
  3884. cli.set_read_timeout(5, 0);
  3885. EXPECT_FALSE(cli.Get("/throw"));
  3886. }
  3887. EXPECT_TRUE(svr.is_running());
  3888. EXPECT_EQ(1, reported.load());
  3889. {
  3890. Client cli(HOST, port);
  3891. auto res = cli.Get("/ok");
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. EXPECT_EQ("ok", res->body);
  3895. }
  3896. }
  3897. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3898. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3899. // so the exception unwinds through the ws::WebSocket object on its way to
  3900. // the guard. None of the HTTP cases above cross that.
  3901. Server svr;
  3902. svr.new_task_queue = [] { return new ThreadPool(1); };
  3903. std::atomic<int> reported{0};
  3904. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3905. if (err == Error::UserCallbackException) { reported++; }
  3906. });
  3907. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3908. throw std::runtime_error("from the WebSocket handler");
  3909. });
  3910. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3911. res.set_content("ok", "text/plain");
  3912. });
  3913. auto port = svr.bind_to_any_port(HOST);
  3914. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3915. auto se = detail::scope_exit([&] {
  3916. svr.stop();
  3917. listen_thread.join();
  3918. ASSERT_FALSE(svr.is_running());
  3919. });
  3920. svr.wait_until_ready();
  3921. {
  3922. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3923. "/ws");
  3924. auto res = client.connect();
  3925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3926. // The server dropped the connection instead of dying.
  3927. std::string msg;
  3928. EXPECT_FALSE(client.read(msg));
  3929. client.close();
  3930. }
  3931. EXPECT_TRUE(svr.is_running());
  3932. EXPECT_EQ(1, reported.load());
  3933. {
  3934. Client cli(HOST, port);
  3935. auto res = cli.Get("/ok");
  3936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3937. EXPECT_EQ(StatusCode::OK_200, res->status);
  3938. EXPECT_EQ("ok", res->body);
  3939. }
  3940. }
  3941. #ifdef CPPHTTPLIB_SSL_ENABLED
  3942. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3943. // SSLServer::process_and_close_socket() is a separate overload with its own
  3944. // guard, so it is exercised on its own.
  3945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3946. ASSERT_TRUE(svr.is_valid());
  3947. svr.new_task_queue = [] { return new ThreadPool(1); };
  3948. std::atomic<int> reported{0};
  3949. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3950. if (err == Error::UserCallbackException) { reported++; }
  3951. });
  3952. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3953. res.set_content_provider(
  3954. 1024, "text/plain",
  3955. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3956. sink.write("hello", 5);
  3957. throw std::runtime_error("from the content provider");
  3958. });
  3959. });
  3960. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3961. res.set_content("ok", "text/plain");
  3962. });
  3963. auto port = svr.bind_to_any_port(HOST);
  3964. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3965. auto se = detail::scope_exit([&] {
  3966. svr.stop();
  3967. listen_thread.join();
  3968. ASSERT_FALSE(svr.is_running());
  3969. });
  3970. svr.wait_until_ready();
  3971. {
  3972. SSLClient cli(HOST, port);
  3973. cli.enable_server_certificate_verification(false);
  3974. cli.set_read_timeout(5, 0);
  3975. EXPECT_FALSE(cli.Get("/throw"));
  3976. }
  3977. EXPECT_TRUE(svr.is_running());
  3978. EXPECT_EQ(1, reported.load());
  3979. {
  3980. SSLClient cli(HOST, port);
  3981. cli.enable_server_certificate_verification(false);
  3982. auto res = cli.Get("/ok");
  3983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. EXPECT_EQ("ok", res->body);
  3986. }
  3987. }
  3988. #endif
  3989. #endif
  3990. TEST(NoContentTest, ContentLength) {
  3991. Server svr;
  3992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3993. res.status = StatusCode::NoContent_204;
  3994. });
  3995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3996. auto se = detail::scope_exit([&] {
  3997. svr.stop();
  3998. thread.join();
  3999. ASSERT_FALSE(svr.is_running());
  4000. });
  4001. svr.wait_until_ready();
  4002. {
  4003. Client cli(HOST, PORT);
  4004. auto res = cli.Get("/hi");
  4005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4006. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4007. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4008. }
  4009. }
  4010. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4011. #ifdef CPPHTTPLIB_SSL_ENABLED
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4013. ASSERT_TRUE(svr.is_valid());
  4014. #else
  4015. Server svr;
  4016. #endif
  4017. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4018. if (req.path == "/routing_handler") {
  4019. res.set_header("PRE_ROUTING", "on");
  4020. res.set_content("Routing Handler", "text/plain");
  4021. return httplib::Server::HandlerResponse::Handled;
  4022. }
  4023. return httplib::Server::HandlerResponse::Unhandled;
  4024. });
  4025. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4026. res.set_content("Error", "text/html");
  4027. });
  4028. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4029. if (req.path == "/routing_handler") {
  4030. res.set_header("POST_ROUTING", "on");
  4031. }
  4032. });
  4033. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4034. res.set_content("Hello World!\n", "text/plain");
  4035. });
  4036. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4037. auto se = detail::scope_exit([&] {
  4038. svr.stop();
  4039. thread.join();
  4040. ASSERT_FALSE(svr.is_running());
  4041. });
  4042. svr.wait_until_ready();
  4043. {
  4044. #ifdef CPPHTTPLIB_SSL_ENABLED
  4045. SSLClient cli(HOST, PORT);
  4046. cli.enable_server_certificate_verification(false);
  4047. #else
  4048. Client cli(HOST, PORT);
  4049. #endif
  4050. auto res = cli.Get("/routing_handler");
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("Routing Handler", res->body);
  4054. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4055. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4056. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4057. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4058. }
  4059. {
  4060. #ifdef CPPHTTPLIB_SSL_ENABLED
  4061. SSLClient cli(HOST, PORT);
  4062. cli.enable_server_certificate_verification(false);
  4063. #else
  4064. Client cli(HOST, PORT);
  4065. #endif
  4066. auto res = cli.Get("/hi");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. EXPECT_EQ("Hello World!\n", res->body);
  4070. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4071. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4072. }
  4073. {
  4074. #ifdef CPPHTTPLIB_SSL_ENABLED
  4075. SSLClient cli(HOST, PORT);
  4076. cli.enable_server_certificate_verification(false);
  4077. #else
  4078. Client cli(HOST, PORT);
  4079. #endif
  4080. auto res = cli.Get("/aaa");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4083. EXPECT_EQ("Error", res->body);
  4084. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4085. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4086. }
  4087. }
  4088. TEST(RequestHandlerTest, PreRequestHandler) {
  4089. auto route_path = "/user/:user";
  4090. Server svr;
  4091. svr.Get("/hi", [](const Request &, Response &res) {
  4092. res.set_content("hi", "text/plain");
  4093. });
  4094. svr.Get(route_path, [](const Request &req, Response &res) {
  4095. res.set_content(req.path_params.at("user"), "text/plain");
  4096. });
  4097. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4098. if (req.matched_route == route_path) {
  4099. auto user = req.path_params.at("user");
  4100. if (user != "john") {
  4101. res.status = StatusCode::Forbidden_403;
  4102. res.set_content("error", "text/html");
  4103. return Server::HandlerResponse::Handled;
  4104. }
  4105. }
  4106. return Server::HandlerResponse::Unhandled;
  4107. });
  4108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4109. auto se = detail::scope_exit([&] {
  4110. svr.stop();
  4111. thread.join();
  4112. ASSERT_FALSE(svr.is_running());
  4113. });
  4114. svr.wait_until_ready();
  4115. Client cli(HOST, PORT);
  4116. {
  4117. auto res = cli.Get("/hi");
  4118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. EXPECT_EQ("hi", res->body);
  4121. }
  4122. {
  4123. auto res = cli.Get("/user/john");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. EXPECT_EQ("john", res->body);
  4127. }
  4128. {
  4129. auto res = cli.Get("/user/invalid-user");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4132. EXPECT_EQ("error", res->body);
  4133. }
  4134. }
  4135. // The pre-request handler must run before the request body is read, so a
  4136. // rejected request never forces the server to buffer a (potentially large)
  4137. // body. Here the posted body is larger than the payload limit: if the body
  4138. // were read first the server would answer 413, but because the pre-request
  4139. // handler runs first it answers 403 and the body is never read.
  4140. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4141. Server svr;
  4142. svr.set_payload_max_length(8);
  4143. auto handler_ran = false;
  4144. svr.Post("/reject", [&](const Request &req, Response &res) {
  4145. handler_ran = true;
  4146. res.set_content(req.body, "text/plain");
  4147. });
  4148. svr.Post("/accept", [](const Request &req, Response &res) {
  4149. res.set_content(req.body, "text/plain");
  4150. });
  4151. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4152. if (req.matched_route == "/reject") {
  4153. res.status = StatusCode::Forbidden_403;
  4154. res.set_content("denied", "text/plain");
  4155. return Server::HandlerResponse::Handled;
  4156. }
  4157. return Server::HandlerResponse::Unhandled;
  4158. });
  4159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4160. auto se = detail::scope_exit([&] {
  4161. svr.stop();
  4162. thread.join();
  4163. ASSERT_FALSE(svr.is_running());
  4164. });
  4165. svr.wait_until_ready();
  4166. Client cli(HOST, PORT);
  4167. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4168. // rejects with 403 before the body is read, so 413 is never reached.
  4169. {
  4170. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4172. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4173. EXPECT_EQ("denied", res->body);
  4174. EXPECT_FALSE(handler_ran);
  4175. }
  4176. // An approved route still reads the body and enforces the payload limit.
  4177. {
  4178. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4180. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4181. }
  4182. }
  4183. TEST(UserDataTest, BasicOperations) {
  4184. httplib::UserData ud;
  4185. // Initially empty
  4186. EXPECT_FALSE(ud.has("key"));
  4187. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4188. // set and get
  4189. ud.set("key", 42);
  4190. EXPECT_TRUE(ud.has("key"));
  4191. auto *p = ud.get<int>("key");
  4192. ASSERT_NE(nullptr, p);
  4193. EXPECT_EQ(42, *p);
  4194. // Type mismatch → nullptr
  4195. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4196. // Overwrite with different type
  4197. ud.set("key", std::string("hello"));
  4198. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4199. auto *s = ud.get<std::string>("key");
  4200. ASSERT_NE(nullptr, s);
  4201. EXPECT_EQ("hello", *s);
  4202. // erase
  4203. ud.erase("key");
  4204. EXPECT_FALSE(ud.has("key"));
  4205. // clear
  4206. ud.set("a", 1);
  4207. ud.set("b", 2);
  4208. ud.clear();
  4209. EXPECT_FALSE(ud.has("a"));
  4210. EXPECT_FALSE(ud.has("b"));
  4211. }
  4212. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4213. struct AuthCtx {
  4214. std::string user_id;
  4215. };
  4216. Server svr;
  4217. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4218. res.user_data.set("auth", AuthCtx{"alice"});
  4219. return Server::HandlerResponse::Unhandled;
  4220. });
  4221. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4222. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4223. ASSERT_NE(nullptr, ctx);
  4224. res.set_content("Hello " + ctx->user_id, "text/plain");
  4225. });
  4226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4227. auto se = detail::scope_exit([&] {
  4228. svr.stop();
  4229. thread.join();
  4230. ASSERT_FALSE(svr.is_running());
  4231. });
  4232. svr.wait_until_ready();
  4233. Client cli(HOST, PORT);
  4234. auto res = cli.Get("/me");
  4235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4236. EXPECT_EQ(StatusCode::OK_200, res->status);
  4237. EXPECT_EQ("Hello alice", res->body);
  4238. }
  4239. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4240. struct RoleCtx {
  4241. std::string role;
  4242. };
  4243. Server svr;
  4244. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4245. res.user_data.set("role", RoleCtx{"admin"});
  4246. return Server::HandlerResponse::Unhandled;
  4247. });
  4248. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4249. auto *ctx = res.user_data.get<RoleCtx>("role");
  4250. ASSERT_NE(nullptr, ctx);
  4251. res.set_content(ctx->role, "text/plain");
  4252. });
  4253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4254. auto se = detail::scope_exit([&] {
  4255. svr.stop();
  4256. thread.join();
  4257. ASSERT_FALSE(svr.is_running());
  4258. });
  4259. svr.wait_until_ready();
  4260. Client cli(HOST, PORT);
  4261. auto res = cli.Get("/role");
  4262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4263. EXPECT_EQ(StatusCode::OK_200, res->status);
  4264. EXPECT_EQ("admin", res->body);
  4265. }
  4266. TEST(InvalidFormatTest, StatusCode) {
  4267. Server svr;
  4268. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4269. res.set_content("Hello World!\n", "text/plain");
  4270. res.status = 9999; // Status should be a three-digit code...
  4271. });
  4272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4273. auto se = detail::scope_exit([&] {
  4274. svr.stop();
  4275. thread.join();
  4276. ASSERT_FALSE(svr.is_running());
  4277. });
  4278. svr.wait_until_ready();
  4279. {
  4280. Client cli(HOST, PORT);
  4281. auto res = cli.Get("/hi");
  4282. ASSERT_FALSE(res);
  4283. }
  4284. }
  4285. TEST(URLFragmentTest, WithFragment) {
  4286. Server svr;
  4287. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4288. EXPECT_TRUE(req.target == "/hi");
  4289. });
  4290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4291. auto se = detail::scope_exit([&] {
  4292. svr.stop();
  4293. thread.join();
  4294. ASSERT_FALSE(svr.is_running());
  4295. });
  4296. svr.wait_until_ready();
  4297. {
  4298. Client cli(HOST, PORT);
  4299. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4300. EXPECT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. res = cli.Get("/hi%23key1=val1=key2=val2");
  4303. EXPECT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4305. }
  4306. }
  4307. TEST(HeaderWriter, SetHeaderWriter) {
  4308. Server svr;
  4309. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4310. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4311. return detail::write_headers(strm, hdrs);
  4312. });
  4313. svr.Get("/hi", [](const Request &req, Response &res) {
  4314. auto it = req.headers.find("CustomClientHeader");
  4315. EXPECT_TRUE(it != req.headers.end());
  4316. EXPECT_EQ(it->second, "CustomClientValue");
  4317. res.set_content("Hello World!\n", "text/plain");
  4318. });
  4319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4320. auto se = detail::scope_exit([&] {
  4321. svr.stop();
  4322. thread.join();
  4323. ASSERT_FALSE(svr.is_running());
  4324. });
  4325. svr.wait_until_ready();
  4326. {
  4327. Client cli(HOST, PORT);
  4328. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4329. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4330. return detail::write_headers(strm, hdrs);
  4331. });
  4332. auto res = cli.Get("/hi");
  4333. EXPECT_TRUE(res);
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. auto it = res->headers.find("CustomServerHeader");
  4336. EXPECT_TRUE(it != res->headers.end());
  4337. EXPECT_EQ(it->second, "CustomServerValue");
  4338. }
  4339. }
  4340. class ServerTest : public ::testing::Test {
  4341. protected:
  4342. ServerTest()
  4343. : cli_(HOST, PORT)
  4344. #ifdef CPPHTTPLIB_SSL_ENABLED
  4345. ,
  4346. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4347. #endif
  4348. {
  4349. #ifdef CPPHTTPLIB_SSL_ENABLED
  4350. cli_.enable_server_certificate_verification(false);
  4351. #endif
  4352. // Allow LARGE_DATA (100MB) responses
  4353. cli_.set_payload_max_length(200 * 1024 * 1024);
  4354. }
  4355. virtual void SetUp() {
  4356. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4357. svr_.set_payload_max_length(200 * 1024 * 1024);
  4358. svr_.set_mount_point("/", "./www");
  4359. svr_.set_mount_point("/mount", "./www2");
  4360. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4361. svr_.Get("/hi",
  4362. [&](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!", "text/plain");
  4364. })
  4365. .Get("/file_content",
  4366. [&](const Request & /*req*/, Response &res) {
  4367. res.set_file_content("./www/dir/test.html");
  4368. })
  4369. .Get("/file_content_with_content_type",
  4370. [&](const Request & /*req*/, Response &res) {
  4371. res.set_file_content("./www/file", "text/plain");
  4372. })
  4373. .Get("/invalid_file_content",
  4374. [&](const Request & /*req*/, Response &res) {
  4375. res.set_file_content("./www/dir/invalid_file_path");
  4376. })
  4377. .Get("/http_response_splitting",
  4378. [&](const Request & /*req*/, Response &res) {
  4379. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4380. EXPECT_EQ(0U, res.headers.size());
  4381. EXPECT_FALSE(res.has_header("a"));
  4382. res.set_header("a", "1\nSet-Cookie: a=1");
  4383. EXPECT_EQ(0U, res.headers.size());
  4384. EXPECT_FALSE(res.has_header("a"));
  4385. res.set_header("a", "1\rSet-Cookie: a=1");
  4386. EXPECT_EQ(0U, res.headers.size());
  4387. EXPECT_FALSE(res.has_header("a"));
  4388. res.set_header("a\r\nb", "0");
  4389. EXPECT_EQ(0U, res.headers.size());
  4390. EXPECT_FALSE(res.has_header("a"));
  4391. res.set_header("a\rb", "0");
  4392. EXPECT_EQ(0U, res.headers.size());
  4393. EXPECT_FALSE(res.has_header("a"));
  4394. res.set_header("a\nb", "0");
  4395. EXPECT_EQ(0U, res.headers.size());
  4396. EXPECT_FALSE(res.has_header("a"));
  4397. res.set_redirect("1\r\nSet-Cookie: a=1");
  4398. EXPECT_EQ(0U, res.headers.size());
  4399. EXPECT_FALSE(res.has_header("Location"));
  4400. })
  4401. .Get("/slow",
  4402. [&](const Request & /*req*/, Response &res) {
  4403. std::this_thread::sleep_for(std::chrono::seconds(4));
  4404. res.set_content("slow", "text/plain");
  4405. })
  4406. #if 0
  4407. .Post("/slowpost",
  4408. [&](const Request & /*req*/, Response &res) {
  4409. std::this_thread::sleep_for(std::chrono::seconds(2));
  4410. res.set_content("slow", "text/plain");
  4411. })
  4412. #endif
  4413. .Get("/remote_addr",
  4414. [&](const Request &req, Response &res) {
  4415. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4416. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4417. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4418. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4419. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4420. #endif
  4421. res.set_content(req.remote_addr, "text/plain");
  4422. })
  4423. .Get("/local_addr",
  4424. [&](const Request &req, Response &res) {
  4425. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4426. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4427. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4428. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4429. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4430. #endif
  4431. auto local_addr = req.local_addr;
  4432. auto local_port = std::to_string(req.local_port);
  4433. res.set_content(local_addr.append(":").append(local_port),
  4434. "text/plain");
  4435. })
  4436. .Get("/endwith%",
  4437. [&](const Request & /*req*/, Response &res) {
  4438. res.set_content("Hello World!", "text/plain");
  4439. })
  4440. .Get("/a\\+\\+b",
  4441. [&](const Request &req, Response &res) {
  4442. ASSERT_TRUE(req.has_param("a +b"));
  4443. auto val = req.get_param_value("a +b");
  4444. res.set_content(val, "text/plain");
  4445. })
  4446. .Get("/", [&](const Request & /*req*/,
  4447. Response &res) { res.set_redirect("/hi"); })
  4448. .Post("/1",
  4449. [](const Request & /*req*/, Response &res) {
  4450. res.set_redirect("/2", StatusCode::SeeOther_303);
  4451. })
  4452. .Get("/2",
  4453. [](const Request & /*req*/, Response &res) {
  4454. res.set_content("redirected.", "text/plain");
  4455. res.status = StatusCode::OK_200;
  4456. })
  4457. .Post("/person",
  4458. [&](const Request &req, Response &res) {
  4459. if (req.has_param("name") && req.has_param("note")) {
  4460. persons_[req.get_param_value("name")] =
  4461. req.get_param_value("note");
  4462. } else {
  4463. res.status = StatusCode::BadRequest_400;
  4464. }
  4465. })
  4466. .Put("/person",
  4467. [&](const Request &req, Response &res) {
  4468. if (req.has_param("name") && req.has_param("note")) {
  4469. persons_[req.get_param_value("name")] =
  4470. req.get_param_value("note");
  4471. } else {
  4472. res.status = StatusCode::BadRequest_400;
  4473. }
  4474. })
  4475. .Get("/person/(.*)",
  4476. [&](const Request &req, Response &res) {
  4477. string name = req.matches[1];
  4478. if (persons_.find(name) != persons_.end()) {
  4479. auto note = persons_[name];
  4480. res.set_content(note, "text/plain");
  4481. } else {
  4482. res.status = StatusCode::NotFound_404;
  4483. }
  4484. })
  4485. .Delete("/person",
  4486. [&](const Request &req, Response &res) {
  4487. if (req.has_param("name")) {
  4488. string name = req.get_param_value("name");
  4489. if (persons_.find(name) != persons_.end()) {
  4490. persons_.erase(name);
  4491. res.set_content("DELETED", "text/plain");
  4492. } else {
  4493. res.status = StatusCode::NotFound_404;
  4494. }
  4495. } else {
  4496. res.status = StatusCode::BadRequest_400;
  4497. }
  4498. })
  4499. .Post("/x-www-form-urlencoded-json",
  4500. [&](const Request &req, Response &res) {
  4501. auto json = req.get_param_value("json");
  4502. ASSERT_EQ(JSON_DATA, json);
  4503. res.set_content(json, "appliation/json");
  4504. res.status = StatusCode::OK_200;
  4505. })
  4506. .Get("/streamed-chunked",
  4507. [&](const Request & /*req*/, Response &res) {
  4508. res.set_chunked_content_provider(
  4509. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4510. sink.os << "123";
  4511. sink.os << "456";
  4512. sink.os << "789";
  4513. sink.done();
  4514. return true;
  4515. });
  4516. })
  4517. .Get("/streamed-chunked-with-prohibited-trailer",
  4518. [&](const Request & /*req*/, Response &res) {
  4519. auto i = new int(0);
  4520. // Declare both a prohibited trailer (Content-Length) and an
  4521. // allowed one
  4522. res.set_header("Trailer", "Content-Length, X-Allowed");
  4523. res.set_chunked_content_provider(
  4524. "text/plain",
  4525. [i](size_t /*offset*/, DataSink &sink) {
  4526. switch (*i) {
  4527. case 0: sink.os << "123"; break;
  4528. case 1: sink.os << "456"; break;
  4529. case 2: sink.os << "789"; break;
  4530. case 3: {
  4531. sink.done_with_trailer(
  4532. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4533. } break;
  4534. }
  4535. (*i)++;
  4536. return true;
  4537. },
  4538. [i](bool success) {
  4539. EXPECT_TRUE(success);
  4540. delete i;
  4541. });
  4542. })
  4543. .Get("/streamed-chunked2",
  4544. [&](const Request & /*req*/, Response &res) {
  4545. auto i = new int(0);
  4546. res.set_chunked_content_provider(
  4547. "text/plain",
  4548. [i](size_t /*offset*/, DataSink &sink) {
  4549. switch (*i) {
  4550. case 0: sink.os << "123"; break;
  4551. case 1: sink.os << "456"; break;
  4552. case 2: sink.os << "789"; break;
  4553. case 3: sink.done(); break;
  4554. }
  4555. (*i)++;
  4556. return true;
  4557. },
  4558. [i](bool success) {
  4559. EXPECT_TRUE(success);
  4560. delete i;
  4561. });
  4562. })
  4563. .Get("/streamed-chunked-with-trailer",
  4564. [&](const Request & /*req*/, Response &res) {
  4565. auto i = new int(0);
  4566. res.set_header("Trailer", "Dummy1, Dummy2");
  4567. res.set_chunked_content_provider(
  4568. "text/plain",
  4569. [i](size_t /*offset*/, DataSink &sink) {
  4570. switch (*i) {
  4571. case 0: sink.os << "123"; break;
  4572. case 1: sink.os << "456"; break;
  4573. case 2: sink.os << "789"; break;
  4574. case 3: {
  4575. sink.done_with_trailer(
  4576. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4577. } break;
  4578. }
  4579. (*i)++;
  4580. return true;
  4581. },
  4582. [i](bool success) {
  4583. EXPECT_TRUE(success);
  4584. delete i;
  4585. });
  4586. })
  4587. .Get("/streamed",
  4588. [&](const Request & /*req*/, Response &res) {
  4589. res.set_content_provider(
  4590. 6, "text/plain",
  4591. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4592. sink.os << (offset < 3 ? "a" : "b");
  4593. return true;
  4594. });
  4595. })
  4596. .Get("/streamed-without-length",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. auto data = new std::string("abcdefg");
  4599. res.set_content_provider(
  4600. "text/plain",
  4601. [data](size_t offset, DataSink &sink) {
  4602. if (offset < data->size()) {
  4603. sink.os << data->substr(offset);
  4604. }
  4605. sink.done();
  4606. return true;
  4607. },
  4608. [data](bool success) {
  4609. EXPECT_TRUE(success);
  4610. delete data;
  4611. });
  4612. })
  4613. .Get("/streamed-with-range",
  4614. [&](const Request &req, Response &res) {
  4615. auto data = new std::string("abcdefg");
  4616. // An explicit status keeps the server from picking the 206 it
  4617. // would otherwise choose for a ranged request, so the response
  4618. // is not a partial representation.
  4619. auto status = req.get_param_value("status");
  4620. if (status == "200") {
  4621. res.status = StatusCode::OK_200;
  4622. } else if (status == "403") {
  4623. res.status = StatusCode::Forbidden_403;
  4624. }
  4625. res.set_content_provider(
  4626. data->size(), "text/plain",
  4627. [data](size_t offset, size_t length, DataSink &sink) {
  4628. size_t DATA_CHUNK_SIZE = 4;
  4629. const auto &d = *data;
  4630. auto out_len =
  4631. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4632. auto ret =
  4633. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4634. EXPECT_TRUE(ret);
  4635. return true;
  4636. },
  4637. [data, &req](bool success) {
  4638. EXPECT_EQ(success, !req.has_param("error"));
  4639. delete data;
  4640. });
  4641. })
  4642. .Get("/streamed-cancel",
  4643. [&](const Request & /*req*/, Response &res) {
  4644. res.set_content_provider(
  4645. size_t(-1), "text/plain",
  4646. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4647. sink.os << "data_chunk";
  4648. return true;
  4649. });
  4650. })
  4651. .Get("/regex-with-delimiter",
  4652. [&](const Request &req, Response & /*res*/) {
  4653. ASSERT_TRUE(req.has_param("key"));
  4654. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4655. })
  4656. .Get("/with-range",
  4657. [&](const Request & /*req*/, Response &res) {
  4658. res.set_content("abcdefg", "text/plain");
  4659. })
  4660. .Get("/test-start-time",
  4661. [&](const Request &req, Response & /*res*/) {
  4662. EXPECT_NE(req.start_time_,
  4663. std::chrono::steady_clock::time_point::min());
  4664. })
  4665. .Get("/with-range-customized-response",
  4666. [&](const Request & /*req*/, Response &res) {
  4667. res.status = StatusCode::BadRequest_400;
  4668. res.set_content(JSON_DATA, "application/json");
  4669. })
  4670. .Post("/chunked",
  4671. [&](const Request &req, Response & /*res*/) {
  4672. EXPECT_EQ(req.body, "dechunked post body");
  4673. })
  4674. .Post("/large-chunked",
  4675. [&](const Request &req, Response & /*res*/) {
  4676. std::string expected(6 * 30 * 1024u, 'a');
  4677. EXPECT_EQ(req.body, expected);
  4678. })
  4679. .Post("/multipart",
  4680. [&](const Request &req, Response & /*res*/) {
  4681. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4682. req.form.get_field_count("text2") +
  4683. req.form.get_field_count("file3") +
  4684. req.form.get_field_count("file4"));
  4685. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4686. req.form.get_file_count("file2"));
  4687. ASSERT_TRUE(!req.form.has_file("???"));
  4688. ASSERT_TRUE(!req.form.has_field("???"));
  4689. ASSERT_TRUE(req.body.empty());
  4690. {
  4691. const auto &text = req.form.get_field("text1");
  4692. EXPECT_EQ("text default", text);
  4693. }
  4694. {
  4695. const auto &text = req.form.get_field("text2");
  4696. EXPECT_EQ("aωb", text);
  4697. }
  4698. {
  4699. const auto &file = req.form.get_file("file1");
  4700. EXPECT_EQ("hello.txt", file.filename);
  4701. EXPECT_EQ("text/plain", file.content_type);
  4702. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4703. }
  4704. {
  4705. const auto &file = req.form.get_file("file2");
  4706. EXPECT_EQ("world.json", file.filename);
  4707. EXPECT_EQ("application/json", file.content_type);
  4708. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4709. }
  4710. {
  4711. const auto &text = req.form.get_field("file3");
  4712. EXPECT_EQ(0u, text.size());
  4713. }
  4714. {
  4715. const auto &text = req.form.get_field("file4");
  4716. EXPECT_EQ(0u, text.size());
  4717. }
  4718. })
  4719. .Post("/multipart/multi_file_values",
  4720. [&](const Request &req, Response & /*res*/) {
  4721. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4722. req.form.get_field_count("multi_text1"));
  4723. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4724. ASSERT_TRUE(!req.form.has_file("???"));
  4725. ASSERT_TRUE(!req.form.has_field("???"));
  4726. ASSERT_TRUE(req.body.empty());
  4727. {
  4728. const auto &text = req.form.get_field("text");
  4729. EXPECT_EQ("default text", text);
  4730. }
  4731. {
  4732. const auto &text1_values = req.form.get_fields("multi_text1");
  4733. EXPECT_EQ(2u, text1_values.size());
  4734. EXPECT_EQ("aaaaa", text1_values[0]);
  4735. EXPECT_EQ("bbbbb", text1_values[1]);
  4736. }
  4737. {
  4738. const auto &file1_values = req.form.get_files("multi_file1");
  4739. EXPECT_EQ(2u, file1_values.size());
  4740. auto file1 = file1_values[0];
  4741. EXPECT_EQ(file1.filename, "hello.txt");
  4742. EXPECT_EQ(file1.content_type, "text/plain");
  4743. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4744. auto file2 = file1_values[1];
  4745. EXPECT_EQ(file2.filename, "world.json");
  4746. EXPECT_EQ(file2.content_type, "application/json");
  4747. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4748. }
  4749. })
  4750. .Post("/empty",
  4751. [&](const Request &req, Response &res) {
  4752. EXPECT_EQ(req.body, "");
  4753. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4754. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4755. res.set_content("empty", "text/plain");
  4756. })
  4757. .Post("/empty-no-content-type",
  4758. [&](const Request &req, Response &res) {
  4759. EXPECT_EQ(req.body, "");
  4760. EXPECT_FALSE(req.has_header("Content-Type"));
  4761. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4762. res.set_content("empty-no-content-type", "text/plain");
  4763. })
  4764. .Post("/path-only",
  4765. [&](const Request &req, Response &res) {
  4766. EXPECT_EQ(req.body, "");
  4767. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4768. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4769. res.set_content("path-only", "text/plain");
  4770. })
  4771. .Post("/path-headers-only",
  4772. [&](const Request &req, Response &res) {
  4773. EXPECT_EQ(req.body, "");
  4774. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4775. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4776. EXPECT_EQ("world", req.get_header_value("hello"));
  4777. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4778. res.set_content("path-headers-only", "text/plain");
  4779. })
  4780. .Post("/post-large",
  4781. [&](const Request &req, Response &res) {
  4782. EXPECT_EQ(req.body, LARGE_DATA);
  4783. res.set_content(req.body, "text/plain");
  4784. })
  4785. .Post("/post-loopback",
  4786. [&](const Request &, Response &res,
  4787. ContentReader const &content_reader) {
  4788. std::string body;
  4789. content_reader([&](const char *data, size_t data_length) {
  4790. body.append(data, data_length);
  4791. return true;
  4792. });
  4793. res.set_content(body, "text/plain");
  4794. })
  4795. .Put("/put-loopback",
  4796. [&](const Request &, Response &res,
  4797. ContentReader const &content_reader) {
  4798. std::string body;
  4799. content_reader([&](const char *data, size_t data_length) {
  4800. body.append(data, data_length);
  4801. return true;
  4802. });
  4803. res.set_content(body, "text/plain");
  4804. })
  4805. .Patch("/patch-loopback",
  4806. [&](const Request &, Response &res,
  4807. ContentReader const &content_reader) {
  4808. std::string body;
  4809. content_reader([&](const char *data, size_t data_length) {
  4810. body.append(data, data_length);
  4811. return true;
  4812. });
  4813. res.set_content(body, "text/plain");
  4814. })
  4815. .Put("/empty-no-content-type",
  4816. [&](const Request &req, Response &res) {
  4817. EXPECT_EQ(req.body, "");
  4818. EXPECT_FALSE(req.has_header("Content-Type"));
  4819. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4820. res.set_content("empty-no-content-type", "text/plain");
  4821. })
  4822. .Put("/put",
  4823. [&](const Request &req, Response &res) {
  4824. EXPECT_EQ(req.body, "PUT");
  4825. res.set_content(req.body, "text/plain");
  4826. })
  4827. .Put("/put-large",
  4828. [&](const Request &req, Response &res) {
  4829. EXPECT_EQ(req.body, LARGE_DATA);
  4830. res.set_content(req.body, "text/plain");
  4831. })
  4832. .Patch("/patch",
  4833. [&](const Request &req, Response &res) {
  4834. EXPECT_EQ(req.body, "PATCH");
  4835. res.set_content(req.body, "text/plain");
  4836. })
  4837. .Delete("/delete",
  4838. [&](const Request & /*req*/, Response &res) {
  4839. res.set_content("DELETE", "text/plain");
  4840. })
  4841. .Delete("/delete-body",
  4842. [&](const Request &req, Response &res) {
  4843. EXPECT_EQ(req.body, "content");
  4844. res.set_content(req.body, "text/plain");
  4845. })
  4846. .Options(R"(\*)",
  4847. [&](const Request & /*req*/, Response &res) {
  4848. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4849. })
  4850. .CustomRoute("PROPFIND", "/dav/:id",
  4851. [&](const Request &req, Response &res) {
  4852. res.set_header("x-body-size",
  4853. std::to_string(req.body.size()));
  4854. res.set_header("x-matched-route", req.matched_route);
  4855. res.set_header("x-dav-id", req.path_params.at("id"));
  4856. res.status = StatusCode::MultiStatus_207;
  4857. res.set_content(req.body, "application/xml");
  4858. })
  4859. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4860. [&](const Request &req, Response &res) {
  4861. res.set_header("x-dav-match", req.matches[1]);
  4862. res.status = StatusCode::MultiStatus_207;
  4863. })
  4864. .CustomRoute("MKCOL", "/dav-mkcol",
  4865. [&](const Request &req, Response &res) {
  4866. EXPECT_TRUE(req.body.empty());
  4867. res.status = StatusCode::Created_201;
  4868. })
  4869. .CustomRoute(
  4870. "REPORT", "/dav-report",
  4871. [&](const Request & /*req*/, Response &res,
  4872. const ContentReader &content_reader) {
  4873. std::string body;
  4874. content_reader([&](const char *data, size_t data_length) {
  4875. body.append(data, data_length);
  4876. return true;
  4877. });
  4878. res.set_header("x-body-size", std::to_string(body.size()));
  4879. res.status = StatusCode::MultiStatus_207;
  4880. res.set_content(body, "application/xml");
  4881. })
  4882. .Get("/request-target",
  4883. [&](const Request &req, Response & /*res*/) {
  4884. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4885. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4886. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4887. })
  4888. .Get("/long-query-value",
  4889. [&](const Request &req, Response & /*res*/) {
  4890. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4891. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4892. })
  4893. .Get("/too-long-query-value",
  4894. [&](const Request &req, Response & /*res*/) {
  4895. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4896. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4897. })
  4898. .Get("/array-param",
  4899. [&](const Request &req, Response & /*res*/) {
  4900. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4901. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4902. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4903. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4904. })
  4905. .Get("/array-param-values",
  4906. [&](const Request &req, Response & /*res*/) {
  4907. auto values = req.get_param_values("array");
  4908. EXPECT_EQ(3u, values.size());
  4909. EXPECT_EQ("value1", values[0]);
  4910. EXPECT_EQ("value2", values[1]);
  4911. EXPECT_EQ("value3", values[2]);
  4912. auto empty = req.get_param_values("nonexistent");
  4913. EXPECT_TRUE(empty.empty());
  4914. })
  4915. .Post("/validate-no-multiple-headers",
  4916. [&](const Request &req, Response & /*res*/) {
  4917. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4918. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4919. })
  4920. .Post("/content_receiver",
  4921. [&](const Request &req, Response &res,
  4922. const ContentReader &content_reader) {
  4923. if (req.is_multipart_form_data()) {
  4924. std::vector<FormData> items;
  4925. content_reader(
  4926. [&](const FormData &file) {
  4927. items.push_back(file);
  4928. return true;
  4929. },
  4930. [&](const char *data, size_t data_length) {
  4931. items.back().content.append(data, data_length);
  4932. return true;
  4933. });
  4934. EXPECT_EQ(5u, items.size());
  4935. {
  4936. const auto &file = get_file_value(items, "text1");
  4937. EXPECT_TRUE(file.filename.empty());
  4938. EXPECT_EQ("text default", file.content);
  4939. }
  4940. {
  4941. const auto &file = get_file_value(items, "text2");
  4942. EXPECT_TRUE(file.filename.empty());
  4943. EXPECT_EQ("aωb", file.content);
  4944. }
  4945. {
  4946. const auto &file = get_file_value(items, "file1");
  4947. EXPECT_EQ("hello.txt", file.filename);
  4948. EXPECT_EQ("text/plain", file.content_type);
  4949. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4950. }
  4951. {
  4952. const auto &file = get_file_value(items, "file2");
  4953. EXPECT_EQ("world.json", file.filename);
  4954. EXPECT_EQ("application/json", file.content_type);
  4955. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4956. }
  4957. {
  4958. const auto &file = get_file_value(items, "file3");
  4959. EXPECT_TRUE(file.filename.empty());
  4960. EXPECT_EQ("application/octet-stream", file.content_type);
  4961. EXPECT_EQ(0u, file.content.size());
  4962. }
  4963. } else {
  4964. std::string body;
  4965. content_reader([&](const char *data, size_t data_length) {
  4966. EXPECT_EQ(7U, data_length);
  4967. body.append(data, data_length);
  4968. return true;
  4969. });
  4970. EXPECT_EQ(body, "content");
  4971. res.set_content(body, "text/plain");
  4972. }
  4973. })
  4974. .Put("/content_receiver",
  4975. [&](const Request & /*req*/, Response &res,
  4976. const ContentReader &content_reader) {
  4977. std::string body;
  4978. content_reader([&](const char *data, size_t data_length) {
  4979. body.append(data, data_length);
  4980. return true;
  4981. });
  4982. EXPECT_EQ(body, "content");
  4983. res.set_content(body, "text/plain");
  4984. })
  4985. .Patch("/content_receiver",
  4986. [&](const Request & /*req*/, Response &res,
  4987. const ContentReader &content_reader) {
  4988. std::string body;
  4989. content_reader([&](const char *data, size_t data_length) {
  4990. body.append(data, data_length);
  4991. return true;
  4992. });
  4993. EXPECT_EQ(body, "content");
  4994. res.set_content(body, "text/plain");
  4995. })
  4996. .Post("/query-string-and-body",
  4997. [&](const Request &req, Response & /*res*/) {
  4998. ASSERT_TRUE(req.has_param("key"));
  4999. EXPECT_EQ(req.get_param_value("key"), "value");
  5000. EXPECT_EQ(req.body, "content");
  5001. })
  5002. .Get("/last-request",
  5003. [&](const Request &req, Response & /*res*/) {
  5004. EXPECT_EQ("close", req.get_header_value("Connection"));
  5005. })
  5006. .Get(R"(/redirect/(\d+))",
  5007. [&](const Request &req, Response &res) {
  5008. auto num = std::stoi(req.matches[1]) + 1;
  5009. std::string url = "/redirect/" + std::to_string(num);
  5010. res.set_redirect(url);
  5011. })
  5012. .Post("/binary",
  5013. [&](const Request &req, Response &res) {
  5014. EXPECT_EQ(4U, req.body.size());
  5015. EXPECT_EQ("application/octet-stream",
  5016. req.get_header_value("Content-Type"));
  5017. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5018. res.set_content(req.body, "application/octet-stream");
  5019. })
  5020. .Put("/binary",
  5021. [&](const Request &req, Response &res) {
  5022. EXPECT_EQ(4U, req.body.size());
  5023. EXPECT_EQ("application/octet-stream",
  5024. req.get_header_value("Content-Type"));
  5025. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5026. res.set_content(req.body, "application/octet-stream");
  5027. })
  5028. .Patch("/binary",
  5029. [&](const Request &req, Response &res) {
  5030. EXPECT_EQ(4U, req.body.size());
  5031. EXPECT_EQ("application/octet-stream",
  5032. req.get_header_value("Content-Type"));
  5033. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5034. res.set_content(req.body, "application/octet-stream");
  5035. })
  5036. .Delete("/binary",
  5037. [&](const Request &req, Response &res) {
  5038. EXPECT_EQ(4U, req.body.size());
  5039. EXPECT_EQ("application/octet-stream",
  5040. req.get_header_value("Content-Type"));
  5041. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5042. res.set_content(req.body, "application/octet-stream");
  5043. })
  5044. .Get("/issue1772",
  5045. [&](const Request & /*req*/, Response &res) {
  5046. res.status = 401;
  5047. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5048. })
  5049. .Delete("/issue609",
  5050. [](const httplib::Request &, httplib::Response &res,
  5051. const httplib::ContentReader &) {
  5052. res.set_content("ok", "text/plain");
  5053. })
  5054. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5055. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5056. .Get("/compress",
  5057. [&](const Request & /*req*/, Response &res) {
  5058. res.set_content(
  5059. "12345678901234567890123456789012345678901234567890123456789"
  5060. "01234567890123456789012345678901234567890",
  5061. "text/plain");
  5062. })
  5063. .Get("/compress-with-charset",
  5064. [&](const Request & /*req*/, Response &res) {
  5065. res.set_content(
  5066. "12345678901234567890123456789012345678901234567890123456789"
  5067. "01234567890123456789012345678901234567890",
  5068. "application/json; charset=utf-8");
  5069. })
  5070. .Get("/nocompress",
  5071. [&](const Request & /*req*/, Response &res) {
  5072. res.set_content(
  5073. "12345678901234567890123456789012345678901234567890123456789"
  5074. "01234567890123456789012345678901234567890",
  5075. "application/octet-stream");
  5076. })
  5077. .Post("/compress-multipart",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. EXPECT_EQ(2u, req.form.fields.size());
  5080. ASSERT_TRUE(!req.form.has_field("???"));
  5081. {
  5082. const auto &text = req.form.get_field("key1");
  5083. EXPECT_EQ("test", text);
  5084. }
  5085. {
  5086. const auto &text = req.form.get_field("key2");
  5087. EXPECT_EQ("--abcdefg123", text);
  5088. }
  5089. })
  5090. #endif
  5091. ;
  5092. persons_["john"] = "programmer";
  5093. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5094. svr_.wait_until_ready();
  5095. }
  5096. virtual void TearDown() {
  5097. svr_.stop();
  5098. if (!request_threads_.empty()) {
  5099. std::this_thread::sleep_for(std::chrono::seconds(1));
  5100. for (auto &t : request_threads_) {
  5101. t.join();
  5102. }
  5103. }
  5104. t_.join();
  5105. }
  5106. map<string, string> persons_;
  5107. #ifdef CPPHTTPLIB_SSL_ENABLED
  5108. SSLClient cli_;
  5109. SSLServer svr_;
  5110. #else
  5111. Client cli_;
  5112. Server svr_;
  5113. #endif
  5114. thread t_;
  5115. std::vector<thread> request_threads_;
  5116. };
  5117. TEST_F(ServerTest, GetMethod200) {
  5118. auto res = cli_.Get("/hi");
  5119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5120. EXPECT_EQ("HTTP/1.1", res->version);
  5121. EXPECT_EQ(StatusCode::OK_200, res->status);
  5122. EXPECT_EQ("OK", res->reason);
  5123. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5124. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5125. EXPECT_EQ("Hello World!", res->body);
  5126. }
  5127. TEST_F(ServerTest, GetEmptyFile) {
  5128. auto res = cli_.Get("/empty_file");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5132. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5133. EXPECT_EQ("", res->body);
  5134. }
  5135. TEST_F(ServerTest, GetFileContent) {
  5136. auto res = cli_.Get("/file_content");
  5137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5140. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5141. EXPECT_EQ("test.html", res->body);
  5142. }
  5143. TEST_F(ServerTest, GetFileContentWithRange) {
  5144. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5147. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5148. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5149. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5150. EXPECT_EQ("est", res->body);
  5151. }
  5152. TEST_F(ServerTest, GetFileContentWithContentType) {
  5153. auto res = cli_.Get("/file_content_with_content_type");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5158. EXPECT_EQ("file\n", res->body);
  5159. }
  5160. TEST_F(ServerTest, GetInvalidFileContent) {
  5161. auto res = cli_.Get("/invalid_file_content");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5164. }
  5165. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5166. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5168. EXPECT_EQ("HTTP/1.1", res->version);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5171. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5172. EXPECT_EQ("Hello World!", res->body);
  5173. }
  5174. TEST_F(ServerTest, GetMethod302) {
  5175. auto res = cli_.Get("/");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::Found_302, res->status);
  5178. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5179. }
  5180. TEST_F(ServerTest, GetMethod302Redirect) {
  5181. cli_.set_follow_location(true);
  5182. auto res = cli_.Get("/");
  5183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. EXPECT_EQ("Hello World!", res->body);
  5186. EXPECT_EQ("/hi", res->location);
  5187. }
  5188. TEST_F(ServerTest, GetMethod404) {
  5189. auto res = cli_.Get("/invalid");
  5190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5191. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5192. }
  5193. TEST_F(ServerTest, HeadMethod200) {
  5194. auto res = cli_.Head("/hi");
  5195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5198. EXPECT_TRUE(res->body.empty());
  5199. }
  5200. TEST_F(ServerTest, HeadMethod200Static) {
  5201. auto res = cli_.Head("/mount/dir/index.html");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5205. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5206. EXPECT_TRUE(res->body.empty());
  5207. }
  5208. TEST_F(ServerTest, HeadMethod404) {
  5209. auto res = cli_.Head("/invalid");
  5210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5212. EXPECT_TRUE(res->body.empty());
  5213. }
  5214. TEST_F(ServerTest, GetMethodPersonJohn) {
  5215. auto res = cli_.Get("/person/john");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5219. EXPECT_EQ("programmer", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostMethod1) {
  5222. auto res = cli_.Get("/person/john1");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5225. res = cli_.Post("/person", "name=john1&note=coder",
  5226. "application/x-www-form-urlencoded");
  5227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5228. ASSERT_EQ(StatusCode::OK_200, res->status);
  5229. res = cli_.Get("/person/john1");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. ASSERT_EQ(StatusCode::OK_200, res->status);
  5232. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. ASSERT_EQ("coder", res->body);
  5234. }
  5235. TEST_F(ServerTest, PostMethod2) {
  5236. auto res = cli_.Get("/person/john2");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5239. Params params;
  5240. params.emplace("name", "john2");
  5241. params.emplace("note", "coder");
  5242. res = cli_.Post("/person", params);
  5243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5244. ASSERT_EQ(StatusCode::OK_200, res->status);
  5245. res = cli_.Get("/person/john2");
  5246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5247. ASSERT_EQ(StatusCode::OK_200, res->status);
  5248. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5249. ASSERT_EQ("coder", res->body);
  5250. }
  5251. TEST_F(ServerTest, PutMethod3) {
  5252. auto res = cli_.Get("/person/john3");
  5253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5254. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5255. Params params;
  5256. params.emplace("name", "john3");
  5257. params.emplace("note", "coder");
  5258. res = cli_.Put("/person", params);
  5259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5260. ASSERT_EQ(StatusCode::OK_200, res->status);
  5261. res = cli_.Get("/person/john3");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5265. ASSERT_EQ("coder", res->body);
  5266. }
  5267. TEST_F(ServerTest, DeleteMethod1) {
  5268. auto res = cli_.Get("/person/john4");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5271. Params params;
  5272. params.emplace("name", "john4");
  5273. params.emplace("note", "coder");
  5274. res = cli_.Post("/person", params);
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. ASSERT_EQ(StatusCode::OK_200, res->status);
  5277. res = cli_.Get("/person/john4");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. ASSERT_EQ(StatusCode::OK_200, res->status);
  5280. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5281. ASSERT_EQ("coder", res->body);
  5282. Params delete_params;
  5283. delete_params.emplace("name", "john4");
  5284. res = cli_.Delete("/person", delete_params);
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. ASSERT_EQ(StatusCode::OK_200, res->status);
  5287. ASSERT_EQ("DELETED", res->body);
  5288. res = cli_.Get("/person/john4");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5291. }
  5292. TEST_F(ServerTest, DeleteMethod2) {
  5293. auto res = cli_.Get("/person/john5");
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5296. Params params;
  5297. params.emplace("name", "john5");
  5298. params.emplace("note", "developer");
  5299. res = cli_.Post("/person", params);
  5300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5301. ASSERT_EQ(StatusCode::OK_200, res->status);
  5302. res = cli_.Get("/person/john5");
  5303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5304. ASSERT_EQ(StatusCode::OK_200, res->status);
  5305. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5306. ASSERT_EQ("developer", res->body);
  5307. Params delete_params;
  5308. delete_params.emplace("name", "john5");
  5309. Headers headers;
  5310. headers.emplace("Custom-Header", "test-value");
  5311. res = cli_.Delete("/person", headers, delete_params);
  5312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5313. ASSERT_EQ(StatusCode::OK_200, res->status);
  5314. ASSERT_EQ("DELETED", res->body);
  5315. res = cli_.Get("/person/john5");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5318. }
  5319. TEST_F(ServerTest, DeleteMethod3) {
  5320. auto res = cli_.Get("/person/john6");
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5323. Params params;
  5324. params.emplace("name", "john6");
  5325. params.emplace("note", "tester");
  5326. res = cli_.Post("/person", params);
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::OK_200, res->status);
  5329. res = cli_.Get("/person/john6");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. ASSERT_EQ(StatusCode::OK_200, res->status);
  5332. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. ASSERT_EQ("tester", res->body);
  5334. Params delete_params;
  5335. delete_params.emplace("name", "john6");
  5336. Headers headers;
  5337. headers.emplace("Custom-Header", "test-value");
  5338. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5340. ASSERT_EQ(StatusCode::OK_200, res->status);
  5341. ASSERT_EQ("DELETED", res->body);
  5342. res = cli_.Get("/person/john6");
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5345. }
  5346. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5347. Params params;
  5348. params.emplace("json", JSON_DATA);
  5349. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5351. ASSERT_EQ(StatusCode::OK_200, res->status);
  5352. ASSERT_EQ(JSON_DATA, res->body);
  5353. }
  5354. TEST_F(ServerTest, PostEmptyContent) {
  5355. auto res = cli_.Post("/empty", "", "text/plain");
  5356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5357. ASSERT_EQ(StatusCode::OK_200, res->status);
  5358. ASSERT_EQ("empty", res->body);
  5359. }
  5360. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5361. auto res = cli_.Post("/empty-no-content-type");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. ASSERT_EQ("empty-no-content-type", res->body);
  5365. }
  5366. TEST_F(ServerTest, PostPathOnly) {
  5367. auto res = cli_.Post("/path-only");
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. ASSERT_EQ(StatusCode::OK_200, res->status);
  5370. ASSERT_EQ("path-only", res->body);
  5371. }
  5372. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5373. auto res = cli_.Post("/path-headers-only",
  5374. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. ASSERT_EQ(StatusCode::OK_200, res->status);
  5377. ASSERT_EQ("path-headers-only", res->body);
  5378. }
  5379. TEST_F(ServerTest, PostLarge) {
  5380. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5382. ASSERT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ(LARGE_DATA, res->body);
  5384. }
  5385. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5386. auto res = cli_.Put("/empty-no-content-type");
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. ASSERT_EQ(StatusCode::OK_200, res->status);
  5389. ASSERT_EQ("empty-no-content-type", res->body);
  5390. }
  5391. TEST_F(ServerTest, GetMethodDir) {
  5392. auto res = cli_.Get("/dir/");
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5396. auto body = R"(<html>
  5397. <head>
  5398. </head>
  5399. <body>
  5400. <a href="/dir/test.html">Test</a>
  5401. <a href="/hi">hi</a>
  5402. </body>
  5403. </html>
  5404. )";
  5405. EXPECT_EQ(body, res->body);
  5406. }
  5407. TEST_F(ServerTest, GetMethodDirTest) {
  5408. auto res = cli_.Get("/dir/test.html");
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::OK_200, res->status);
  5411. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5412. EXPECT_EQ("test.html", res->body);
  5413. }
  5414. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5415. auto res = cli_.Get("/dir/../dir/test.html");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. EXPECT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5419. EXPECT_EQ("test.html", res->body);
  5420. }
  5421. TEST_F(ServerTest, GetMethodInvalidPath) {
  5422. auto res = cli_.Get("/dir/../test.html");
  5423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5425. }
  5426. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5427. auto res = cli_.Get("/../www/dir/test.html");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5430. }
  5431. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5432. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5435. }
  5436. TEST_F(ServerTest, GetMethodDirMountTest) {
  5437. auto res = cli_.Get("/mount/dir/test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::OK_200, res->status);
  5440. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5441. EXPECT_EQ("test.html", res->body);
  5442. }
  5443. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5444. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5448. EXPECT_EQ("test.html", res->body);
  5449. }
  5450. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5451. auto res = cli_.Get("/mount/dir/../test.html");
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5454. }
  5455. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5456. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5459. }
  5460. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5461. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5464. }
  5465. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5466. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5469. }
  5470. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5471. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5474. }
  5475. TEST_F(ServerTest, PostMethod303) {
  5476. auto res = cli_.Post("/1", "body", "text/plain");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5479. EXPECT_EQ("/2", res->get_header_value("Location"));
  5480. }
  5481. TEST_F(ServerTest, PostMethod303Redirect) {
  5482. cli_.set_follow_location(true);
  5483. auto res = cli_.Post("/1", "body", "text/plain");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("redirected.", res->body);
  5487. EXPECT_EQ("/2", res->location);
  5488. }
  5489. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5490. auto res = cli_.Get("/dir/test.abcde");
  5491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5494. EXPECT_EQ("abcde", res->body);
  5495. }
  5496. TEST_F(ServerTest, StaticFileRange) {
  5497. auto res =
  5498. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5500. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5501. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ(true, res->has_header("Content-Range"));
  5504. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5505. EXPECT_EQ(std::string("cd"), res->body);
  5506. }
  5507. TEST_F(ServerTest, StaticFileRanges) {
  5508. auto res = cli_.Get("/dir/test.abcde",
  5509. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5512. EXPECT_TRUE(
  5513. res->get_header_value("Content-Type")
  5514. .find(
  5515. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5516. 0);
  5517. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5518. }
  5519. TEST_F(ServerTest, StaticFileRangeHead) {
  5520. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5522. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5523. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5524. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5525. EXPECT_EQ(true, res->has_header("Content-Range"));
  5526. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5527. }
  5528. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5529. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5533. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5534. EXPECT_EQ(true, res->has_header("Content-Range"));
  5535. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5536. res->get_header_value("Content-Range"));
  5537. EXPECT_EQ("LAST\n", res->body);
  5538. }
  5539. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5540. auto res =
  5541. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5543. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5544. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5545. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5546. EXPECT_EQ(true, res->has_header("Content-Range"));
  5547. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5548. }
  5549. TEST_F(ServerTest, StaticFileBigFile) {
  5550. auto res = cli_.Get("/dir/1MB.txt");
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::OK_200, res->status);
  5553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5554. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5555. }
  5556. TEST_F(ServerTest, InvalidBaseDirMount) {
  5557. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5558. }
  5559. TEST_F(ServerTest, Binary) {
  5560. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5561. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5562. "application/octet-stream");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. ASSERT_EQ(StatusCode::OK_200, res->status);
  5565. ASSERT_EQ(4U, res->body.size());
  5566. res = cli_.Put("/binary", binary.data(), binary.size(),
  5567. "application/octet-stream");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. ASSERT_EQ(StatusCode::OK_200, res->status);
  5570. ASSERT_EQ(4U, res->body.size());
  5571. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5572. "application/octet-stream");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. ASSERT_EQ(StatusCode::OK_200, res->status);
  5575. ASSERT_EQ(4U, res->body.size());
  5576. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5577. "application/octet-stream");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. ASSERT_EQ(4U, res->body.size());
  5581. }
  5582. TEST_F(ServerTest, BinaryString) {
  5583. auto binary = std::string("\x00\x01\x02\x03", 4);
  5584. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. ASSERT_EQ(4U, res->body.size());
  5588. res = cli_.Put("/binary", binary, "application/octet-stream");
  5589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5590. ASSERT_EQ(StatusCode::OK_200, res->status);
  5591. ASSERT_EQ(4U, res->body.size());
  5592. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. ASSERT_EQ(StatusCode::OK_200, res->status);
  5595. ASSERT_EQ(4U, res->body.size());
  5596. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. ASSERT_EQ(StatusCode::OK_200, res->status);
  5599. ASSERT_EQ(4U, res->body.size());
  5600. }
  5601. TEST_F(ServerTest, EmptyRequest) {
  5602. auto res = cli_.Get("");
  5603. ASSERT_TRUE(!res);
  5604. EXPECT_EQ(Error::Connection, res.error());
  5605. }
  5606. TEST_F(ServerTest, LongRequest) {
  5607. std::string request;
  5608. for (size_t i = 0; i < 545; i++) {
  5609. request += "/TooLongRequest";
  5610. }
  5611. request += "OK";
  5612. auto res = cli_.Get(request.c_str());
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5615. }
  5616. TEST_F(ServerTest, TooLongRequest) {
  5617. std::string request;
  5618. for (size_t i = 0; i < 546; i++) {
  5619. request += "/TooLongRequest";
  5620. }
  5621. request += "_NG";
  5622. auto start = std::chrono::high_resolution_clock::now();
  5623. cli_.set_keep_alive(true);
  5624. auto res = cli_.Get(request.c_str());
  5625. auto end = std::chrono::high_resolution_clock::now();
  5626. auto elapsed =
  5627. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5628. .count();
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5631. EXPECT_LE(elapsed, 1000);
  5632. EXPECT_EQ("close", res->get_header_value("Connection"));
  5633. EXPECT_FALSE(cli_.is_socket_open());
  5634. }
  5635. TEST_F(ServerTest, AlmostTooLongRequest) {
  5636. // test for #2046 - URI length check shouldn't include other content on req
  5637. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5638. // leading /, space, HTTP/1.1)
  5639. std::string request =
  5640. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5641. auto res = cli_.Get(request.c_str());
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5644. }
  5645. TEST_F(ServerTest, LongHeader) {
  5646. Request req;
  5647. req.method = "GET";
  5648. req.path = "/hi";
  5649. std::string host_and_port;
  5650. host_and_port += HOST;
  5651. host_and_port += ":";
  5652. host_and_port += std::to_string(PORT);
  5653. req.headers.emplace("Host", host_and_port.c_str());
  5654. req.headers.emplace("Accept", "*/*");
  5655. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5656. req.headers.emplace(
  5657. "Header-Name",
  5658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5686. "@@@@@@@@@@@@@@@@");
  5687. auto res = std::make_shared<Response>();
  5688. auto error = Error::Success;
  5689. auto ret = cli_.send(req, *res, error);
  5690. ASSERT_TRUE(ret);
  5691. EXPECT_EQ(StatusCode::OK_200, res->status);
  5692. }
  5693. TEST_F(ServerTest, LongQueryValue) {
  5694. auto start = std::chrono::high_resolution_clock::now();
  5695. cli_.set_keep_alive(true);
  5696. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5697. auto end = std::chrono::high_resolution_clock::now();
  5698. auto elapsed =
  5699. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5700. .count();
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5703. EXPECT_LE(elapsed, 1000);
  5704. EXPECT_EQ("close", res->get_header_value("Connection"));
  5705. EXPECT_FALSE(cli_.is_socket_open());
  5706. }
  5707. TEST_F(ServerTest, TooLongQueryValue) {
  5708. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5709. ASSERT_FALSE(res);
  5710. EXPECT_EQ(Error::Read, res.error());
  5711. }
  5712. TEST_F(ServerTest, TooLongHeader) {
  5713. Request req;
  5714. req.method = "GET";
  5715. req.path = "/hi";
  5716. std::string host_and_port;
  5717. host_and_port += HOST;
  5718. host_and_port += ":";
  5719. host_and_port += std::to_string(PORT);
  5720. req.headers.emplace("Host", host_and_port.c_str());
  5721. req.headers.emplace("Accept", "*/*");
  5722. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5723. req.headers.emplace(
  5724. "Header-Name",
  5725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5753. "@@@@@@@@@@@@@@@@@");
  5754. auto res = std::make_shared<Response>();
  5755. auto error = Error::Success;
  5756. auto ret = cli_.send(req, *res, error);
  5757. ASSERT_TRUE(ret);
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. }
  5760. TEST_F(ServerTest, HeaderCountAtLimit) {
  5761. // Test with headers just under the 100 limit
  5762. httplib::Headers headers;
  5763. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5764. // This should keep us just under the 100 header limit
  5765. for (int i = 0; i < 95; i++) {
  5766. std::string name = "X-Test-Header-" + std::to_string(i);
  5767. std::string value = "value" + std::to_string(i);
  5768. headers.emplace(name, value);
  5769. }
  5770. // This should work fine as we're under the limit
  5771. auto res = cli_.Get("/hi", headers);
  5772. EXPECT_TRUE(res);
  5773. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5774. }
  5775. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5776. // Test with many headers to exceed the 100 limit
  5777. httplib::Headers headers;
  5778. // Add 150 headers to definitely exceed the 100 limit
  5779. for (int i = 0; i < 150; i++) {
  5780. std::string name = "X-Test-Header-" + std::to_string(i);
  5781. std::string value = "value" + std::to_string(i);
  5782. headers.emplace(name, value);
  5783. }
  5784. // This should fail due to exceeding header count limit
  5785. cli_.set_keep_alive(true);
  5786. auto res = cli_.Get("/hi", headers);
  5787. // The server should respond with 400 Bad Request
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5790. EXPECT_EQ("close", res->get_header_value("Connection"));
  5791. EXPECT_FALSE(cli_.is_socket_open());
  5792. }
  5793. TEST_F(ServerTest, PercentEncoding) {
  5794. auto res = cli_.Get("/e%6edwith%");
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. TEST_F(ServerTest, PercentEncodingUnicode) {
  5799. auto res = cli_.Get("/e%u006edwith%");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. }
  5803. TEST_F(ServerTest, InvalidPercentEncoding) {
  5804. auto res = cli_.Get("/%endwith%");
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5807. }
  5808. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5809. auto res = cli_.Get("/%uendwith%");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5814. auto res = cli_.Get("/hello?aaa=bbb%");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, PlusSignEncoding) {
  5819. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ("a +b", res->body);
  5823. }
  5824. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5825. // This test simulates a potential DoS attack using many headers
  5826. // to verify our security fix prevents memory exhaustion
  5827. httplib::Headers attack_headers;
  5828. // Attempt to add many headers like an attacker would (200 headers to far
  5829. // exceed limit)
  5830. for (int i = 0; i < 200; i++) {
  5831. std::string name = "X-Attack-Header-" + std::to_string(i);
  5832. std::string value = "attack_payload_" + std::to_string(i);
  5833. attack_headers.emplace(name, value);
  5834. }
  5835. // Try to POST with excessive headers
  5836. cli_.set_keep_alive(true);
  5837. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5838. // Should either fail or return 400 Bad Request due to security limit
  5839. if (res) {
  5840. // If we get a response, it should be 400 Bad Request
  5841. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5842. EXPECT_EQ("close", res->get_header_value("Connection"));
  5843. }
  5844. EXPECT_FALSE(cli_.is_socket_open());
  5845. }
  5846. TEST_F(ServerTest, MultipartFormData) {
  5847. UploadFormDataItems items = {
  5848. {"text1", "text default", "", ""},
  5849. {"text2", "aωb", "", ""},
  5850. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5851. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5852. {"file3", "", "", "application/octet-stream"},
  5853. {"file4", "", "", " application/json tmp-string "}};
  5854. auto res = cli_.Post("/multipart", items);
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. }
  5858. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5859. UploadFormDataItems items = {
  5860. {"text", "default text", "", ""},
  5861. {"multi_text1", "aaaaa", "", ""},
  5862. {"multi_text1", "bbbbb", "", ""},
  5863. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5864. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5865. "application/json"},
  5866. };
  5867. auto res = cli_.Post("/multipart/multi_file_values", items);
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. EXPECT_EQ(StatusCode::OK_200, res->status);
  5870. }
  5871. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5872. auto res = cli_.Get("/hi");
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::OK_200, res->status);
  5875. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5876. EXPECT_EQ("Hello World!", res->body);
  5877. }
  5878. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5879. Request req;
  5880. req.method = "POST";
  5881. req.path = "/chunked";
  5882. std::string host_and_port;
  5883. host_and_port += HOST;
  5884. host_and_port += ":";
  5885. host_and_port += std::to_string(PORT);
  5886. req.headers.emplace("Host", host_and_port.c_str());
  5887. req.headers.emplace("Accept", "*/*");
  5888. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5889. req.headers.emplace("Content-Type", "text/plain");
  5890. req.headers.emplace("Content-Length", "0");
  5891. req.headers.emplace(
  5892. "Transfer-Encoding",
  5893. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5894. // Client does not chunk, so make a chunked body manually.
  5895. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5896. auto res = std::make_shared<Response>();
  5897. auto error = Error::Success;
  5898. auto ret = cli_.send(req, *res, error);
  5899. ASSERT_TRUE(ret);
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. }
  5902. template <typename ClientT>
  5903. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5904. int expected_status) {
  5905. Request req;
  5906. req.method = "POST";
  5907. req.path = "/chunked";
  5908. std::string host_and_port;
  5909. host_and_port += HOST;
  5910. host_and_port += ":";
  5911. host_and_port += std::to_string(PORT);
  5912. req.headers.emplace("Host", host_and_port.c_str());
  5913. req.headers.emplace("Content-Length", "0");
  5914. req.headers.emplace("Transfer-Encoding", "chunked");
  5915. req.body = body;
  5916. auto res = std::make_shared<Response>();
  5917. auto error = Error::Success;
  5918. ASSERT_TRUE(cli.send(req, *res, error));
  5919. EXPECT_EQ(expected_status, res->status);
  5920. }
  5921. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5922. // rather than treat them as valid lengths.
  5923. template <typename ClientT>
  5924. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5925. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5926. }
  5927. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5928. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5929. }
  5930. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5931. expect_chunked_body_rejected(
  5932. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5933. }
  5934. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5935. // chunk-size line carries no CR, LF or other control character ahead of its
  5936. // terminator. Such a line must be refused rather than read as extension text.
  5937. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5938. expect_chunked_body_rejected(
  5939. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5940. }
  5941. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  5942. expect_chunked_body_rejected(
  5943. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5944. }
  5945. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  5946. expect_chunked_body_rejected(
  5947. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5948. }
  5949. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  5950. // The literal stays split: a hex escape consumes every hex digit that
  5951. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  5952. expect_chunked_body_rejected(
  5953. cli_, "4;a\x01"
  5954. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5955. }
  5956. TEST_F(ServerTest, AcceptsChunkExtension) {
  5957. expect_chunked_body_status(cli_,
  5958. "4;name=value\r\ndech\r\n"
  5959. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  5960. "0;last\r\n\r\n",
  5961. StatusCode::OK_200);
  5962. }
  5963. TEST_F(ServerTest, GetStreamed2) {
  5964. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5966. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5967. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5968. EXPECT_EQ(true, res->has_header("Content-Range"));
  5969. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5970. EXPECT_EQ(std::string("ab"), res->body);
  5971. }
  5972. TEST_F(ServerTest, GetStreamed) {
  5973. auto res = cli_.Get("/streamed");
  5974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5975. EXPECT_EQ(StatusCode::OK_200, res->status);
  5976. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5977. EXPECT_EQ(std::string("aaabbb"), res->body);
  5978. }
  5979. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5980. auto res = cli_.Get("/streamed-without-length",
  5981. Headers{make_range_header({{0, -1}})});
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::OK_200, res->status);
  5984. EXPECT_EQ(false, res->has_header("Content-Length"));
  5985. EXPECT_EQ(false, res->has_header("Content-Range"));
  5986. EXPECT_EQ(std::string("abcdefg"), res->body);
  5987. }
  5988. TEST_F(ServerTest, GetStreamedWithRange1) {
  5989. auto res =
  5990. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5993. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5994. EXPECT_EQ(true, res->has_header("Content-Range"));
  5995. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5996. EXPECT_EQ(std::string("def"), res->body);
  5997. }
  5998. TEST_F(ServerTest, GetStreamedWithRange2) {
  5999. auto res =
  6000. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6003. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(true, res->has_header("Content-Range"));
  6005. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6006. EXPECT_EQ(std::string("bcdefg"), res->body);
  6007. }
  6008. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6009. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6012. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6013. EXPECT_EQ(true, res->has_header("Content-Range"));
  6014. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6015. EXPECT_EQ(std::string("efg"), res->body);
  6016. }
  6017. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6018. auto res =
  6019. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6022. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6023. EXPECT_EQ(false, res->has_header("Content-Range"));
  6024. EXPECT_EQ(0U, res->body.size());
  6025. }
  6026. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6027. // Only a 206 is served as a partial representation. Under any other status
  6028. // `apply_ranges()` reported the full content length, so the body must match
  6029. // that header, and the content provider must never be asked for an offset
  6030. // outside the representation.
  6031. auto check = [&](int status, const char *range) {
  6032. auto path =
  6033. std::string("/streamed-with-range?status=") + std::to_string(status);
  6034. auto ctx = path + " Range: " + range;
  6035. auto res = cli_.Get(path, Headers{{"Range", range}});
  6036. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6037. EXPECT_EQ(status, res->status) << ctx;
  6038. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6040. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6041. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6042. };
  6043. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6044. check(403, "bytes=3-5");
  6045. // The offset is far past the representation.
  6046. check(403, "bytes=100000-100200");
  6047. // `first_pos` is still -1 here, and the bounds asserts in
  6048. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6049. check(403, "bytes=-3");
  6050. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6051. // multipart branch would have written one that is empty.
  6052. check(403, "bytes=1-2, 4-5");
  6053. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6054. // covers the whole representation.
  6055. check(200, "bytes=3-5");
  6056. check(200, "bytes=1-2, 4-5");
  6057. }
  6058. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6059. auto res =
  6060. cli_.Get("/streamed-with-range",
  6061. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6062. "92233720368547758079223372036854775807"}});
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6065. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6066. EXPECT_EQ(false, res->has_header("Content-Range"));
  6067. EXPECT_EQ(0U, res->body.size());
  6068. }
  6069. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6070. auto res = cli_.Get(
  6071. "/with-range",
  6072. Headers{{"Range",
  6073. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6074. {"Accept-Encoding", ""}});
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6077. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6078. EXPECT_EQ(true, res->has_header("Content-Range"));
  6079. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6080. EXPECT_EQ(std::string("abcdefg"), res->body);
  6081. }
  6082. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6083. auto res = cli_.Get("/with-range", Headers{
  6084. {"Range", "bytes=0-"},
  6085. {"Accept-Encoding", ""},
  6086. });
  6087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6089. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6090. EXPECT_EQ(true, res->has_header("Content-Range"));
  6091. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6092. EXPECT_EQ(std::string("abcdefg"), res->body);
  6093. }
  6094. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6095. auto res = cli_.Get("/streamed-with-range",
  6096. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6099. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6100. EXPECT_EQ(false, res->has_header("Content-Range"));
  6101. EXPECT_EQ(267U, res->body.size());
  6102. // Check that both range contents are present
  6103. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6104. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6105. // Check that Content-Range headers are present for both ranges
  6106. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6107. std::string::npos);
  6108. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6109. std::string::npos);
  6110. }
  6111. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6112. Ranges ranges;
  6113. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6114. ranges.emplace_back(0, -1);
  6115. }
  6116. auto res = cli_.Get("/streamed-with-range?error",
  6117. Headers{{make_range_header(ranges)}});
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6120. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6121. EXPECT_EQ(false, res->has_header("Content-Range"));
  6122. EXPECT_EQ(0U, res->body.size());
  6123. }
  6124. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6125. auto res = cli_.Get("/streamed-with-range",
  6126. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6129. EXPECT_EQ(5U, res->body.size());
  6130. // Check that overlapping ranges are coalesced into a single range
  6131. EXPECT_EQ("bcdef", res->body);
  6132. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6133. // Should be single range, not multipart
  6134. EXPECT_TRUE(res->has_header("Content-Range"));
  6135. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6136. }
  6137. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6138. auto res = cli_.Get("/streamed-with-range",
  6139. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6142. EXPECT_EQ(268U, res->body.size());
  6143. // Check that both range contents are present
  6144. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6145. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6146. // Check that Content-Range headers are present for both ranges
  6147. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6148. std::string::npos);
  6149. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6150. std::string::npos);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6153. auto res = cli_.Get("/streamed-with-range",
  6154. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6157. EXPECT_EQ(269U, res->body.size());
  6158. // Check that both duplicate range contents are present
  6159. size_t first_abc = res->body.find("abc\r\n");
  6160. EXPECT_TRUE(first_abc != std::string::npos);
  6161. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6162. EXPECT_TRUE(second_abc != std::string::npos);
  6163. // Check that Content-Range headers are present for both ranges
  6164. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6165. EXPECT_TRUE(first_range != std::string::npos);
  6166. size_t second_range =
  6167. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6168. EXPECT_TRUE(second_range != std::string::npos);
  6169. }
  6170. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6171. auto res =
  6172. cli_.Get("/streamed-with-range?error",
  6173. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6176. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6177. EXPECT_EQ(false, res->has_header("Content-Range"));
  6178. EXPECT_EQ(0U, res->body.size());
  6179. }
  6180. TEST_F(ServerTest, GetStreamedEndless) {
  6181. uint64_t offset = 0;
  6182. auto res = cli_.Get("/streamed-cancel",
  6183. [&](const char * /*data*/, uint64_t data_length) {
  6184. if (offset < 100) {
  6185. offset += data_length;
  6186. return true;
  6187. }
  6188. return false;
  6189. });
  6190. ASSERT_TRUE(!res);
  6191. EXPECT_EQ(Error::Canceled, res.error());
  6192. }
  6193. TEST_F(ServerTest, ClientStop) {
  6194. std::atomic_size_t count{4};
  6195. std::vector<std::thread> threads;
  6196. for (auto i = count.load(); i != 0; --i) {
  6197. threads.emplace_back([&]() {
  6198. auto res = cli_.Get("/streamed-cancel",
  6199. [&](const char *, uint64_t) { return true; });
  6200. --count;
  6201. ASSERT_TRUE(!res);
  6202. EXPECT_TRUE(res.error() == Error::Canceled ||
  6203. res.error() == Error::Read || res.error() == Error::Write);
  6204. });
  6205. }
  6206. std::this_thread::sleep_for(std::chrono::seconds(2));
  6207. while (count != 0) {
  6208. cli_.stop();
  6209. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6210. }
  6211. for (auto &t : threads) {
  6212. t.join();
  6213. }
  6214. }
  6215. TEST_F(ServerTest, GetWithRange1) {
  6216. auto res = cli_.Get("/with-range", Headers{
  6217. make_range_header({{3, 5}}),
  6218. {"Accept-Encoding", ""},
  6219. });
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6222. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ(true, res->has_header("Content-Range"));
  6224. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6225. EXPECT_EQ(std::string("def"), res->body);
  6226. }
  6227. TEST_F(ServerTest, GetWithRange2) {
  6228. auto res = cli_.Get("/with-range", Headers{
  6229. make_range_header({{1, -1}}),
  6230. {"Accept-Encoding", ""},
  6231. });
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6235. EXPECT_EQ(true, res->has_header("Content-Range"));
  6236. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6237. EXPECT_EQ(std::string("bcdefg"), res->body);
  6238. }
  6239. TEST_F(ServerTest, GetWithRange3) {
  6240. auto res = cli_.Get("/with-range", Headers{
  6241. make_range_header({{0, 0}}),
  6242. {"Accept-Encoding", ""},
  6243. });
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6246. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6247. EXPECT_EQ(true, res->has_header("Content-Range"));
  6248. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6249. EXPECT_EQ(std::string("a"), res->body);
  6250. }
  6251. TEST_F(ServerTest, GetWithRange4) {
  6252. auto res = cli_.Get("/with-range", Headers{
  6253. make_range_header({{-1, 2}}),
  6254. {"Accept-Encoding", ""},
  6255. });
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6258. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6259. EXPECT_EQ(true, res->has_header("Content-Range"));
  6260. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6261. EXPECT_EQ(std::string("fg"), res->body);
  6262. }
  6263. TEST_F(ServerTest, GetWithRange5) {
  6264. auto res = cli_.Get("/with-range", Headers{
  6265. make_range_header({{0, 5}}),
  6266. {"Accept-Encoding", ""},
  6267. });
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6270. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6271. EXPECT_EQ(true, res->has_header("Content-Range"));
  6272. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6273. EXPECT_EQ(std::string("abcdef"), res->body);
  6274. }
  6275. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6276. auto res =
  6277. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6280. }
  6281. TEST_F(ServerTest, GetWithRangeMultipart) {
  6282. auto res =
  6283. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6286. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6287. EXPECT_EQ(false, res->has_header("Content-Range"));
  6288. EXPECT_EQ(267U, res->body.size());
  6289. }
  6290. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6291. auto res = cli_.Get("/with-range",
  6292. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6295. }
  6296. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6297. auto res = cli_.Get("/with-range-customized-response",
  6298. Headers{{make_range_header({{1, 2}})}});
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6301. EXPECT_EQ(true, res->has_header("Content-Length"));
  6302. EXPECT_EQ(false, res->has_header("Content-Range"));
  6303. EXPECT_EQ(JSON_DATA, res->body);
  6304. }
  6305. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6306. auto res = cli_.Get("/with-range-customized-response",
  6307. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6310. EXPECT_EQ(true, res->has_header("Content-Length"));
  6311. EXPECT_EQ(false, res->has_header("Content-Range"));
  6312. EXPECT_EQ(JSON_DATA, res->body);
  6313. }
  6314. TEST_F(ServerTest, Issue1772) {
  6315. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6317. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6318. }
  6319. TEST_F(ServerTest, Issue609) {
  6320. auto res = cli_.Delete("/issue609");
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. EXPECT_EQ(std::string("ok"), res->body);
  6324. }
  6325. TEST_F(ServerTest, GetStreamedChunked) {
  6326. auto res = cli_.Get("/streamed-chunked");
  6327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6328. EXPECT_EQ(StatusCode::OK_200, res->status);
  6329. EXPECT_EQ(std::string("123456789"), res->body);
  6330. }
  6331. TEST_F(ServerTest, GetStreamedChunked2) {
  6332. auto res = cli_.Get("/streamed-chunked2");
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. EXPECT_EQ(StatusCode::OK_200, res->status);
  6335. EXPECT_EQ(std::string("123456789"), res->body);
  6336. }
  6337. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6338. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ(std::string("123456789"), res->body);
  6342. EXPECT_TRUE(res->has_header("Trailer"));
  6343. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6344. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6345. // Trailers are now stored separately from headers (security fix)
  6346. EXPECT_EQ(2U, res->trailers.size());
  6347. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6348. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6349. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6350. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6351. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6352. // Verify trailers are NOT in headers (security verification)
  6353. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6354. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6355. }
  6356. TEST_F(ServerTest, LargeChunkedPost) {
  6357. Request req;
  6358. req.method = "POST";
  6359. req.path = "/large-chunked";
  6360. std::string host_and_port;
  6361. host_and_port += HOST;
  6362. host_and_port += ":";
  6363. host_and_port += std::to_string(PORT);
  6364. req.headers.emplace("Host", host_and_port.c_str());
  6365. req.headers.emplace("Accept", "*/*");
  6366. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6367. req.headers.emplace("Content-Type", "text/plain");
  6368. req.headers.emplace("Content-Length", "0");
  6369. req.headers.emplace("Transfer-Encoding", "chunked");
  6370. std::string long_string(30 * 1024u, 'a');
  6371. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6372. // Attempt to make a large enough post to exceed OS buffers, to test that
  6373. // the server handles short reads if the full chunk data isn't available.
  6374. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6375. auto res = std::make_shared<Response>();
  6376. auto error = Error::Success;
  6377. auto ret = cli_.send(req, *res, error);
  6378. ASSERT_TRUE(ret);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. }
  6381. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6382. auto res = cli_.Get("/remote_addr");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6386. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6387. }
  6388. TEST_F(ServerTest, GetMethodLocalAddr) {
  6389. auto res = cli_.Get("/local_addr");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6393. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6394. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6395. }
  6396. TEST_F(ServerTest, HTTPResponseSplitting) {
  6397. auto res = cli_.Get("/http_response_splitting");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::OK_200, res->status);
  6400. }
  6401. TEST_F(ServerTest, SlowRequest) {
  6402. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6403. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6404. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6405. }
  6406. #if 0
  6407. TEST_F(ServerTest, SlowPost) {
  6408. char buffer[64 * 1024];
  6409. memset(buffer, 0x42, sizeof(buffer));
  6410. auto res = cli_.Post(
  6411. "/slowpost", 64 * 1024 * 1024,
  6412. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6413. auto ret = sink.write(buffer, sizeof(buffer));
  6414. EXPECT_TRUE(ret);
  6415. return true;
  6416. },
  6417. "text/plain");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::OK_200, res->status);
  6420. }
  6421. TEST_F(ServerTest, SlowPostFail) {
  6422. char buffer[64 * 1024];
  6423. memset(buffer, 0x42, sizeof(buffer));
  6424. cli_.set_write_timeout(std::chrono::seconds(0));
  6425. auto res = cli_.Post(
  6426. "/slowpost", 64 * 1024 * 1024,
  6427. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6428. sink.write(buffer, sizeof(buffer));
  6429. return true;
  6430. },
  6431. "text/plain");
  6432. ASSERT_TRUE(!res);
  6433. EXPECT_EQ(Error::Write, res.error());
  6434. }
  6435. #endif
  6436. TEST_F(ServerTest, Put) {
  6437. auto res = cli_.Put("/put", "PUT", "text/plain");
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::OK_200, res->status);
  6440. EXPECT_EQ("PUT", res->body);
  6441. }
  6442. TEST_F(ServerTest, PutWithContentProvider) {
  6443. auto res = cli_.Put(
  6444. "/put", 3,
  6445. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6446. sink.os << "PUT";
  6447. return true;
  6448. },
  6449. "text/plain");
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. EXPECT_EQ("PUT", res->body);
  6453. }
  6454. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6455. auto res = cli_.Post(
  6456. "/post", 42,
  6457. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6458. return false;
  6459. },
  6460. "text/plain");
  6461. ASSERT_TRUE(!res);
  6462. EXPECT_EQ(Error::Canceled, res.error());
  6463. }
  6464. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6465. auto res = cli_.Put(
  6466. "/put",
  6467. [](size_t /*offset*/, DataSink &sink) {
  6468. sink.os << "PUT";
  6469. sink.done();
  6470. return true;
  6471. },
  6472. "text/plain");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::OK_200, res->status);
  6475. EXPECT_EQ("PUT", res->body);
  6476. }
  6477. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6478. auto res = cli_.Post(
  6479. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6480. "text/plain");
  6481. ASSERT_TRUE(!res);
  6482. EXPECT_EQ(Error::Canceled, res.error());
  6483. }
  6484. TEST_F(ServerTest, PostLoopBack) {
  6485. std::string body;
  6486. auto res = cli_.Post(
  6487. "/post-loopback", 9,
  6488. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6489. EXPECT_EQ(9u, length);
  6490. sink.write("123", 3);
  6491. sink.write("456", 3);
  6492. sink.write("789", 3);
  6493. return true;
  6494. },
  6495. "text/plain",
  6496. [&body](const char *data, size_t data_length) {
  6497. body.append(data, data_length);
  6498. return true;
  6499. });
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::OK_200, res->status);
  6502. EXPECT_EQ("123456789", body);
  6503. }
  6504. TEST_F(ServerTest, PutLoopBack) {
  6505. std::string body;
  6506. auto res = cli_.Put(
  6507. "/put-loopback", 9,
  6508. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6509. EXPECT_EQ(9u, length);
  6510. sink.write("123", 3);
  6511. sink.write("456", 3);
  6512. sink.write("789", 3);
  6513. return true;
  6514. },
  6515. "text/plain",
  6516. [&body](const char *data, size_t data_length) {
  6517. body.append(data, data_length);
  6518. return true;
  6519. });
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. EXPECT_EQ("123456789", body);
  6523. }
  6524. TEST_F(ServerTest, PatchLoopBack) {
  6525. std::string body;
  6526. auto res = cli_.Patch(
  6527. "/patch-loopback", 9,
  6528. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6529. EXPECT_EQ(9u, length);
  6530. sink.write("123", 3);
  6531. sink.write("456", 3);
  6532. sink.write("789", 3);
  6533. return true;
  6534. },
  6535. "text/plain",
  6536. [&body](const char *data, size_t data_length) {
  6537. body.append(data, data_length);
  6538. return true;
  6539. });
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. EXPECT_EQ("123456789", body);
  6543. }
  6544. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6545. std::string body;
  6546. auto res = cli_.Post(
  6547. "/post-loopback",
  6548. [](size_t /*offset*/, DataSink &sink) {
  6549. sink.write("123", 3);
  6550. sink.write("456", 3);
  6551. sink.write("789", 3);
  6552. sink.done();
  6553. return true;
  6554. },
  6555. "text/plain",
  6556. [&body](const char *data, size_t data_length) {
  6557. body.append(data, data_length);
  6558. return true;
  6559. });
  6560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6561. EXPECT_EQ(StatusCode::OK_200, res->status);
  6562. EXPECT_EQ("123456789", body);
  6563. }
  6564. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6565. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6566. cli_.set_compress(true);
  6567. auto res = cli_.Put(
  6568. "/put", 3,
  6569. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6570. sink.os << "PUT";
  6571. return true;
  6572. },
  6573. "text/plain");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::OK_200, res->status);
  6576. EXPECT_EQ("PUT", res->body);
  6577. }
  6578. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6579. cli_.set_compress(true);
  6580. auto res = cli_.Post(
  6581. "/post", 42,
  6582. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6583. return false;
  6584. },
  6585. "text/plain");
  6586. ASSERT_TRUE(!res);
  6587. EXPECT_EQ(Error::Canceled, res.error());
  6588. }
  6589. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6590. cli_.set_compress(true);
  6591. auto res = cli_.Put(
  6592. "/put",
  6593. [](size_t /*offset*/, DataSink &sink) {
  6594. sink.os << "PUT";
  6595. sink.done();
  6596. return true;
  6597. },
  6598. "text/plain");
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. EXPECT_EQ(StatusCode::OK_200, res->status);
  6601. EXPECT_EQ("PUT", res->body);
  6602. }
  6603. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6604. cli_.set_compress(true);
  6605. auto res = cli_.Post(
  6606. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6607. "text/plain");
  6608. ASSERT_TRUE(!res);
  6609. EXPECT_EQ(Error::Canceled, res.error());
  6610. }
  6611. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6612. cli_.set_compress(true);
  6613. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::OK_200, res->status);
  6616. EXPECT_EQ(LARGE_DATA, res->body);
  6617. }
  6618. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6619. #ifdef CPPHTTPLIB_SSL_ENABLED
  6620. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6621. Client cli(s.c_str());
  6622. cli.enable_server_certificate_verification(false);
  6623. #else
  6624. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6625. Client cli(s.c_str());
  6626. #endif
  6627. cli.set_compress(true);
  6628. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. EXPECT_EQ(StatusCode::OK_200, res->status);
  6631. EXPECT_EQ(LARGE_DATA, res->body);
  6632. // The compressed size should be less than a 10th of the original. May vary
  6633. // depending on the zlib library.
  6634. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6635. static_cast<uint64_t>(10 * 1024 * 1024));
  6636. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6637. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6638. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6639. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6640. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6641. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6642. #endif
  6643. }
  6644. TEST_F(ServerTest, PutContentWithDeflate) {
  6645. cli_.set_compress(false);
  6646. Headers headers;
  6647. headers.emplace("Content-Encoding", "deflate");
  6648. // PUT in deflate format:
  6649. auto res = cli_.Put("/put", headers,
  6650. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6652. EXPECT_EQ(StatusCode::OK_200, res->status);
  6653. EXPECT_EQ("PUT", res->body);
  6654. }
  6655. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6656. Headers headers;
  6657. headers.emplace("Accept-Encoding", "gzip, deflate");
  6658. auto res = cli_.Get("/streamed-chunked", headers);
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. EXPECT_EQ(std::string("123456789"), res->body);
  6662. }
  6663. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6664. Headers headers;
  6665. headers.emplace("Accept-Encoding", "gzip, deflate");
  6666. auto res = cli_.Get("/streamed-chunked2", headers);
  6667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6668. EXPECT_EQ(StatusCode::OK_200, res->status);
  6669. EXPECT_EQ(std::string("123456789"), res->body);
  6670. }
  6671. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6672. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. }
  6676. TEST(GzipDecompressor, ChunkedDecompression) {
  6677. std::string data;
  6678. for (size_t i = 0; i < 32 * 1024; ++i) {
  6679. data.push_back(static_cast<char>('a' + i % 26));
  6680. }
  6681. std::string compressed_data;
  6682. {
  6683. httplib::detail::gzip_compressor compressor;
  6684. bool result = compressor.compress(
  6685. data.data(), data.size(),
  6686. /*last=*/true,
  6687. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6688. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6689. compressed_data_size);
  6690. return true;
  6691. });
  6692. ASSERT_TRUE(result);
  6693. }
  6694. std::string decompressed_data;
  6695. {
  6696. httplib::detail::gzip_decompressor decompressor;
  6697. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6698. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6699. size_t chunk_size = 130;
  6700. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6701. chunk_begin += chunk_size) {
  6702. size_t current_chunk_size =
  6703. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6704. bool result = decompressor.decompress(
  6705. compressed_data.data() + chunk_begin, current_chunk_size,
  6706. [&](const char *decompressed_data_chunk,
  6707. size_t decompressed_data_chunk_size) {
  6708. decompressed_data.insert(decompressed_data.size(),
  6709. decompressed_data_chunk,
  6710. decompressed_data_chunk_size);
  6711. return true;
  6712. });
  6713. ASSERT_TRUE(result);
  6714. }
  6715. }
  6716. ASSERT_EQ(data, decompressed_data);
  6717. }
  6718. TEST(GzipDecompressor, DeflateDecompression) {
  6719. std::string original_text = "Raw deflate without gzip";
  6720. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6721. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6722. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6723. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6724. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6725. std::string decompressed_data;
  6726. {
  6727. httplib::detail::gzip_decompressor decompressor;
  6728. bool result = decompressor.decompress(
  6729. compressed_data.data(), compressed_data.size(),
  6730. [&](const char *decompressed_data_chunk,
  6731. size_t decompressed_data_chunk_size) {
  6732. decompressed_data.insert(decompressed_data.size(),
  6733. decompressed_data_chunk,
  6734. decompressed_data_chunk_size);
  6735. return true;
  6736. });
  6737. ASSERT_TRUE(result);
  6738. }
  6739. ASSERT_EQ(original_text, decompressed_data);
  6740. }
  6741. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6742. std::string original_text = "Raw deflate without gzip";
  6743. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6744. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6745. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6746. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6747. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6748. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6749. std::string decompressed_data;
  6750. {
  6751. httplib::detail::gzip_decompressor decompressor;
  6752. bool result = decompressor.decompress(
  6753. compressed_data.data(), compressed_data.size(),
  6754. [&](const char *decompressed_data_chunk,
  6755. size_t decompressed_data_chunk_size) {
  6756. decompressed_data.insert(decompressed_data.size(),
  6757. decompressed_data_chunk,
  6758. decompressed_data_chunk_size);
  6759. return true;
  6760. });
  6761. ASSERT_TRUE(result);
  6762. }
  6763. ASSERT_EQ(original_text, decompressed_data);
  6764. }
  6765. #endif
  6766. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6767. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6768. Headers headers;
  6769. headers.emplace("Accept-Encoding", "br");
  6770. auto res = cli_.Get("/streamed-chunked", headers);
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. EXPECT_EQ(std::string("123456789"), res->body);
  6774. }
  6775. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6776. Headers headers;
  6777. headers.emplace("Accept-Encoding", "br");
  6778. auto res = cli_.Get("/streamed-chunked2", headers);
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ(std::string("123456789"), res->body);
  6782. }
  6783. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6784. cli_.set_compress(true);
  6785. auto res = cli_.Put(
  6786. "/put", 3,
  6787. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6788. sink.os << "PUT";
  6789. return true;
  6790. },
  6791. "text/plain");
  6792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6793. EXPECT_EQ(StatusCode::OK_200, res->status);
  6794. EXPECT_EQ("PUT", res->body);
  6795. }
  6796. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6797. cli_.set_compress(true);
  6798. auto res = cli_.Put(
  6799. "/put",
  6800. [](size_t /*offset*/, DataSink &sink) {
  6801. sink.os << "PUT";
  6802. sink.done();
  6803. return true;
  6804. },
  6805. "text/plain");
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ("PUT", res->body);
  6809. }
  6810. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6811. cli_.set_compress(true);
  6812. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ(LARGE_DATA, res->body);
  6816. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6817. }
  6818. #endif
  6819. TEST_F(ServerTest, Patch) {
  6820. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. EXPECT_EQ(StatusCode::OK_200, res->status);
  6823. EXPECT_EQ("PATCH", res->body);
  6824. }
  6825. TEST_F(ServerTest, Delete) {
  6826. auto res = cli_.Delete("/delete");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("DELETE", res->body);
  6830. }
  6831. TEST_F(ServerTest, DeleteContentReceiver) {
  6832. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6834. EXPECT_EQ(StatusCode::OK_200, res->status);
  6835. EXPECT_EQ("content", res->body);
  6836. }
  6837. TEST_F(ServerTest, Options) {
  6838. auto res = cli_.Options("*");
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_EQ(StatusCode::OK_200, res->status);
  6841. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6842. EXPECT_TRUE(res->body.empty());
  6843. }
  6844. TEST_F(ServerTest, URL) {
  6845. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. }
  6849. TEST_F(ServerTest, ArrayParam) {
  6850. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. EXPECT_EQ(StatusCode::OK_200, res->status);
  6853. }
  6854. TEST_F(ServerTest, ArrayParamValues) {
  6855. auto res =
  6856. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::OK_200, res->status);
  6859. }
  6860. TEST_F(ServerTest, NoMultipleHeaders) {
  6861. Headers headers = {{"Content-Length", "5"}};
  6862. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6863. "text/plain");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. }
  6867. TEST_F(ServerTest, PostContentReceiver) {
  6868. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6870. ASSERT_EQ(StatusCode::OK_200, res->status);
  6871. ASSERT_EQ("content", res->body);
  6872. }
  6873. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6874. UploadFormDataItems items = {
  6875. {"text1", "text default", "", ""},
  6876. {"text2", "aωb", "", ""},
  6877. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6878. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6879. {"file3", "", "", "application/octet-stream"},
  6880. };
  6881. auto res = cli_.Post("/content_receiver", items);
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. }
  6885. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6886. UploadFormDataItems items = {
  6887. {"text1", "text default", "", ""},
  6888. {"text2", "aωb", "", ""},
  6889. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6890. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6891. {"file3", "", "", "application/octet-stream"},
  6892. };
  6893. auto boundary = std::string("+++++");
  6894. std::string body;
  6895. for (const auto &item : items) {
  6896. body += "--" + boundary + "\r\n";
  6897. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6898. if (!item.filename.empty()) {
  6899. body += "; filename=\"" + item.filename + "\"";
  6900. }
  6901. body += "\r\n";
  6902. if (!item.content_type.empty()) {
  6903. body += "Content-Type: " + item.content_type + "\r\n";
  6904. }
  6905. body += "\r\n";
  6906. body += item.content + "\r\n";
  6907. }
  6908. body += "--" + boundary + "--\r\n";
  6909. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6910. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. }
  6914. TEST(MultipartFormDataTest, FieldEscaping) {
  6915. Server svr;
  6916. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6917. const ContentReader &content_reader) {
  6918. ASSERT_TRUE(req.is_multipart_form_data());
  6919. std::vector<FormData> received;
  6920. content_reader(
  6921. [&](const FormData &file) {
  6922. received.push_back(file);
  6923. return true;
  6924. },
  6925. [&](const char *data, size_t data_length) {
  6926. received.back().content.append(data, data_length);
  6927. return true;
  6928. });
  6929. // '"', CR and LF in names and filenames are escaped following the
  6930. // WHATWG HTML standard, so each part still parses as a single part
  6931. // with no injected headers. Content types get CR/LF escaped too,
  6932. // while '"' (legal there, e.g. quoted charset) is preserved.
  6933. ASSERT_EQ(4U, received.size());
  6934. EXPECT_EQ("na%22me", received[0].name);
  6935. EXPECT_EQ("quoted name", received[0].content);
  6936. EXPECT_EQ("file", received[1].name);
  6937. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6938. received[1].filename);
  6939. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6940. EXPECT_EQ("injected", received[1].content);
  6941. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6942. EXPECT_EQ("my%22file.txt", received[2].filename);
  6943. EXPECT_EQ("cr lf name", received[2].content);
  6944. EXPECT_EQ("typed", received[3].name);
  6945. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6946. received[3].content_type);
  6947. EXPECT_EQ("typed content", received[3].content);
  6948. });
  6949. auto port = svr.bind_to_any_port("localhost");
  6950. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6951. auto se = detail::scope_exit([&] {
  6952. svr.stop();
  6953. t.join();
  6954. ASSERT_FALSE(svr.is_running());
  6955. });
  6956. svr.wait_until_ready();
  6957. Client cli("localhost", port);
  6958. UploadFormDataItems items = {
  6959. {"na\"me", "quoted name", "", ""},
  6960. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6961. "application/octet-stream"},
  6962. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6963. {"typed", "typed content", "",
  6964. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6965. };
  6966. auto res = cli.Post("/post", items);
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6971. const UploadFormDataItems items = {
  6972. {"name1", "Content 1", "", ""},
  6973. {"name2", "Content 2", "file2.txt", "text/plain"},
  6974. };
  6975. Server svr;
  6976. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6977. const ContentReader &content_reader) {
  6978. ASSERT_TRUE(req.is_multipart_form_data());
  6979. std::vector<FormData> received;
  6980. content_reader(
  6981. [&](const FormData &file) {
  6982. received.push_back(file);
  6983. return true;
  6984. },
  6985. [&](const char *data, size_t data_length) {
  6986. received.back().content.append(data, data_length);
  6987. return true;
  6988. });
  6989. ASSERT_EQ(2U, received.size());
  6990. EXPECT_EQ("name1", received[0].name);
  6991. EXPECT_EQ("Content 1", received[0].content);
  6992. EXPECT_EQ("name2", received[1].name);
  6993. EXPECT_EQ("Content 2", received[1].content);
  6994. EXPECT_EQ("file2.txt", received[1].filename);
  6995. EXPECT_EQ("text/plain", received[1].content_type);
  6996. });
  6997. auto port = svr.bind_to_any_port("localhost");
  6998. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6999. auto se = detail::scope_exit([&] {
  7000. svr.stop();
  7001. t.join();
  7002. ASSERT_FALSE(svr.is_running());
  7003. });
  7004. svr.wait_until_ready();
  7005. Client cli("localhost", port);
  7006. // Whole-body serialization with a generated boundary
  7007. {
  7008. MultipartFormDataWriter writer;
  7009. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7010. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7011. writer.content_type());
  7012. auto body = writer.serialize(items);
  7013. EXPECT_EQ(body.size(), writer.content_length(items));
  7014. auto res = cli.Post("/post", body, writer.content_type());
  7015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. }
  7018. // Per-part framing with a custom boundary via a content provider
  7019. {
  7020. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7021. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7022. MultipartFormDataWriter writer("custom-boundary_123");
  7023. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7024. std::string body;
  7025. for (const auto &item : items) {
  7026. body += writer.item_begin(item);
  7027. body += item.content;
  7028. body += MultipartFormDataWriter::item_end();
  7029. }
  7030. body += writer.finish();
  7031. EXPECT_EQ(body.size(), writer.content_length(items));
  7032. auto res = cli.Post(
  7033. "/post", body.size(),
  7034. [&](size_t offset, size_t length, DataSink &sink) {
  7035. sink.write(body.data() + offset, length);
  7036. return true;
  7037. },
  7038. writer.content_type());
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::OK_200, res->status);
  7041. }
  7042. }
  7043. TEST_F(ServerTest, PostContentReceiverGzip) {
  7044. cli_.set_compress(true);
  7045. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. ASSERT_EQ(StatusCode::OK_200, res->status);
  7048. ASSERT_EQ("content", res->body);
  7049. }
  7050. TEST_F(ServerTest, PutContentReceiver) {
  7051. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. ASSERT_EQ(StatusCode::OK_200, res->status);
  7054. ASSERT_EQ("content", res->body);
  7055. }
  7056. TEST_F(ServerTest, PatchContentReceiver) {
  7057. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7059. ASSERT_EQ(StatusCode::OK_200, res->status);
  7060. ASSERT_EQ("content", res->body);
  7061. }
  7062. template <typename ClientType>
  7063. void TestWithHeadersAndContentReceiver(
  7064. ClientType &cli,
  7065. std::function<Result(ClientType &, const std::string &, const Headers &,
  7066. const std::string &, const std::string &,
  7067. ContentReceiver, DownloadProgress)>
  7068. request_func) {
  7069. Headers headers;
  7070. headers.emplace("X-Custom-Header", "test-value");
  7071. std::string received_body;
  7072. auto res = request_func(
  7073. cli, "/content_receiver", headers, "content", "application/json",
  7074. [&](const char *data, size_t data_length) {
  7075. received_body.append(data, data_length);
  7076. return true;
  7077. },
  7078. nullptr);
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ("content", received_body);
  7082. }
  7083. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7084. #ifdef CPPHTTPLIB_SSL_ENABLED
  7085. using ClientT = SSLClient;
  7086. #else
  7087. using ClientT = Client;
  7088. #endif
  7089. TestWithHeadersAndContentReceiver<ClientT>(
  7090. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7091. const std::string &body, const std::string &content_type,
  7092. ContentReceiver receiver, DownloadProgress progress) {
  7093. return cli.Post(path, headers, body, content_type, receiver, progress);
  7094. });
  7095. }
  7096. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7097. #ifdef CPPHTTPLIB_SSL_ENABLED
  7098. using ClientT = SSLClient;
  7099. #else
  7100. using ClientT = Client;
  7101. #endif
  7102. TestWithHeadersAndContentReceiver<ClientT>(
  7103. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7104. const std::string &body, const std::string &content_type,
  7105. ContentReceiver receiver, DownloadProgress progress) {
  7106. return cli.Put(path, headers, body, content_type, receiver, progress);
  7107. });
  7108. }
  7109. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7110. #ifdef CPPHTTPLIB_SSL_ENABLED
  7111. using ClientT = SSLClient;
  7112. #else
  7113. using ClientT = Client;
  7114. #endif
  7115. TestWithHeadersAndContentReceiver<ClientT>(
  7116. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7117. const std::string &body, const std::string &content_type,
  7118. ContentReceiver receiver, DownloadProgress progress) {
  7119. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7120. });
  7121. }
  7122. template <typename ClientType>
  7123. void TestWithHeadersAndContentReceiverWithProgress(
  7124. ClientType &cli,
  7125. std::function<Result(ClientType &, const std::string &, const Headers &,
  7126. const std::string &, const std::string &,
  7127. ContentReceiver, DownloadProgress)>
  7128. request_func) {
  7129. Headers headers;
  7130. headers.emplace("X-Test-Header", "progress-test");
  7131. std::string received_body;
  7132. auto progress_called = false;
  7133. auto res = request_func(
  7134. cli, "/content_receiver", headers, "content", "text/plain",
  7135. [&](const char *data, size_t data_length) {
  7136. received_body.append(data, data_length);
  7137. return true;
  7138. },
  7139. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7140. progress_called = true;
  7141. return true;
  7142. });
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::OK_200, res->status);
  7145. EXPECT_EQ("content", received_body);
  7146. EXPECT_TRUE(progress_called);
  7147. }
  7148. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7149. #ifdef CPPHTTPLIB_SSL_ENABLED
  7150. using ClientT = SSLClient;
  7151. #else
  7152. using ClientT = Client;
  7153. #endif
  7154. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7155. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7156. const std::string &body, const std::string &content_type,
  7157. ContentReceiver receiver, DownloadProgress progress) {
  7158. return cli.Post(path, headers, body, content_type, receiver, progress);
  7159. });
  7160. }
  7161. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7162. #ifdef CPPHTTPLIB_SSL_ENABLED
  7163. using ClientT = SSLClient;
  7164. #else
  7165. using ClientT = Client;
  7166. #endif
  7167. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7168. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7169. const std::string &body, const std::string &content_type,
  7170. ContentReceiver receiver, DownloadProgress progress) {
  7171. return cli.Put(path, headers, body, content_type, receiver, progress);
  7172. });
  7173. }
  7174. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7175. #ifdef CPPHTTPLIB_SSL_ENABLED
  7176. using ClientT = SSLClient;
  7177. #else
  7178. using ClientT = Client;
  7179. #endif
  7180. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7181. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7182. const std::string &body, const std::string &content_type,
  7183. ContentReceiver receiver, DownloadProgress progress) {
  7184. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7185. });
  7186. }
  7187. template <typename ClientType>
  7188. void TestWithHeadersAndContentReceiverError(
  7189. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7190. const Headers &, const std::string &,
  7191. const std::string &, ContentReceiver)>
  7192. request_func) {
  7193. Headers headers;
  7194. headers.emplace("X-Error-Test", "true");
  7195. std::string received_body;
  7196. auto receiver_failed = false;
  7197. auto res =
  7198. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7199. [&](const char *data, size_t data_length) {
  7200. received_body.append(data, data_length);
  7201. receiver_failed = true;
  7202. return false;
  7203. });
  7204. ASSERT_FALSE(res);
  7205. EXPECT_TRUE(receiver_failed);
  7206. }
  7207. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7208. #ifdef CPPHTTPLIB_SSL_ENABLED
  7209. using ClientT = SSLClient;
  7210. #else
  7211. using ClientT = Client;
  7212. #endif
  7213. TestWithHeadersAndContentReceiverError<ClientT>(
  7214. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7215. const std::string &body, const std::string &content_type,
  7216. ContentReceiver receiver) {
  7217. return cli.Post(path, headers, body, content_type, receiver);
  7218. });
  7219. }
  7220. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7221. #ifdef CPPHTTPLIB_SSL_ENABLED
  7222. using ClientT = SSLClient;
  7223. #else
  7224. using ClientT = Client;
  7225. #endif
  7226. TestWithHeadersAndContentReceiverError<ClientT>(
  7227. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7228. const std::string &body, const std::string &content_type,
  7229. ContentReceiver receiver) {
  7230. return cli.Put(path, headers, body, content_type, receiver);
  7231. });
  7232. }
  7233. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7234. #ifdef CPPHTTPLIB_SSL_ENABLED
  7235. using ClientT = SSLClient;
  7236. #else
  7237. using ClientT = Client;
  7238. #endif
  7239. TestWithHeadersAndContentReceiverError<ClientT>(
  7240. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7241. const std::string &body, const std::string &content_type,
  7242. ContentReceiver receiver) {
  7243. return cli.Patch(path, headers, body, content_type, receiver);
  7244. });
  7245. }
  7246. TEST_F(ServerTest, PostQueryStringAndBody) {
  7247. auto res =
  7248. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. ASSERT_EQ(StatusCode::OK_200, res->status);
  7251. }
  7252. TEST_F(ServerTest, HTTP2Magic) {
  7253. Request req;
  7254. req.method = "PRI";
  7255. req.path = "*";
  7256. req.body = "SM";
  7257. auto res = std::make_shared<Response>();
  7258. auto error = Error::Success;
  7259. auto ret = cli_.send(req, *res, error);
  7260. ASSERT_TRUE(ret);
  7261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7262. }
  7263. TEST_F(ServerTest, KeepAlive) {
  7264. auto res = cli_.Get("/hi");
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::OK_200, res->status);
  7267. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7268. EXPECT_EQ("Hello World!", res->body);
  7269. res = cli_.Get("/hi");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7273. EXPECT_EQ("Hello World!", res->body);
  7274. res = cli_.Get("/hi");
  7275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7276. EXPECT_EQ(StatusCode::OK_200, res->status);
  7277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7278. EXPECT_EQ("Hello World!", res->body);
  7279. res = cli_.Get("/not-exist");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7282. res = cli_.Post("/empty", "", "text/plain");
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::OK_200, res->status);
  7285. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7286. EXPECT_EQ("empty", res->body);
  7287. EXPECT_EQ("close", res->get_header_value("Connection"));
  7288. res = cli_.Post(
  7289. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7290. "text/plain");
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::OK_200, res->status);
  7293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7294. EXPECT_EQ("empty", res->body);
  7295. cli_.set_keep_alive(false);
  7296. res = cli_.Get("/last-request");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. EXPECT_EQ("close", res->get_header_value("Connection"));
  7300. }
  7301. TEST_F(ServerTest, TooManyRedirect) {
  7302. cli_.set_follow_location(true);
  7303. auto res = cli_.Get("/redirect/0");
  7304. ASSERT_TRUE(!res);
  7305. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7306. }
  7307. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7308. Request req;
  7309. req.method = "FOOBAR";
  7310. req.path = "/hi";
  7311. cli_.set_keep_alive(true);
  7312. auto res = cli_.send(req);
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7315. EXPECT_EQ("close", res->get_header_value("Connection"));
  7316. EXPECT_FALSE(cli_.is_socket_open());
  7317. }
  7318. TEST_F(ServerTest, CustomRouteReadsBody) {
  7319. const std::string xml =
  7320. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7321. Request req;
  7322. req.method = "PROPFIND";
  7323. req.path = "/dav/dir";
  7324. req.set_header("Depth", "1");
  7325. req.body = xml;
  7326. auto res = cli_.send(req);
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7329. EXPECT_EQ(xml, res->body);
  7330. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7331. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7332. }
  7333. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7334. Request req;
  7335. req.method = "PROPFIND";
  7336. req.path = "/dav/42";
  7337. auto res = cli_.send(req);
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7340. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7341. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7342. }
  7343. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7344. Request req;
  7345. req.method = "PROPFIND";
  7346. req.path = "/dav-re/123";
  7347. auto res = cli_.send(req);
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7350. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7351. }
  7352. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7353. Request req;
  7354. req.method = "MKCOL";
  7355. req.path = "/dav-mkcol";
  7356. auto res = cli_.send(req);
  7357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7358. EXPECT_EQ(StatusCode::Created_201, res->status);
  7359. }
  7360. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7361. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7362. Request req;
  7363. req.method = "REPORT";
  7364. req.path = "/dav-report";
  7365. req.body = xml;
  7366. auto res = cli_.send(req);
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7369. EXPECT_EQ(xml, res->body);
  7370. }
  7371. // A content reader route must fire even when the request carries no body,
  7372. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7373. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7374. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7375. Request req;
  7376. req.method = "REPORT";
  7377. req.path = "/dav-report";
  7378. auto res = cli_.send(req);
  7379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7380. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7381. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7382. }
  7383. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7384. Request req;
  7385. req.method = "PROPFIND";
  7386. req.path = "/not-dav";
  7387. auto res = cli_.send(req);
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7390. }
  7391. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7392. Request req;
  7393. req.method = "UNLOCK";
  7394. req.path = "/dav/dir";
  7395. cli_.set_keep_alive(true);
  7396. auto res = cli_.send(req);
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7399. EXPECT_EQ("close", res->get_header_value("Connection"));
  7400. EXPECT_FALSE(cli_.is_socket_open());
  7401. }
  7402. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7403. // The mount point serves this path, but only for GET and HEAD.
  7404. auto get_res = cli_.Get("/dir/index.html");
  7405. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7406. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7407. Request req;
  7408. req.method = "PROPFIND";
  7409. req.path = "/dir/index.html";
  7410. auto res = cli_.send(req);
  7411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7413. }
  7414. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7415. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7416. cli_.set_keep_alive(true);
  7417. for (auto i = 0; i < 2; i++) {
  7418. Request req;
  7419. req.method = "PROPFIND";
  7420. req.path = "/dav/dir";
  7421. req.body = xml;
  7422. auto res = cli_.send(req);
  7423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7424. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7425. EXPECT_EQ(xml, res->body);
  7426. EXPECT_TRUE(cli_.is_socket_open());
  7427. }
  7428. // A built-in method must still be served on the same connection.
  7429. cli_.set_keep_alive(false);
  7430. auto res = cli_.Get("/hi");
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_EQ(StatusCode::OK_200, res->status);
  7433. EXPECT_EQ("close", res->get_header_value("Connection"));
  7434. }
  7435. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7436. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7437. Request req;
  7438. req.method = "PROPFIND";
  7439. req.path = "/dav/dir";
  7440. req.set_header("Expect", "100-continue");
  7441. req.body = xml;
  7442. auto res = cli_.send(req);
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7445. EXPECT_EQ(xml, res->body);
  7446. }
  7447. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7448. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7449. TEST_F(ServerTest, Gzip) {
  7450. Headers headers;
  7451. headers.emplace("Accept-Encoding", "gzip, deflate");
  7452. auto res = cli_.Get("/compress", headers);
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7456. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7457. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7458. "7890123456789012345678901234567890",
  7459. res->body);
  7460. EXPECT_EQ(StatusCode::OK_200, res->status);
  7461. }
  7462. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7463. Headers headers;
  7464. headers.emplace("Accept-Encoding", "gzip, deflate");
  7465. auto res = cli_.Get("/compress-with-charset", headers);
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7468. EXPECT_EQ("application/json; charset=utf-8",
  7469. res->get_header_value("Content-Type"));
  7470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7471. "7890123456789012345678901234567890",
  7472. res->body);
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. }
  7475. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7476. Headers headers;
  7477. headers.emplace("Accept-Encoding", "");
  7478. auto res = cli_.Get("/compress", headers);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7482. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7483. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7484. "7890123456789012345678901234567890",
  7485. res->body);
  7486. EXPECT_EQ(StatusCode::OK_200, res->status);
  7487. }
  7488. TEST_F(ServerTest, GzipWithContentReceiver) {
  7489. Headers headers;
  7490. headers.emplace("Accept-Encoding", "gzip, deflate");
  7491. std::string body;
  7492. auto res = cli_.Get("/compress", headers,
  7493. [&](const char *data, uint64_t data_length) {
  7494. EXPECT_EQ(100U, data_length);
  7495. body.append(data, data_length);
  7496. return true;
  7497. });
  7498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7499. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7501. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7503. "7890123456789012345678901234567890",
  7504. body);
  7505. EXPECT_EQ(StatusCode::OK_200, res->status);
  7506. }
  7507. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7508. Headers headers;
  7509. headers.emplace("Accept-Encoding", "gzip, deflate");
  7510. cli_.set_decompress(false);
  7511. auto res = cli_.Get("/compress", headers);
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7515. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7516. EXPECT_EQ(33U, res->body.size());
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. }
  7519. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7520. Headers headers;
  7521. headers.emplace("Accept-Encoding", "");
  7522. std::string body;
  7523. auto res = cli_.Get("/compress", headers,
  7524. [&](const char *data, uint64_t data_length) {
  7525. EXPECT_EQ(100U, data_length);
  7526. body.append(data, data_length);
  7527. return true;
  7528. });
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7531. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7532. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7533. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7534. "7890123456789012345678901234567890",
  7535. body);
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. }
  7538. TEST_F(ServerTest, NoGzip) {
  7539. Headers headers;
  7540. headers.emplace("Accept-Encoding", "gzip, deflate");
  7541. auto res = cli_.Get("/nocompress", headers);
  7542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7543. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7544. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7545. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7546. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7547. "7890123456789012345678901234567890",
  7548. res->body);
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. }
  7551. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7552. Headers headers;
  7553. headers.emplace("Accept-Encoding", "gzip, deflate");
  7554. std::string body;
  7555. auto res = cli_.Get("/nocompress", headers,
  7556. [&](const char *data, uint64_t data_length) {
  7557. EXPECT_EQ(100U, data_length);
  7558. body.append(data, data_length);
  7559. return true;
  7560. });
  7561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7562. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7563. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7564. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7565. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7566. "7890123456789012345678901234567890",
  7567. body);
  7568. EXPECT_EQ(StatusCode::OK_200, res->status);
  7569. }
  7570. TEST_F(ServerTest, MultipartFormDataGzip) {
  7571. UploadFormDataItems items = {
  7572. {"key1", "test", "", ""},
  7573. {"key2", "--abcdefg123", "", ""},
  7574. };
  7575. cli_.set_compress(true);
  7576. auto res = cli_.Post("/compress-multipart", items);
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. #endif
  7581. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7582. // Static file compression is opt-in, so these run their own server rather than
  7583. // flipping it on for the shared ServerTest fixture, which would silently
  7584. // rewrite what every other static file test is asserting.
  7585. class StaticFileCompressionTest : public ::testing::Test {
  7586. protected:
  7587. void TearDown() override {
  7588. if (t_.joinable()) {
  7589. svr_.stop();
  7590. t_.join();
  7591. }
  7592. }
  7593. int start(const std::function<void(Server &)> &configure = nullptr) {
  7594. // Serves the same tree as a directory of build-time compressed assets
  7595. // would be served: the mount point names the coding the files are already
  7596. // stored in. Registered before "/" so it is the one that matches.
  7597. svr_.set_mount_point("/pre-encoded", "./www",
  7598. {{"Content-Encoding", "gzip"}});
  7599. svr_.set_mount_point("/", "./www");
  7600. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7601. res.set_file_content("./www/dir/index.html", "text/html");
  7602. });
  7603. svr_.Get("/pre-encoded-file-content",
  7604. [](const Request & /*req*/, Response &res) {
  7605. res.set_header("Content-Encoding", "gzip");
  7606. res.set_file_content("./www/dir/index.html", "text/html");
  7607. });
  7608. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7609. res.set_content_provider(
  7610. 6, "text/plain",
  7611. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7612. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7613. return true;
  7614. });
  7615. });
  7616. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7617. res.set_content_provider(
  7618. 1000, "text/plain",
  7619. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7620. if (offset < 100) {
  7621. std::string data(100, 'A');
  7622. sink.write(data.data(), data.size());
  7623. return true;
  7624. }
  7625. std::this_thread::sleep_for(std::chrono::seconds(2));
  7626. std::string data(900, 'B');
  7627. sink.write(data.data(), data.size());
  7628. return true;
  7629. });
  7630. });
  7631. if (configure) { configure(svr_); }
  7632. auto port = svr_.bind_to_any_port(HOST);
  7633. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7634. svr_.wait_until_ready();
  7635. return port;
  7636. }
  7637. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7638. // Every file under ./www except 1MB.txt is smaller than the default
  7639. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7640. // it out of the way.
  7641. static void enable_without_floor(Server &svr) {
  7642. svr.set_static_file_compression(true);
  7643. svr.set_static_file_compression_min_length(0);
  7644. }
  7645. Server svr_;
  7646. std::thread t_;
  7647. };
  7648. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7649. auto port = start();
  7650. Client cli(HOST, port);
  7651. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7653. EXPECT_EQ(StatusCode::OK_200, res->status);
  7654. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7655. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7656. EXPECT_EQ(1048576U, res->body.size());
  7657. }
  7658. TEST_F(StaticFileCompressionTest, MountPoint) {
  7659. auto port = start(enable);
  7660. Client cli(HOST, port);
  7661. cli.set_decompress(false);
  7662. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(StatusCode::OK_200, res->status);
  7665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7666. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7667. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7668. // The response stays self-delimiting: a length, not a chunked body.
  7669. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7670. EXPECT_EQ(std::to_string(res->body.size()),
  7671. res->get_header_value("Content-Length"));
  7672. EXPECT_LT(res->body.size(), 1048576U);
  7673. EXPECT_FALSE(res->body.empty());
  7674. }
  7675. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7676. auto port = start(enable);
  7677. Client cli(HOST, port);
  7678. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7682. EXPECT_EQ(1048576U, res->body.size());
  7683. }
  7684. TEST_F(StaticFileCompressionTest, FileContent) {
  7685. auto port = start(enable_without_floor);
  7686. Client cli(HOST, port);
  7687. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7692. EXPECT_EQ(104U, res->body.size());
  7693. }
  7694. // A handler that serves an already-encoded file names the coding itself. The
  7695. // file-backed path decided its coding from Accept-Encoding and the content
  7696. // type alone, so it compressed the stored bytes a second time and appended a
  7697. // second Content-Encoding field line.
  7698. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7699. auto port = start(enable_without_floor);
  7700. Client cli(HOST, port);
  7701. cli.set_decompress(false);
  7702. auto res = cli.Get("/pre-encoded-file-content",
  7703. Headers{{"Accept-Encoding", "gzip"}});
  7704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7705. EXPECT_EQ(StatusCode::OK_200, res->status);
  7706. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7707. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7708. // Vary belongs to a coding the server chose, and it chose none here.
  7709. EXPECT_FALSE(res->has_header("Vary"));
  7710. // The file travels exactly as it is stored on disk.
  7711. EXPECT_EQ(104U, res->body.size());
  7712. }
  7713. // The 1MB file clears the default floor, so this one runs the configuration a
  7714. // deployment would actually have.
  7715. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7716. auto port = start(enable);
  7717. Client cli(HOST, port);
  7718. cli.set_decompress(false);
  7719. auto res =
  7720. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7722. EXPECT_EQ(StatusCode::OK_200, res->status);
  7723. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7724. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7725. EXPECT_FALSE(res->has_header("Vary"));
  7726. EXPECT_EQ(1048576U, res->body.size());
  7727. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7728. }
  7729. TEST_F(StaticFileCompressionTest, Head) {
  7730. auto port = start(enable);
  7731. Client cli(HOST, port);
  7732. cli.set_decompress(false);
  7733. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7734. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7735. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::OK_200, res->status);
  7738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7739. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7740. // HEAD still reports the size a GET would return.
  7741. EXPECT_EQ(get->get_header_value("Content-Length"),
  7742. res->get_header_value("Content-Length"));
  7743. EXPECT_TRUE(res->body.empty());
  7744. }
  7745. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7746. auto port = start(enable);
  7747. Client cli(HOST, port);
  7748. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7749. {"Accept-Encoding", "gzip"}});
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7752. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7753. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7754. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7755. EXPECT_EQ("cd", res->body);
  7756. }
  7757. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7758. auto port = start(enable);
  7759. Client cli(HOST, port);
  7760. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7764. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7765. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7766. }
  7767. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7768. auto port = start(enable);
  7769. Client cli(HOST, port);
  7770. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7774. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7775. EXPECT_TRUE(res->body.empty());
  7776. }
  7777. TEST_F(StaticFileCompressionTest, MinLength) {
  7778. auto port = start(enable);
  7779. Client cli(HOST, port);
  7780. // 104 bytes, well under the default floor. Compressing it would add the
  7781. // gzip header and trailer to a body that already fits in one packet.
  7782. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::OK_200, res->status);
  7785. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7786. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7787. }
  7788. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7789. auto port = start([](Server &svr) {
  7790. svr.set_static_file_compression(true);
  7791. svr.set_static_file_compression_min_length(1);
  7792. });
  7793. Client cli(HOST, port);
  7794. cli.set_decompress(false);
  7795. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7798. // A 9-byte file comes back larger than it went in, because gzip's header and
  7799. // trailer outweigh anything deflate can save. That is the end of the range
  7800. // the floor exists to keep out.
  7801. EXPECT_GT(res->body.size(), 9U);
  7802. }
  7803. TEST_F(StaticFileCompressionTest, MaxLength) {
  7804. auto port = start([](Server &svr) {
  7805. svr.set_static_file_compression(true);
  7806. svr.set_static_file_compression_min_length(0);
  7807. svr.set_static_file_compression_max_length(1024);
  7808. });
  7809. Client cli(HOST, port);
  7810. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7811. // defines `small` as a macro on Windows.
  7812. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7813. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7814. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7815. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7816. // Under it: compressed.
  7817. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7818. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7819. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7820. }
  7821. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7822. auto port = start(enable_without_floor);
  7823. Client cli(HOST, port);
  7824. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7825. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7826. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7827. auto identity_etag = identity->get_header_value("ETag");
  7828. ASSERT_FALSE(identity_etag.empty());
  7829. auto gzipped =
  7830. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7831. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7832. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7833. auto gzip_etag = gzipped->get_header_value("ETag");
  7834. ASSERT_FALSE(gzip_etag.empty());
  7835. // Two representations, two validators.
  7836. EXPECT_NE(identity_etag, gzip_etag);
  7837. // Each one revalidates against the request that would produce it...
  7838. auto fresh =
  7839. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7840. {"If-None-Match", gzip_etag}});
  7841. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7842. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7843. auto fresh_identity =
  7844. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7845. {"If-None-Match", identity_etag}});
  7846. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7847. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7848. // ...and not against the other representation.
  7849. auto crossed =
  7850. cli.Get("/dir/index.html",
  7851. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7852. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7853. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7854. }
  7855. // The opt-in covers responses the server reads off disk itself. A caller's own
  7856. // known-length provider keeps its Content-Length and, more importantly, keeps
  7857. // delivering incrementally: routing it through a compressor would hold every
  7858. // write back until zlib's window filled.
  7859. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7860. auto port = start(enable);
  7861. Client cli(HOST, port);
  7862. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7866. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7867. EXPECT_EQ("aaabbb", res->body);
  7868. }
  7869. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7870. auto port = start(enable);
  7871. Client cli(HOST, port);
  7872. cli.set_read_timeout(1, 0);
  7873. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7874. Headers{{"Accept-Encoding", "gzip"}});
  7875. ASSERT_TRUE(handle.is_valid());
  7876. // The provider writes 100 bytes and then stalls for longer than the read
  7877. // timeout. Those first bytes have to arrive anyway: run the response through
  7878. // a compressor and zlib holds them until its window fills, so the read would
  7879. // come back empty instead.
  7880. char buf[256];
  7881. auto n = handle.read(buf, sizeof(buf));
  7882. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7883. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7884. }
  7885. #endif
  7886. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7887. TEST_F(ServerTest, Brotli) {
  7888. Headers headers;
  7889. headers.emplace("Accept-Encoding", "br");
  7890. auto res = cli_.Get("/compress", headers);
  7891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7892. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7893. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7894. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7895. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7896. "7890123456789012345678901234567890",
  7897. res->body);
  7898. EXPECT_EQ(StatusCode::OK_200, res->status);
  7899. }
  7900. #endif
  7901. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7902. TEST_F(ServerTest, Zstd) {
  7903. Headers headers;
  7904. headers.emplace("Accept-Encoding", "zstd");
  7905. auto res = cli_.Get("/compress", headers);
  7906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7907. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7909. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7911. "7890123456789012345678901234567890",
  7912. res->body);
  7913. EXPECT_EQ(StatusCode::OK_200, res->status);
  7914. }
  7915. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7916. Headers headers;
  7917. headers.emplace("Accept-Encoding", "");
  7918. auto res = cli_.Get("/compress", headers);
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7921. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7922. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7923. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7924. "7890123456789012345678901234567890",
  7925. res->body);
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. }
  7928. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7929. Headers headers;
  7930. headers.emplace("Accept-Encoding", "zstd");
  7931. std::string body;
  7932. auto res = cli_.Get("/compress", headers,
  7933. [&](const char *data, uint64_t data_length) {
  7934. EXPECT_EQ(100U, data_length);
  7935. body.append(data, data_length);
  7936. return true;
  7937. });
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7941. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7942. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7943. "7890123456789012345678901234567890",
  7944. body);
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. }
  7947. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7948. Headers headers;
  7949. headers.emplace("Accept-Encoding", "zstd");
  7950. cli_.set_decompress(false);
  7951. auto res = cli_.Get("/compress", headers);
  7952. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7953. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7954. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7955. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7959. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. ASSERT_EQ(26U, res->body.size());
  7962. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7963. 0);
  7964. }
  7965. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7966. Headers headers;
  7967. headers.emplace("Accept-Encoding", "");
  7968. std::string body;
  7969. auto res = cli_.Get("/compress", headers,
  7970. [&](const char *data, uint64_t data_length) {
  7971. EXPECT_EQ(100U, data_length);
  7972. body.append(data, data_length);
  7973. return true;
  7974. });
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7978. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7979. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7980. "7890123456789012345678901234567890",
  7981. body);
  7982. EXPECT_EQ(StatusCode::OK_200, res->status);
  7983. }
  7984. TEST_F(ServerTest, NoZstd) {
  7985. Headers headers;
  7986. headers.emplace("Accept-Encoding", "zstd");
  7987. auto res = cli_.Get("/nocompress", headers);
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7990. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7991. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7992. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7993. "7890123456789012345678901234567890",
  7994. res->body);
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. }
  7997. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7998. Headers headers;
  7999. headers.emplace("Accept-Encoding", "zstd");
  8000. std::string body;
  8001. auto res = cli_.Get("/nocompress", headers,
  8002. [&](const char *data, uint64_t data_length) {
  8003. EXPECT_EQ(100U, data_length);
  8004. body.append(data, data_length);
  8005. return true;
  8006. });
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8009. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8010. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8011. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8012. "7890123456789012345678901234567890",
  8013. body);
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. }
  8016. // TODO: How to enable zstd ??
  8017. TEST_F(ServerTest, MultipartFormDataZstd) {
  8018. UploadFormDataItems items = {
  8019. {"key1", "test", "", ""},
  8020. {"key2", "--abcdefg123", "", ""},
  8021. };
  8022. Headers headers;
  8023. headers.emplace("Accept-Encoding", "zstd");
  8024. cli_.set_compress(true);
  8025. auto res = cli_.Post("/compress-multipart", headers, items);
  8026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8030. Headers headers;
  8031. headers.emplace("Accept-Encoding", "zstd");
  8032. cli_.set_compress(true);
  8033. auto res = cli_.Put(
  8034. "/put", headers, 3,
  8035. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8036. sink.os << "PUT";
  8037. return true;
  8038. },
  8039. "text/plain");
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. EXPECT_EQ("PUT", res->body);
  8043. }
  8044. // Pre-compression logging tests
  8045. TEST_F(ServerTest, PreCompressionLogging) {
  8046. // Test data for compression (matches the actual /compress endpoint content)
  8047. const std::string test_content =
  8048. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8049. "3456789012345678901234567890";
  8050. // Variables to capture logging data
  8051. std::string pre_compression_body;
  8052. std::string pre_compression_content_type;
  8053. std::string pre_compression_content_encoding;
  8054. std::string post_compression_body;
  8055. std::string post_compression_content_type;
  8056. std::string post_compression_content_encoding;
  8057. // Set up pre-compression logger
  8058. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8059. const Response &res) {
  8060. pre_compression_body = res.body;
  8061. pre_compression_content_type = res.get_header_value("Content-Type");
  8062. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8063. });
  8064. // Set up post-compression logger
  8065. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8066. post_compression_body = res.body;
  8067. post_compression_content_type = res.get_header_value("Content-Type");
  8068. post_compression_content_encoding =
  8069. res.get_header_value("Content-Encoding");
  8070. });
  8071. // Test with gzip compression
  8072. Headers headers;
  8073. headers.emplace("Accept-Encoding", "gzip");
  8074. auto res = cli_.Get("/compress", headers);
  8075. // Verify response was compressed
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ(StatusCode::OK_200, res->status);
  8078. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8079. // Verify pre-compression logger captured uncompressed content
  8080. EXPECT_EQ(test_content, pre_compression_body);
  8081. EXPECT_EQ("text/plain", pre_compression_content_type);
  8082. EXPECT_TRUE(pre_compression_content_encoding
  8083. .empty()); // No encoding header before compression
  8084. // Verify post-compression logger captured compressed content
  8085. EXPECT_NE(test_content,
  8086. post_compression_body); // Should be different after compression
  8087. EXPECT_EQ("text/plain", post_compression_content_type);
  8088. EXPECT_EQ("gzip", post_compression_content_encoding);
  8089. // Verify compressed content is smaller
  8090. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8091. }
  8092. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8093. const std::string test_content =
  8094. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8095. "3456789012345678901234567890";
  8096. std::string pre_compression_body;
  8097. std::string post_compression_body;
  8098. svr_.set_pre_compression_logger(
  8099. [&](const Request & /*req*/, const Response &res) {
  8100. pre_compression_body = res.body;
  8101. });
  8102. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8103. post_compression_body = res.body;
  8104. });
  8105. Headers headers;
  8106. headers.emplace("Accept-Encoding", "br");
  8107. auto res = cli_.Get("/compress", headers);
  8108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8109. EXPECT_EQ(StatusCode::OK_200, res->status);
  8110. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8111. // Verify pre-compression content is uncompressed
  8112. EXPECT_EQ(test_content, pre_compression_body);
  8113. // Verify post-compression content is compressed
  8114. EXPECT_NE(test_content, post_compression_body);
  8115. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8116. }
  8117. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8118. const std::string test_content =
  8119. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8120. "3456789012345678901234567890";
  8121. std::string pre_compression_body;
  8122. std::string post_compression_body;
  8123. svr_.set_pre_compression_logger(
  8124. [&](const Request & /*req*/, const Response &res) {
  8125. pre_compression_body = res.body;
  8126. });
  8127. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8128. post_compression_body = res.body;
  8129. });
  8130. // Request without compression (use /nocompress endpoint)
  8131. Headers headers;
  8132. auto res = cli_.Get("/nocompress", headers);
  8133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8134. EXPECT_EQ(StatusCode::OK_200, res->status);
  8135. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8136. // Pre-compression logger should not be called when no compression is applied
  8137. EXPECT_TRUE(
  8138. pre_compression_body.empty()); // Pre-compression logger not called
  8139. EXPECT_EQ(
  8140. test_content,
  8141. post_compression_body); // Post-compression logger captures final content
  8142. }
  8143. TEST_F(ServerTest, LoggerSeesContentLength) {
  8144. size_t logged_content_length = 0;
  8145. std::string logged_content_length_header;
  8146. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8147. logged_content_length = res.content_length_;
  8148. logged_content_length_header = res.get_header_value("Content-Length");
  8149. });
  8150. auto res = cli_.Get("/nocompress");
  8151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8152. EXPECT_EQ(StatusCode::OK_200, res->status);
  8153. EXPECT_EQ(res->body.size(), logged_content_length);
  8154. EXPECT_EQ(std::to_string(logged_content_length),
  8155. logged_content_length_header);
  8156. }
  8157. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8158. const std::string test_content =
  8159. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8160. "3456789012345678901234567890";
  8161. std::string pre_compression_body;
  8162. bool pre_logger_called = false;
  8163. // Set only pre-compression logger
  8164. svr_.set_pre_compression_logger(
  8165. [&](const Request & /*req*/, const Response &res) {
  8166. pre_compression_body = res.body;
  8167. pre_logger_called = true;
  8168. });
  8169. Headers headers;
  8170. headers.emplace("Accept-Encoding", "gzip");
  8171. auto res = cli_.Get("/compress", headers);
  8172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8173. EXPECT_EQ(StatusCode::OK_200, res->status);
  8174. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8175. // Verify pre-compression logger was called
  8176. EXPECT_TRUE(pre_logger_called);
  8177. EXPECT_EQ(test_content, pre_compression_body);
  8178. }
  8179. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8180. {
  8181. // Test with Expect: 100-continue header - success case
  8182. // Server returns 100 Continue, client sends body, server returns 200 OK
  8183. Request req;
  8184. req.method = "POST";
  8185. req.path = "/post-large";
  8186. req.set_header("Expect", "100-continue");
  8187. req.body = LARGE_DATA;
  8188. Response res;
  8189. auto error = Error::Success;
  8190. cli_.set_keep_alive(true);
  8191. auto ret = cli_.send(req, res, error);
  8192. EXPECT_TRUE(ret);
  8193. EXPECT_EQ(StatusCode::OK_200, res.status);
  8194. EXPECT_EQ(LARGE_DATA, res.body);
  8195. }
  8196. {
  8197. // Test with Expect: 100-continue header - error case
  8198. // Client should not send the body when server returns an error
  8199. Request req;
  8200. req.method = "POST";
  8201. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8202. req.set_header("Expect", "100-continue");
  8203. req.body = LARGE_DATA;
  8204. Response res;
  8205. auto error = Error::Success;
  8206. auto start = std::chrono::high_resolution_clock::now();
  8207. cli_.set_keep_alive(true);
  8208. auto ret = cli_.send(req, res, error);
  8209. auto end = std::chrono::high_resolution_clock::now();
  8210. auto elapsed =
  8211. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8212. .count();
  8213. // With Expect: 100-continue, request completes successfully but with error
  8214. EXPECT_TRUE(ret);
  8215. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8216. EXPECT_EQ("close", res.get_header_value("Connection"));
  8217. EXPECT_FALSE(cli_.is_socket_open());
  8218. EXPECT_LE(elapsed, 2000);
  8219. }
  8220. {
  8221. // Send an extra GET request to ensure error recovery without hanging
  8222. Request req;
  8223. req.method = "GET";
  8224. req.path = "/hi";
  8225. auto start = std::chrono::high_resolution_clock::now();
  8226. auto res = cli_.send(req);
  8227. auto end = std::chrono::high_resolution_clock::now();
  8228. auto elapsed =
  8229. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8230. .count();
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ(StatusCode::OK_200, res->status);
  8233. EXPECT_EQ("Hello World!", res->body);
  8234. EXPECT_LE(elapsed, 500);
  8235. }
  8236. }
  8237. TEST(ZstdDecompressor, ChunkedDecompression) {
  8238. std::string data;
  8239. for (size_t i = 0; i < 32 * 1024; ++i) {
  8240. data.push_back(static_cast<char>('a' + i % 26));
  8241. }
  8242. std::string compressed_data;
  8243. {
  8244. httplib::detail::zstd_compressor compressor;
  8245. bool result = compressor.compress(
  8246. data.data(), data.size(),
  8247. /*last=*/true,
  8248. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8249. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8250. compressed_data_size);
  8251. return true;
  8252. });
  8253. ASSERT_TRUE(result);
  8254. }
  8255. std::string decompressed_data;
  8256. {
  8257. httplib::detail::zstd_decompressor decompressor;
  8258. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8259. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8260. size_t chunk_size = 130;
  8261. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8262. chunk_begin += chunk_size) {
  8263. size_t current_chunk_size =
  8264. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8265. bool result = decompressor.decompress(
  8266. compressed_data.data() + chunk_begin, current_chunk_size,
  8267. [&](const char *decompressed_data_chunk,
  8268. size_t decompressed_data_chunk_size) {
  8269. decompressed_data.insert(decompressed_data.size(),
  8270. decompressed_data_chunk,
  8271. decompressed_data_chunk_size);
  8272. return true;
  8273. });
  8274. ASSERT_TRUE(result);
  8275. }
  8276. }
  8277. ASSERT_EQ(data, decompressed_data);
  8278. }
  8279. TEST(ZstdDecompressor, Decompress) {
  8280. std::string original_text = "Compressed with ZSTD";
  8281. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8282. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8283. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8284. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8285. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8286. std::string decompressed_data;
  8287. {
  8288. httplib::detail::zstd_decompressor decompressor;
  8289. bool result = decompressor.decompress(
  8290. compressed_data.data(), compressed_data.size(),
  8291. [&](const char *decompressed_data_chunk,
  8292. size_t decompressed_data_chunk_size) {
  8293. decompressed_data.insert(decompressed_data.size(),
  8294. decompressed_data_chunk,
  8295. decompressed_data_chunk_size);
  8296. return true;
  8297. });
  8298. ASSERT_TRUE(result);
  8299. }
  8300. ASSERT_EQ(original_text, decompressed_data);
  8301. }
  8302. #endif
  8303. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8304. // separate chunks so that the server sees each part in its own read(). Used to
  8305. // place a read boundary at a specific offset of a request body.
  8306. static bool send_request_in_parts(time_t read_timeout_sec,
  8307. const std::vector<std::string> &parts,
  8308. std::string *resp = nullptr,
  8309. int port = PORT) {
  8310. auto error = Error::Success;
  8311. auto client_sock = detail::create_client_socket(
  8312. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8313. /*connection_timeout_sec=*/5, 0,
  8314. /*read_timeout_sec=*/5, 0,
  8315. /*write_timeout_sec=*/5, 0, std::string(), error);
  8316. if (client_sock == INVALID_SOCKET) { return false; }
  8317. auto ret = detail::process_client_socket(
  8318. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8319. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8320. for (size_t i = 0; i < parts.size(); i++) {
  8321. const auto &part = parts[i];
  8322. if (part.size() !=
  8323. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8324. return false;
  8325. }
  8326. if (i + 1 < parts.size()) {
  8327. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8328. }
  8329. }
  8330. char buf[512];
  8331. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8332. while (line_reader.getline()) {
  8333. if (resp) { *resp += line_reader.ptr(); }
  8334. }
  8335. return true;
  8336. });
  8337. detail::close_socket(client_sock);
  8338. return ret;
  8339. }
  8340. // Sends a raw request to a server listening at HOST:PORT.
  8341. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8342. std::string *resp = nullptr, int port = PORT) {
  8343. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8344. }
  8345. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8346. Server svr;
  8347. std::string header_value;
  8348. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8349. header_value = req.get_header_value("foo");
  8350. res.set_content("ok", "text/plain");
  8351. });
  8352. thread t = thread([&] { svr.listen(HOST, PORT); });
  8353. auto se = detail::scope_exit([&] {
  8354. svr.stop();
  8355. t.join();
  8356. ASSERT_FALSE(svr.is_running());
  8357. });
  8358. svr.wait_until_ready();
  8359. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8360. // like characters are not treated the same - use vertical tab and escape.
  8361. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8362. "foo: \t \v bar \x1B\t \r\n"
  8363. "Connection: close\r\n"
  8364. "\r\n";
  8365. std::string res;
  8366. ASSERT_TRUE(send_request(5, req, &res));
  8367. EXPECT_EQ(header_value, "");
  8368. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8369. }
  8370. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8371. Server svr;
  8372. std::string received;
  8373. svr.Get("/order", [&](const Request &req, Response &res) {
  8374. received = entries_to_string(req.headers);
  8375. res.set_content("ok", "text/plain");
  8376. });
  8377. auto port = svr.bind_to_any_port(HOST);
  8378. thread t = thread([&] { svr.listen_after_bind(); });
  8379. auto se = detail::scope_exit([&] {
  8380. svr.stop();
  8381. t.join();
  8382. ASSERT_FALSE(svr.is_running());
  8383. });
  8384. svr.wait_until_ready();
  8385. const std::string req = "GET /order HTTP/1.1\r\n"
  8386. "X-First: 1\r\n"
  8387. "X-Dup: a\r\n"
  8388. "X-Second: 2\r\n"
  8389. "X-Dup: b\r\n"
  8390. "Connection: close\r\n"
  8391. "\r\n";
  8392. std::string res;
  8393. ASSERT_TRUE(send_request(5, req, &res, port));
  8394. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8395. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8396. }
  8397. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8398. Server svr;
  8399. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8400. res.set_header("Set-Cookie", "first=1");
  8401. res.set_header("X-Between", "y");
  8402. res.set_header("Set-Cookie", "second=2");
  8403. res.set_content("ok", "text/plain");
  8404. });
  8405. auto port = svr.bind_to_any_port(HOST);
  8406. thread t = thread([&] { svr.listen_after_bind(); });
  8407. auto se = detail::scope_exit([&] {
  8408. svr.stop();
  8409. t.join();
  8410. ASSERT_FALSE(svr.is_running());
  8411. });
  8412. svr.wait_until_ready();
  8413. Client cli(HOST, port);
  8414. auto res = cli.Get("/cookies");
  8415. ASSERT_TRUE(res);
  8416. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8417. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8418. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8419. }
  8420. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8421. Server svr;
  8422. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8423. auto i = new int(0);
  8424. res.set_header("Trailer", "X-Safe, X-Reflected");
  8425. res.set_chunked_content_provider(
  8426. "text/plain",
  8427. [i](size_t /*offset*/, DataSink &sink) {
  8428. if (*i == 0) {
  8429. sink.os << "body";
  8430. } else {
  8431. Headers trailer;
  8432. // A valid trailer that must survive.
  8433. trailer.emplace("X-Safe", "safe");
  8434. // Attacker-controlled value carrying CR/LF (response splitting).
  8435. trailer.emplace("X-Reflected",
  8436. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8437. // Attacker-controlled name carrying CR/LF.
  8438. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8439. sink.done_with_trailer(trailer);
  8440. }
  8441. (*i)++;
  8442. return true;
  8443. },
  8444. [i](bool /*success*/) { delete i; });
  8445. });
  8446. thread t = thread([&] { svr.listen(HOST, PORT); });
  8447. auto se = detail::scope_exit([&] {
  8448. svr.stop();
  8449. t.join();
  8450. ASSERT_FALSE(svr.is_running());
  8451. });
  8452. svr.wait_until_ready();
  8453. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8454. "Host: " + HOST +
  8455. "\r\n"
  8456. "Connection: close\r\n"
  8457. "\r\n";
  8458. std::string res;
  8459. ASSERT_TRUE(send_request(5, req, &res));
  8460. // The injected fields must not appear anywhere in the raw response.
  8461. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8462. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8463. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8464. // Invalid trailers are dropped entirely, matching set_header().
  8465. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8466. // The valid trailer still passes through.
  8467. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8468. }
  8469. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8470. Server svr;
  8471. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8472. // res.headers is a public field an application can populate directly,
  8473. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8474. // A valid header that must survive.
  8475. res.headers.emplace("X-Safe", "safe");
  8476. // Attacker-controlled value carrying CR/LF (response splitting).
  8477. res.headers.emplace("X-Reflected",
  8478. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8479. // Attacker-controlled name carrying CR/LF.
  8480. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8481. res.set_content("body", "text/plain");
  8482. });
  8483. thread t = thread([&] { svr.listen(HOST, PORT); });
  8484. auto se = detail::scope_exit([&] {
  8485. svr.stop();
  8486. t.join();
  8487. ASSERT_FALSE(svr.is_running());
  8488. });
  8489. svr.wait_until_ready();
  8490. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8491. "Host: " + HOST +
  8492. "\r\n"
  8493. "Connection: close\r\n"
  8494. "\r\n";
  8495. std::string res;
  8496. ASSERT_TRUE(send_request(5, req, &res));
  8497. // The injected fields must not appear anywhere in the raw response.
  8498. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8499. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8500. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8501. // Invalid headers are dropped entirely, matching set_header().
  8502. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8503. // The valid header still passes through.
  8504. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8505. }
  8506. // Forward declaration: in split builds split.py strips `inline` and moves the
  8507. // definition into httplib.cc, so detail::write_request_line is not visible from
  8508. // the public httplib.h. Re-declaring it here lets the tests link against the
  8509. // symbol in both header-only and split builds.
  8510. namespace httplib {
  8511. namespace detail {
  8512. ssize_t write_request_line(Stream &strm, const std::string &method,
  8513. const std::string &path);
  8514. } // namespace detail
  8515. } // namespace httplib
  8516. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8517. // A well-formed target is written verbatim.
  8518. {
  8519. detail::BufferStream strm;
  8520. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8521. EXPECT_GT(n, 0);
  8522. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8523. }
  8524. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8525. // otherwise it splits the request line and injects a header or a whole
  8526. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8527. // when path encoding is disabled.
  8528. const std::string evil_targets[] = {
  8529. "/a\r\nInjected: pwned",
  8530. "/a\rInjected",
  8531. "/a\nInjected",
  8532. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8533. };
  8534. for (const auto &evil : evil_targets) {
  8535. detail::BufferStream strm;
  8536. auto n = detail::write_request_line(strm, "GET", evil);
  8537. EXPECT_LT(n, 0);
  8538. EXPECT_TRUE(strm.get_buffer().empty());
  8539. }
  8540. }
  8541. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8542. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8543. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8544. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8545. // client must fail cleanly with Error::Write instead of putting a
  8546. // request-line-less, header-injecting request on the wire.
  8547. Server svr;
  8548. svr.Get("/a", [](const Request &, Response &res) {
  8549. res.set_content("ok", "text/plain");
  8550. });
  8551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8552. auto se = detail::scope_exit([&] {
  8553. svr.stop();
  8554. thread.join();
  8555. ASSERT_FALSE(svr.is_running());
  8556. });
  8557. svr.wait_until_ready();
  8558. {
  8559. Client cli(HOST, PORT);
  8560. cli.set_path_encode(false);
  8561. // The request is rejected before anything is written, so the connection
  8562. // stays silent and the subsequent response read would otherwise block for
  8563. // the full default read timeout. Shorten it -- the assertion is on the
  8564. // error, not the timeout.
  8565. cli.set_read_timeout(1, 0);
  8566. auto res = cli.Get("/a\r\nInjected: pwned");
  8567. EXPECT_FALSE(res);
  8568. EXPECT_EQ(Error::Write, res.error());
  8569. }
  8570. }
  8571. // Sends a raw request and verifies that there isn't a crash or exception.
  8572. static void test_raw_request(const std::string &req,
  8573. std::string *out = nullptr) {
  8574. Server svr;
  8575. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8576. res.set_content("ok", "text/plain");
  8577. });
  8578. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8579. res.set_content("ok", "text/plain");
  8580. });
  8581. svr.Get("/header_field_value_check",
  8582. [&](const Request & /*req*/, Response &res) {
  8583. res.set_content("ok", "text/plain");
  8584. });
  8585. svr.CustomRoute("PROPFIND", "/dav",
  8586. [&](const Request & /*req*/, Response &res) {
  8587. res.status = StatusCode::MultiStatus_207;
  8588. });
  8589. // Server read timeout must be longer than the client read timeout for the
  8590. // bug to reproduce, probably to force the server to process a request
  8591. // without a trailing blank line.
  8592. const time_t client_read_timeout_sec = 1;
  8593. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8594. bool listen_thread_ok = false;
  8595. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8596. auto se = detail::scope_exit([&] {
  8597. svr.stop();
  8598. t.join();
  8599. ASSERT_FALSE(svr.is_running());
  8600. EXPECT_TRUE(listen_thread_ok);
  8601. });
  8602. svr.wait_until_ready();
  8603. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8604. }
  8605. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8606. // A certain header line causes an exception if the header property is parsed
  8607. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8608. test_raw_request(
  8609. "GET /hi HTTP/1.1\r\n"
  8610. " : "
  8611. " "
  8612. " ");
  8613. }
  8614. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8615. // A certain header line causes an exception if the header property *name* is
  8616. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8617. // greedy matcher and requires backtracking when there are a lot of ":"
  8618. // characters.
  8619. // This occurs with libc++ but not libstdc++.
  8620. test_raw_request(
  8621. "GET /hi HTTP/1.1\r\n"
  8622. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8623. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8624. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8625. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8626. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8627. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8628. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8629. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8630. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8631. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8632. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8633. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8634. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8635. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8636. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8637. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8638. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8639. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8640. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8641. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8642. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8643. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8644. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8645. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8646. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8647. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8648. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8649. "&&&%%%");
  8650. }
  8651. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8652. // Make sure this doesn't crash the server.
  8653. // In a previous version of the header line regex, the "\r" rendered the line
  8654. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8655. // a new position where the leading white space ended and the field value
  8656. // began.
  8657. // The crash occurs with libc++ but not libstdc++.
  8658. test_raw_request("GET /hi HTTP/1.1\r\n"
  8659. "a:" +
  8660. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8661. "\r\n"
  8662. "\r\n");
  8663. }
  8664. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8665. std::string out;
  8666. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8667. "Content-Type: text/plain\r\n"
  8668. "Transfer-Encoding: chunked\r\n"
  8669. "\r\n"
  8670. "nothex\r\n",
  8671. &out);
  8672. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8673. }
  8674. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8675. std::string out;
  8676. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8677. "Content-Type: text/plain\r\n"
  8678. "Transfer-Encoding: chunked\r\n"
  8679. "\r\n"
  8680. "3\r\n"
  8681. "xyz\r\n"
  8682. "NaN\r\n",
  8683. &out);
  8684. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8685. }
  8686. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8687. std::string out;
  8688. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8689. "Content-Type: text/plain\r\n"
  8690. "Transfer-Encoding: chunked\r\n"
  8691. "\r\n"
  8692. // Length is too large for 64 bits.
  8693. "1ffffffffffffffff\r\n"
  8694. "xyz\r\n",
  8695. &out);
  8696. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8697. }
  8698. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8699. test_raw_request("GET /hi HTTP/1.1\r\n"
  8700. "Content-Type: text/plain\r\n\r");
  8701. }
  8702. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8703. std::string out;
  8704. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8705. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8706. }
  8707. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8708. Server svr;
  8709. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8710. EXPECT_TRUE(!req.remote_addr.empty());
  8711. });
  8712. thread t = thread([&] { svr.listen(HOST, PORT); });
  8713. auto se = detail::scope_exit([&] {
  8714. svr.stop();
  8715. t.join();
  8716. ASSERT_FALSE(svr.is_running());
  8717. });
  8718. svr.wait_until_ready();
  8719. // Send an invalid request line to trigger Bad Request
  8720. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8721. std::string out;
  8722. ASSERT_TRUE(send_request(5, bad_req, &out));
  8723. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8724. }
  8725. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8726. // answered right away rather than blocking on a read that waits for EOF.
  8727. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8728. std::string out;
  8729. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8730. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8731. }
  8732. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8733. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8734. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8735. for (const auto *method : methods) {
  8736. Server svr;
  8737. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8738. EXPECT_FALSE(svr.is_valid()) << method;
  8739. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8740. }
  8741. }
  8742. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8743. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8744. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8745. for (const auto *method : methods) {
  8746. Server svr;
  8747. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8748. EXPECT_FALSE(svr.is_valid()) << method;
  8749. }
  8750. }
  8751. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8752. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8753. "COPY", "MOVE", "LOCK",
  8754. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8755. Server svr;
  8756. for (const auto *method : methods) {
  8757. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8758. }
  8759. EXPECT_TRUE(svr.is_valid());
  8760. }
  8761. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8762. Server svr;
  8763. svr.CustomRoute("POST", "/x",
  8764. [](const Request &, Response &, const ContentReader &) {});
  8765. EXPECT_FALSE(svr.is_valid());
  8766. }
  8767. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8768. Server svr;
  8769. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8770. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8771. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8772. EXPECT_FALSE(svr.is_valid());
  8773. }
  8774. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8775. Server svr;
  8776. auto captured = Error::Success;
  8777. svr.set_error_logger(
  8778. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8779. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8780. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8781. }
  8782. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8783. std::string out;
  8784. std::string request(
  8785. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8786. test_raw_request(request, &out);
  8787. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8788. }
  8789. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8790. std::string out;
  8791. std::string request(
  8792. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8793. test_raw_request(request, &out);
  8794. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8795. }
  8796. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8797. std::string out;
  8798. std::string request(
  8799. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8800. test_raw_request(request, &out);
  8801. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8802. }
  8803. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8804. std::string out;
  8805. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8806. "Test: \r\n\r\n",
  8807. &out);
  8808. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8809. }
  8810. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8811. Server svr;
  8812. std::string x_custom;
  8813. std::string cookie;
  8814. std::string xff;
  8815. std::string x_unicode;
  8816. std::string x_iis;
  8817. svr.Get("/check", [&](const Request &req, Response &res) {
  8818. x_custom = req.get_header_value("X-Custom");
  8819. cookie = req.get_header_value("Cookie");
  8820. xff = req.get_header_value("X-Forwarded-For");
  8821. x_unicode = req.get_header_value("X-Unicode");
  8822. x_iis = req.get_header_value("X-IIS");
  8823. res.set_content("ok", "text/plain");
  8824. });
  8825. thread t = thread([&] { svr.listen(HOST, PORT); });
  8826. auto se = detail::scope_exit([&] {
  8827. svr.stop();
  8828. t.join();
  8829. ASSERT_FALSE(svr.is_running());
  8830. });
  8831. svr.wait_until_ready();
  8832. const std::string req = "GET /check HTTP/1.1\r\n"
  8833. "Host: localhost\r\n"
  8834. "X-Custom: a%0D%0AInjected: b\r\n"
  8835. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8836. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8837. "X-Unicode: %E3%81%82\r\n"
  8838. "X-IIS: %u00E9\r\n"
  8839. "Connection: close\r\n"
  8840. "\r\n";
  8841. std::string res;
  8842. ASSERT_TRUE(send_request(5, req, &res));
  8843. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8844. // Every value must be returned verbatim (wire form), with no decoding.
  8845. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8846. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8847. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8848. EXPECT_EQ("%E3%81%82", x_unicode);
  8849. EXPECT_EQ("%u00E9", x_iis);
  8850. }
  8851. // Applications that previously relied on automatic percent-decoding can
  8852. // reproduce the old behavior by explicitly calling decode_path_component()
  8853. // or, for RFC 3986 conformance, decode_uri_component().
  8854. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8855. Server svr;
  8856. std::string decoded;
  8857. svr.Get("/check", [&](const Request &req, Response &res) {
  8858. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8859. res.set_content("ok", "text/plain");
  8860. });
  8861. thread t = thread([&] { svr.listen(HOST, PORT); });
  8862. auto se = detail::scope_exit([&] {
  8863. svr.stop();
  8864. t.join();
  8865. ASSERT_FALSE(svr.is_running());
  8866. });
  8867. svr.wait_until_ready();
  8868. const std::string req = "GET /check HTTP/1.1\r\n"
  8869. "Host: localhost\r\n"
  8870. "X-Custom: hello%20world\r\n"
  8871. "Connection: close\r\n"
  8872. "\r\n";
  8873. std::string res;
  8874. ASSERT_TRUE(send_request(5, req, &res));
  8875. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8876. EXPECT_EQ("hello world", decoded);
  8877. }
  8878. // Regression test for #2033. Browsers send Referer values that include
  8879. // percent-encoded characters such as %0A inside the URL. Decoding the
  8880. // header value would either trip the post-decode CR/LF/NUL guard (the
  8881. // original bug, returning 400) or, after that guard was relaxed, silently
  8882. // store a literal LF — both unacceptable. The wire form must round-trip.
  8883. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8884. Server svr;
  8885. std::string referer;
  8886. svr.Get("/check", [&](const Request &req, Response &res) {
  8887. referer = req.get_header_value("Referer");
  8888. res.set_content("ok", "text/plain");
  8889. });
  8890. thread t = thread([&] { svr.listen(HOST, PORT); });
  8891. auto se = detail::scope_exit([&] {
  8892. svr.stop();
  8893. t.join();
  8894. ASSERT_FALSE(svr.is_running());
  8895. });
  8896. svr.wait_until_ready();
  8897. const std::string req = "GET /check HTTP/1.1\r\n"
  8898. "Host: localhost\r\n"
  8899. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8900. "Connection: close\r\n"
  8901. "\r\n";
  8902. std::string res;
  8903. ASSERT_TRUE(send_request(5, req, &res));
  8904. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8905. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8906. }
  8907. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8908. Server svr;
  8909. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8910. res.set_header("Cache-Control", "no-cache");
  8911. res.set_chunked_content_provider(
  8912. "text/event-stream", [](size_t offset, DataSink &sink) {
  8913. std::string s = "data:";
  8914. s += std::to_string(offset);
  8915. s += "\n\n";
  8916. auto ret = sink.write(s.data(), s.size());
  8917. EXPECT_TRUE(ret);
  8918. std::this_thread::sleep_for(std::chrono::seconds(1));
  8919. return true;
  8920. });
  8921. });
  8922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8923. svr.wait_until_ready();
  8924. Client client(HOST, PORT);
  8925. const Headers headers = {{"Accept", "text/event-stream"}};
  8926. auto get_thread = std::thread([&client, &headers]() {
  8927. auto res = client.Get(
  8928. "/events", headers,
  8929. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8930. });
  8931. auto se = detail::scope_exit([&] {
  8932. svr.stop();
  8933. get_thread.join();
  8934. listen_thread.join();
  8935. ASSERT_FALSE(svr.is_running());
  8936. });
  8937. // Give GET time to get a few messages.
  8938. std::this_thread::sleep_for(std::chrono::seconds(2));
  8939. }
  8940. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8941. httplib::Server svr;
  8942. svr.Post("/hi",
  8943. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8944. res.status = StatusCode::OK_200;
  8945. });
  8946. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8947. svr.wait_until_ready();
  8948. Client cli(HOST, PORT);
  8949. auto res = cli.Post("/hi", "data", "text/plain");
  8950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8951. EXPECT_EQ(StatusCode::OK_200, res->status);
  8952. svr.stop();
  8953. thread.join();
  8954. ASSERT_FALSE(svr.is_running());
  8955. res = cli.Post("/hi", "data", "text/plain");
  8956. ASSERT_FALSE(res);
  8957. }
  8958. TEST(ServerStopTest, ListenFailure) {
  8959. Server svr;
  8960. auto t = thread([&]() {
  8961. auto ret = svr.listen("????", PORT);
  8962. EXPECT_FALSE(ret);
  8963. });
  8964. svr.wait_until_ready();
  8965. svr.stop();
  8966. t.join();
  8967. }
  8968. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8969. TEST(ServerStopTest, Decommision) {
  8970. Server svr;
  8971. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8972. for (int i = 0; i < 4; i++) {
  8973. auto is_even = !(i % 2);
  8974. std::thread t{[&] {
  8975. try {
  8976. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8977. if (is_even) {
  8978. throw std::runtime_error("Some thing that happens to go wrong.");
  8979. }
  8980. svr.listen(HOST, PORT);
  8981. } catch (...) { svr.decommission(); }
  8982. }};
  8983. svr.wait_until_ready();
  8984. // Server is up
  8985. {
  8986. Client cli(HOST, PORT);
  8987. auto res = cli.Get("/hi");
  8988. if (is_even) {
  8989. EXPECT_FALSE(res);
  8990. } else {
  8991. EXPECT_TRUE(res);
  8992. EXPECT_EQ("hi...", res->body);
  8993. }
  8994. }
  8995. svr.stop();
  8996. t.join();
  8997. // Server is down...
  8998. {
  8999. Client cli(HOST, PORT);
  9000. auto res = cli.Get("/hi");
  9001. EXPECT_FALSE(res);
  9002. }
  9003. }
  9004. }
  9005. #endif
  9006. // Helper function for string body upload progress tests
  9007. template <typename SetupHandler, typename ClientCall>
  9008. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9009. ClientCall &&client_call,
  9010. const string &body) {
  9011. Server svr;
  9012. setup_handler(svr);
  9013. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9014. auto se = detail::scope_exit([&] {
  9015. svr.stop();
  9016. t.join();
  9017. });
  9018. svr.wait_until_ready();
  9019. Client cli(HOST, PORT);
  9020. vector<uint64_t> progress_values;
  9021. bool progress_called = false;
  9022. auto res =
  9023. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9024. progress_values.push_back(current);
  9025. progress_called = true;
  9026. return true;
  9027. });
  9028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9029. EXPECT_EQ(200, res->status);
  9030. EXPECT_TRUE(progress_called);
  9031. }
  9032. TEST(UploadProgressTest, PostStringBodyBasic) {
  9033. TestStringBodyUploadProgress(
  9034. [](Server &svr) {
  9035. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9036. res.set_content("received", "text/plain");
  9037. });
  9038. },
  9039. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9040. return cli.Post("/test", body, "text/plain", progress_callback);
  9041. },
  9042. "test data for upload progress");
  9043. }
  9044. TEST(UploadProgressTest, PutStringBodyBasic) {
  9045. TestStringBodyUploadProgress(
  9046. [](Server &svr) {
  9047. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9048. res.set_content("put received", "text/plain");
  9049. });
  9050. },
  9051. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9052. return cli.Put("/test", body, "text/plain", progress_callback);
  9053. },
  9054. "put test data for upload progress");
  9055. }
  9056. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9057. TestStringBodyUploadProgress(
  9058. [](Server &svr) {
  9059. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9060. res.set_content("patch received", "text/plain");
  9061. });
  9062. },
  9063. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9064. return cli.Patch("/test", body, "text/plain", progress_callback);
  9065. },
  9066. "patch test data for upload progress");
  9067. }
  9068. // Helper function for content provider upload progress tests
  9069. template <typename SetupHandler, typename ClientCall>
  9070. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9071. ClientCall &&client_call) {
  9072. Server svr;
  9073. setup_handler(svr);
  9074. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9075. auto se = detail::scope_exit([&] {
  9076. svr.stop();
  9077. t.join();
  9078. });
  9079. svr.wait_until_ready();
  9080. Client cli(HOST, PORT);
  9081. vector<uint64_t> progress_values;
  9082. auto res =
  9083. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9084. progress_values.push_back(current);
  9085. return true;
  9086. });
  9087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9088. EXPECT_EQ(200, res->status);
  9089. EXPECT_FALSE(progress_values.empty());
  9090. }
  9091. TEST(UploadProgressTest, PostContentProviderProgress) {
  9092. TestContentProviderUploadProgress(
  9093. [](Server &svr) {
  9094. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9095. res.set_content("provider received", "text/plain");
  9096. });
  9097. },
  9098. [](Client &cli, UploadProgress progress_callback) {
  9099. return cli.Post(
  9100. "/test", 10,
  9101. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9102. sink.os << "test data";
  9103. return true;
  9104. },
  9105. "text/plain", progress_callback);
  9106. });
  9107. }
  9108. // Helper function for multipart upload progress tests
  9109. template <typename SetupHandler, typename ClientCall>
  9110. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9111. ClientCall &&client_call,
  9112. const string &endpoint) {
  9113. Server svr;
  9114. setup_handler(svr);
  9115. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9116. auto se = detail::scope_exit([&] {
  9117. svr.stop();
  9118. t.join();
  9119. });
  9120. svr.wait_until_ready();
  9121. Client cli(HOST, PORT);
  9122. vector<uint64_t> progress_values;
  9123. UploadFormDataItems items = {
  9124. {"field1", "value1", "", ""},
  9125. {"field2", "longer value for progress tracking test", "", ""},
  9126. {"file1", "file content data for upload progress", "test.txt",
  9127. "text/plain"}};
  9128. auto res = client_call(cli, endpoint, items,
  9129. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9130. progress_values.push_back(current);
  9131. return true;
  9132. });
  9133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9134. EXPECT_EQ(200, res->status);
  9135. EXPECT_FALSE(progress_values.empty());
  9136. }
  9137. TEST(UploadProgressTest, PostMultipartProgress) {
  9138. TestMultipartUploadProgress(
  9139. [](Server &svr) {
  9140. svr.Post("/multipart", [](const Request &req, Response &res) {
  9141. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9142. res.set_content("multipart received", "text/plain");
  9143. });
  9144. },
  9145. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9146. UploadProgress progress_callback) {
  9147. return cli.Post(endpoint, items, progress_callback);
  9148. },
  9149. "/multipart");
  9150. }
  9151. // Helper function for basic download progress tests
  9152. template <typename SetupHandler, typename ClientCall>
  9153. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9154. ClientCall &&client_call, const string &endpoint,
  9155. size_t expected_content_size) {
  9156. Server svr;
  9157. setup_handler(svr);
  9158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9159. auto se = detail::scope_exit([&] {
  9160. svr.stop();
  9161. t.join();
  9162. });
  9163. svr.wait_until_ready();
  9164. Client cli(HOST, PORT);
  9165. vector<uint64_t> progress_values;
  9166. auto res = client_call(cli, endpoint,
  9167. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9168. progress_values.push_back(current);
  9169. return true;
  9170. });
  9171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9172. EXPECT_EQ(200, res->status);
  9173. EXPECT_FALSE(progress_values.empty());
  9174. EXPECT_EQ(expected_content_size, res->body.size());
  9175. }
  9176. TEST(DownloadProgressTest, GetBasic) {
  9177. TestBasicDownloadProgress(
  9178. [](Server &svr) {
  9179. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9180. string content(1000, 'D');
  9181. res.set_content(content, "text/plain");
  9182. });
  9183. },
  9184. [](Client &cli, const string &endpoint,
  9185. DownloadProgress progress_callback) {
  9186. return cli.Get(endpoint, progress_callback);
  9187. },
  9188. "/download", 1000u);
  9189. }
  9190. // Helper function for content receiver download progress tests
  9191. template <typename SetupHandler, typename ClientCall>
  9192. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9193. ClientCall &&client_call,
  9194. const string &endpoint,
  9195. size_t expected_content_size) {
  9196. Server svr;
  9197. setup_handler(svr);
  9198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9199. auto se = detail::scope_exit([&] {
  9200. svr.stop();
  9201. t.join();
  9202. });
  9203. svr.wait_until_ready();
  9204. Client cli(HOST, PORT);
  9205. vector<uint64_t> progress_values;
  9206. string received_body;
  9207. auto res = client_call(
  9208. cli, endpoint,
  9209. [&](const char *data, size_t data_length) -> bool {
  9210. received_body.append(data, data_length);
  9211. return true;
  9212. },
  9213. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9214. progress_values.push_back(current);
  9215. return true;
  9216. });
  9217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9218. EXPECT_EQ(200, res->status);
  9219. EXPECT_FALSE(progress_values.empty());
  9220. EXPECT_EQ(expected_content_size, received_body.size());
  9221. EXPECT_TRUE(res->body.empty());
  9222. }
  9223. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9224. TestContentReceiverDownloadProgress(
  9225. [](Server &svr) {
  9226. svr.Get("/download-receiver",
  9227. [](const Request & /*req*/, Response &res) {
  9228. string content(2000, 'R');
  9229. res.set_content(content, "text/plain");
  9230. });
  9231. },
  9232. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9233. DownloadProgress progress_callback) {
  9234. return cli.Get(endpoint, content_receiver, progress_callback);
  9235. },
  9236. "/download-receiver", 2000u);
  9237. }
  9238. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9239. // A provider reaching a pass with nothing to hand over - an empty buffer
  9240. // popped off a queue, say - must not be taken to mean the body is finished.
  9241. // It used to end the loop with the terminating chunk unwritten while the
  9242. // server still considered the response complete, so the peer waited for an
  9243. // end that never arrived.
  9244. Server svr;
  9245. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9246. auto step = std::make_shared<int>(0);
  9247. res.set_chunked_content_provider("text/plain",
  9248. [step](size_t /*offset*/, DataSink &sink) {
  9249. switch ((*step)++) {
  9250. case 0: sink.write("", 0); break;
  9251. case 1: sink.write("hello", 5); break;
  9252. default: sink.done(); break;
  9253. }
  9254. return true;
  9255. });
  9256. });
  9257. auto port = svr.bind_to_any_port(HOST);
  9258. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9259. auto listen_se = detail::scope_exit([&] {
  9260. svr.stop();
  9261. listen_thread.join();
  9262. ASSERT_FALSE(svr.is_running());
  9263. });
  9264. svr.wait_until_ready();
  9265. Client cli(HOST, port);
  9266. // Without the fix the body is never terminated, so bound the wait rather
  9267. // than letting the test hang on the default read timeout.
  9268. cli.set_read_timeout(5, 0);
  9269. auto res = cli.Get("/stream");
  9270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9271. EXPECT_EQ(StatusCode::OK_200, res->status);
  9272. EXPECT_EQ("hello", res->body);
  9273. }
  9274. TEST(StreamingTest, NoContentLengthStreaming) {
  9275. Server svr;
  9276. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9277. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9278. if (offset < 6) {
  9279. sink.os << (offset < 3 ? "a" : "b");
  9280. } else {
  9281. sink.done();
  9282. }
  9283. return true;
  9284. });
  9285. });
  9286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9287. auto listen_se = detail::scope_exit([&] {
  9288. svr.stop();
  9289. listen_thread.join();
  9290. ASSERT_FALSE(svr.is_running());
  9291. });
  9292. svr.wait_until_ready();
  9293. Client client(HOST, PORT);
  9294. auto get_thread = std::thread([&client]() {
  9295. std::string s;
  9296. auto res =
  9297. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9298. s += std::string(data, len);
  9299. return true;
  9300. });
  9301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9302. EXPECT_EQ(StatusCode::OK_200, res->status);
  9303. EXPECT_EQ("aaabbb", s);
  9304. });
  9305. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9306. // Give GET time to get a few messages.
  9307. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9308. }
  9309. TEST(MountTest, Unmount) {
  9310. Server svr;
  9311. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9312. auto se = detail::scope_exit([&] {
  9313. svr.stop();
  9314. listen_thread.join();
  9315. ASSERT_FALSE(svr.is_running());
  9316. });
  9317. svr.wait_until_ready();
  9318. Client cli("localhost", PORT);
  9319. svr.set_mount_point("/mount2", "./www2");
  9320. auto res = cli.Get("/");
  9321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9323. res = cli.Get("/mount2/dir/test.html");
  9324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9325. EXPECT_EQ(StatusCode::OK_200, res->status);
  9326. svr.set_mount_point("/", "./www");
  9327. res = cli.Get("/dir/");
  9328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. svr.remove_mount_point("/");
  9331. res = cli.Get("/dir/");
  9332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9334. svr.remove_mount_point("/mount2");
  9335. res = cli.Get("/mount2/dir/test.html");
  9336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9337. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9338. }
  9339. TEST(MountTest, PathSegmentBoundary) {
  9340. Server svr;
  9341. svr.set_mount_point("/mount2", "./www2");
  9342. svr.set_mount_point("/", "./www");
  9343. auto port = svr.bind_to_any_port(HOST);
  9344. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9345. auto se = detail::scope_exit([&] {
  9346. svr.stop();
  9347. listen_thread.join();
  9348. ASSERT_FALSE(svr.is_running());
  9349. });
  9350. svr.wait_until_ready();
  9351. Client cli(HOST, port);
  9352. auto res = cli.Get("/mount2/dir/test.html");
  9353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9354. EXPECT_EQ(StatusCode::OK_200, res->status);
  9355. // "/mount2" must not match part-way through a path segment.
  9356. res = cli.Get("/mount2dir/test.html");
  9357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9358. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9359. // A mount point ending in '/' keeps matching every path below it.
  9360. res = cli.Get("/dir/test.html");
  9361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9362. EXPECT_EQ(StatusCode::OK_200, res->status);
  9363. }
  9364. TEST(MountTest, Redicect) {
  9365. Server svr;
  9366. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9367. auto se = detail::scope_exit([&] {
  9368. svr.stop();
  9369. listen_thread.join();
  9370. ASSERT_FALSE(svr.is_running());
  9371. });
  9372. svr.set_mount_point("/", "./www");
  9373. svr.wait_until_ready();
  9374. Client cli("localhost", PORT);
  9375. auto res = cli.Get("/dir/");
  9376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9377. EXPECT_EQ(StatusCode::OK_200, res->status);
  9378. res = cli.Get("/dir");
  9379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9380. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9381. res = cli.Get("/file");
  9382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9383. EXPECT_EQ(StatusCode::OK_200, res->status);
  9384. res = cli.Get("/file/");
  9385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9387. cli.set_follow_location(true);
  9388. res = cli.Get("/dir");
  9389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9390. EXPECT_EQ(StatusCode::OK_200, res->status);
  9391. }
  9392. TEST(MountTest, MultibytesPathName) {
  9393. Server svr;
  9394. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9395. auto se = detail::scope_exit([&] {
  9396. svr.stop();
  9397. listen_thread.join();
  9398. ASSERT_FALSE(svr.is_running());
  9399. });
  9400. svr.set_mount_point("/", "./www");
  9401. svr.wait_until_ready();
  9402. Client cli("localhost", PORT);
  9403. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9405. EXPECT_EQ(StatusCode::OK_200, res->status);
  9406. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9407. }
  9408. #ifdef _WIN32
  9409. // Issue #2435: mmap::open() must succeed even when another handle holds
  9410. // the file open for writing (e.g. an active log file).
  9411. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9412. const char *path = "mmap_concurrent_writer_test.txt";
  9413. const char *content = "hello";
  9414. {
  9415. std::ofstream f(path, std::ios::binary);
  9416. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9417. }
  9418. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9419. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9420. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9421. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9422. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9423. detail::mmap m(path);
  9424. ASSERT_TRUE(m.is_open());
  9425. EXPECT_EQ(strlen(content), m.size());
  9426. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9427. }
  9428. #endif
  9429. #ifndef _WIN32
  9430. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9431. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9432. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9433. TEST(MmapTest, FailedMappingIsNotOpen) {
  9434. const char *path = "./mmap_failed_mapping_test_dir";
  9435. ASSERT_EQ(0, ::mkdir(path, 0755));
  9436. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9437. detail::mmap m(path);
  9438. EXPECT_FALSE(m.is_open());
  9439. EXPECT_EQ(0U, m.size());
  9440. EXPECT_NE(static_cast<const void *>(m.data()),
  9441. static_cast<const void *>(MAP_FAILED));
  9442. }
  9443. #endif
  9444. TEST(KeepAliveTest, ReadTimeout) {
  9445. Server svr;
  9446. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9447. std::this_thread::sleep_for(std::chrono::seconds(2));
  9448. res.set_content("a", "text/plain");
  9449. });
  9450. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9451. res.set_content("b", "text/plain");
  9452. });
  9453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9454. auto se = detail::scope_exit([&] {
  9455. svr.stop();
  9456. listen_thread.join();
  9457. ASSERT_FALSE(svr.is_running());
  9458. });
  9459. svr.wait_until_ready();
  9460. Client cli("localhost", PORT);
  9461. cli.set_keep_alive(true);
  9462. cli.set_read_timeout(std::chrono::seconds(1));
  9463. auto resa = cli.Get("/a");
  9464. ASSERT_FALSE(resa);
  9465. EXPECT_EQ(Error::Read, resa.error());
  9466. auto resb = cli.Get("/b");
  9467. ASSERT_TRUE(resb);
  9468. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9469. EXPECT_EQ("b", resb->body);
  9470. }
  9471. TEST(KeepAliveTest, MaxCount) {
  9472. size_t keep_alive_max_count = 3;
  9473. Server svr;
  9474. svr.set_keep_alive_max_count(keep_alive_max_count);
  9475. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9476. res.set_content("Hello World!", "text/plain");
  9477. });
  9478. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9479. auto se = detail::scope_exit([&] {
  9480. svr.stop();
  9481. listen_thread.join();
  9482. ASSERT_FALSE(svr.is_running());
  9483. });
  9484. svr.wait_until_ready();
  9485. Client cli(HOST, PORT);
  9486. cli.set_keep_alive(true);
  9487. for (size_t i = 0; i < 5; i++) {
  9488. auto result = cli.Get("/hi");
  9489. ASSERT_TRUE(result);
  9490. EXPECT_EQ(StatusCode::OK_200, result->status);
  9491. if (i == keep_alive_max_count - 1) {
  9492. EXPECT_EQ("close", result->get_header_value("Connection"));
  9493. } else {
  9494. EXPECT_FALSE(result->has_header("Connection"));
  9495. }
  9496. }
  9497. }
  9498. TEST(KeepAliveTest, Issue1041) {
  9499. Server svr;
  9500. svr.set_keep_alive_timeout(3);
  9501. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9502. res.set_content("Hello World!", "text/plain");
  9503. });
  9504. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9505. auto se = detail::scope_exit([&] {
  9506. svr.stop();
  9507. listen_thread.join();
  9508. ASSERT_FALSE(svr.is_running());
  9509. });
  9510. svr.wait_until_ready();
  9511. Client cli(HOST, PORT);
  9512. cli.set_keep_alive(true);
  9513. auto result = cli.Get("/hi");
  9514. ASSERT_TRUE(result);
  9515. EXPECT_EQ(StatusCode::OK_200, result->status);
  9516. std::this_thread::sleep_for(std::chrono::seconds(5));
  9517. result = cli.Get("/hi");
  9518. ASSERT_TRUE(result);
  9519. EXPECT_EQ(StatusCode::OK_200, result->status);
  9520. }
  9521. TEST(KeepAliveTest, Issue1959) {
  9522. Server svr;
  9523. svr.set_keep_alive_timeout(5);
  9524. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9525. res.set_content("a", "text/plain");
  9526. });
  9527. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9528. auto se = detail::scope_exit([&] {
  9529. if (!svr.is_running()) return;
  9530. svr.stop();
  9531. listen_thread.join();
  9532. ASSERT_FALSE(svr.is_running());
  9533. });
  9534. svr.wait_until_ready();
  9535. Client cli("localhost", PORT);
  9536. cli.set_keep_alive(true);
  9537. using namespace std::chrono;
  9538. auto start = steady_clock::now();
  9539. cli.Get("/a");
  9540. svr.stop();
  9541. listen_thread.join();
  9542. auto end = steady_clock::now();
  9543. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9544. EXPECT_LT(elapsed, 5000);
  9545. }
  9546. #ifdef CPPHTTPLIB_SSL_ENABLED
  9547. TEST(KeepAliveTest, SSLClientReconnection) {
  9548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9549. ASSERT_TRUE(svr.is_valid());
  9550. svr.set_keep_alive_timeout(1);
  9551. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9552. res.set_content("Hello World!", "text/plain");
  9553. });
  9554. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. listen_thread.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. SSLClient cli(HOST, PORT);
  9562. cli.enable_server_certificate_verification(false);
  9563. cli.set_keep_alive(true);
  9564. auto result = cli.Get("/hi");
  9565. ASSERT_TRUE(result);
  9566. EXPECT_EQ(StatusCode::OK_200, result->status);
  9567. result = cli.Get("/hi");
  9568. ASSERT_TRUE(result);
  9569. EXPECT_EQ(StatusCode::OK_200, result->status);
  9570. std::this_thread::sleep_for(std::chrono::seconds(2));
  9571. // Recoonect
  9572. result = cli.Get("/hi");
  9573. ASSERT_TRUE(result);
  9574. EXPECT_EQ(StatusCode::OK_200, result->status);
  9575. result = cli.Get("/hi");
  9576. ASSERT_TRUE(result);
  9577. EXPECT_EQ(StatusCode::OK_200, result->status);
  9578. }
  9579. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9581. ASSERT_TRUE(svr.is_valid());
  9582. svr.set_keep_alive_timeout(1);
  9583. std::string content = "reconnect";
  9584. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9585. res.set_content("Hello World!", "text/plain");
  9586. });
  9587. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9588. auto se = detail::scope_exit([&] {
  9589. svr.stop();
  9590. listen_thread.join();
  9591. ASSERT_FALSE(svr.is_running());
  9592. });
  9593. svr.wait_until_ready();
  9594. SSLClient cli(HOST, PORT);
  9595. cli.enable_server_certificate_verification(false);
  9596. cli.set_keep_alive(true);
  9597. auto result = cli.Post(
  9598. "/hi", content.size(),
  9599. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9600. sink.write(content.c_str(), content.size());
  9601. return true;
  9602. },
  9603. "text/plain");
  9604. ASSERT_TRUE(result);
  9605. EXPECT_EQ(200, result->status);
  9606. std::this_thread::sleep_for(std::chrono::seconds(2));
  9607. // Recoonect
  9608. result = cli.Post(
  9609. "/hi", content.size(),
  9610. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9611. sink.write(content.c_str(), content.size());
  9612. return true;
  9613. },
  9614. "text/plain");
  9615. ASSERT_TRUE(result);
  9616. EXPECT_EQ(200, result->status);
  9617. result = cli.Post(
  9618. "/hi", content.size(),
  9619. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9620. sink.write(content.c_str(), content.size());
  9621. return true;
  9622. },
  9623. "text/plain");
  9624. ASSERT_TRUE(result);
  9625. EXPECT_EQ(200, result->status);
  9626. }
  9627. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9628. using namespace httplib::tls;
  9629. {
  9630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9631. ASSERT_TRUE(svr.is_valid());
  9632. svr.Get("/sni", [&](const Request &req, Response &res) {
  9633. std::string expected = req.sni();
  9634. EXPECT_EQ(expected, req.get_param_value("expected"));
  9635. res.set_content("ok", "text/plain");
  9636. });
  9637. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9638. auto se = detail::scope_exit([&] {
  9639. svr.stop();
  9640. listen_thread.join();
  9641. ASSERT_FALSE(svr.is_running());
  9642. });
  9643. svr.wait_until_ready();
  9644. {
  9645. SSLClient cli("localhost", PORT);
  9646. cli.enable_server_certificate_verification(false);
  9647. auto res = cli.Get("/sni?expected=localhost");
  9648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9649. }
  9650. {
  9651. SSLClient cli("::1", PORT);
  9652. cli.enable_server_certificate_verification(false);
  9653. auto res = cli.Get("/sni?expected=");
  9654. // NOTE: This may fail if the server is listening on IPv4 only
  9655. // (e.g., when localhost resolves to 127.0.0.1 only)
  9656. if (res) {
  9657. EXPECT_EQ(StatusCode::OK_200, res->status);
  9658. } else {
  9659. EXPECT_EQ(Error::Connection, res.error());
  9660. }
  9661. }
  9662. }
  9663. }
  9664. #endif
  9665. TEST(ClientProblemDetectionTest, ContentProvider) {
  9666. Server svr;
  9667. size_t content_length = 1024 * 1024;
  9668. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9669. res.set_content_provider(
  9670. content_length, "text/plain",
  9671. [&](size_t offset, size_t length, DataSink &sink) {
  9672. auto out_len = std::min(length, static_cast<size_t>(1024));
  9673. std::string out(out_len, '@');
  9674. sink.write(out.data(), out_len);
  9675. return offset < 4096;
  9676. },
  9677. [](bool success) { ASSERT_FALSE(success); });
  9678. });
  9679. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9680. res.set_content_provider(
  9681. 0, "text/plain",
  9682. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9683. EXPECT_TRUE(false);
  9684. return true;
  9685. },
  9686. [](bool success) { ASSERT_FALSE(success); });
  9687. });
  9688. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9689. auto se = detail::scope_exit([&] {
  9690. svr.stop();
  9691. listen_thread.join();
  9692. ASSERT_FALSE(svr.is_running());
  9693. });
  9694. svr.wait_until_ready();
  9695. Client cli("localhost", PORT);
  9696. {
  9697. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9698. size_t /*data_length*/) { return false; });
  9699. ASSERT_FALSE(res);
  9700. }
  9701. {
  9702. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9703. size_t /*data_length*/) { return false; });
  9704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9705. }
  9706. }
  9707. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9708. // A provider that reports success without writing anything and without
  9709. // calling done() used to be handed the same offset and length again on every
  9710. // pass, so it spun for as long as the peer stayed connected.
  9711. Server svr;
  9712. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9713. res.set_content("ok", "text/plain");
  9714. });
  9715. auto port = svr.bind_to_any_port(HOST);
  9716. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. listen_thread.join();
  9720. ASSERT_FALSE(svr.is_running());
  9721. });
  9722. svr.wait_until_ready();
  9723. std::atomic<int> call_count{0};
  9724. Client cli(HOST, port);
  9725. auto res = cli.Post(
  9726. "/", 1024,
  9727. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9728. // Give up after enough passes to show the spin, so that losing the
  9729. // check below fails this test instead of hanging it.
  9730. return ++call_count < 100;
  9731. },
  9732. "text/plain");
  9733. ASSERT_FALSE(res);
  9734. EXPECT_EQ(Error::Write, res.error());
  9735. EXPECT_EQ(1, call_count.load());
  9736. }
  9737. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9738. // A writer only has to assign `write`. The other three used to be left as
  9739. // empty std::functions, so a provider calling one threw
  9740. // std::bad_function_call out of the thread running it and took the whole
  9741. // process down.
  9742. DataSink sink;
  9743. std::string written;
  9744. sink.write = [&](const char *data, size_t data_len) {
  9745. written.append(data, data_len);
  9746. return true;
  9747. };
  9748. EXPECT_TRUE(sink.is_writable());
  9749. sink.done();
  9750. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9751. EXPECT_TRUE(written.empty());
  9752. }
  9753. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9754. // A sink that cannot carry trailers still has to finish.
  9755. DataSink sink;
  9756. auto done_count = 0;
  9757. sink.done = [&]() { done_count++; };
  9758. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9759. EXPECT_EQ(1, done_count);
  9760. }
  9761. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9762. Server svr;
  9763. const std::string body(4096, 'x');
  9764. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9765. res.set_content_provider(body.size(), "text/plain",
  9766. [&](size_t offset, size_t length, DataSink &sink) {
  9767. sink.write(body.data() + offset, length);
  9768. sink.done();
  9769. return true;
  9770. });
  9771. });
  9772. auto port = svr.bind_to_any_port(HOST);
  9773. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9774. auto se = detail::scope_exit([&] {
  9775. svr.stop();
  9776. listen_thread.join();
  9777. ASSERT_FALSE(svr.is_running());
  9778. });
  9779. svr.wait_until_ready();
  9780. Client cli(HOST, port);
  9781. auto res = cli.Get("/");
  9782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9783. EXPECT_EQ(StatusCode::OK_200, res->status);
  9784. EXPECT_EQ(body, res->body);
  9785. }
  9786. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9787. Server svr;
  9788. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9789. res.set_content_provider(
  9790. 1024, "text/plain",
  9791. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9792. sink.write("hello", 5);
  9793. sink.done(); // short of the 1024 bytes the response promised
  9794. return true;
  9795. });
  9796. });
  9797. auto port = svr.bind_to_any_port(HOST);
  9798. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9799. auto se = detail::scope_exit([&] {
  9800. svr.stop();
  9801. listen_thread.join();
  9802. ASSERT_FALSE(svr.is_running());
  9803. });
  9804. svr.wait_until_ready();
  9805. Client cli(HOST, port);
  9806. cli.set_read_timeout(5, 0);
  9807. // The response is short of its Content-Length, so the client cannot read a
  9808. // complete body. What matters is that this returns at all: a no-op done()
  9809. // would leave the writer looping over a provider that never makes progress.
  9810. auto res = cli.Get("/");
  9811. EXPECT_FALSE(res);
  9812. }
  9813. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9814. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9815. // The compressed path builds the whole body before connecting, so this
  9816. // fails client-side and never reaches a server.
  9817. Client cli(HOST, PORT);
  9818. cli.set_compress(true);
  9819. auto res = cli.Post(
  9820. "/", 1024,
  9821. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9822. sink.write("hello", 5);
  9823. sink.done(); // short of the 1024 bytes the request announced
  9824. return true;
  9825. },
  9826. "text/plain");
  9827. ASSERT_FALSE(res);
  9828. EXPECT_EQ(Error::Write, res.error());
  9829. }
  9830. #endif
  9831. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9832. Server svr;
  9833. svr.set_error_handler([](Request const &, Response &res) -> void {
  9834. res.set_chunked_content_provider(
  9835. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9836. sink.os << "hello";
  9837. sink.os << "world";
  9838. sink.done();
  9839. return true;
  9840. });
  9841. });
  9842. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9843. auto se = detail::scope_exit([&] {
  9844. svr.stop();
  9845. listen_thread.join();
  9846. ASSERT_FALSE(svr.is_running());
  9847. });
  9848. svr.wait_until_ready();
  9849. Client cli("localhost", PORT);
  9850. auto res = cli.Get("/");
  9851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9852. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9853. EXPECT_EQ("helloworld", res->body);
  9854. }
  9855. TEST(LongPollingTest, ClientCloseDetection) {
  9856. Server svr;
  9857. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9858. res.set_chunked_content_provider(
  9859. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9860. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9861. sink.os << "hello";
  9862. auto count = 10;
  9863. while (count > 0 && sink.is_writable()) {
  9864. this_thread::sleep_for(chrono::milliseconds(10));
  9865. count--;
  9866. }
  9867. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9868. return true;
  9869. });
  9870. });
  9871. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9872. auto se = detail::scope_exit([&] {
  9873. svr.stop();
  9874. listen_thread.join();
  9875. ASSERT_FALSE(svr.is_running());
  9876. });
  9877. svr.wait_until_ready();
  9878. Client cli("localhost", PORT);
  9879. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9880. EXPECT_EQ("hello", string(data, data_length));
  9881. return false; // close the socket immediately.
  9882. });
  9883. ASSERT_FALSE(res);
  9884. }
  9885. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9886. Server svr;
  9887. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9888. res.set_chunked_content_provider(
  9889. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9890. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9891. sink.os << "hello";
  9892. EXPECT_TRUE(sink.os.good());
  9893. // Wait for the client to close the connection
  9894. auto count = 10;
  9895. while (count > 0 && sink.is_writable()) {
  9896. this_thread::sleep_for(chrono::milliseconds(10));
  9897. count--;
  9898. }
  9899. // After client disconnect, write repeatedly until the socket
  9900. // write actually fails (small writes may be absorbed by the
  9901. // kernel buffer)
  9902. std::string chunk(1024, 'x');
  9903. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9904. sink.os << chunk;
  9905. }
  9906. EXPECT_TRUE(sink.os.fail());
  9907. return true;
  9908. });
  9909. });
  9910. auto port = svr.bind_to_any_port("localhost");
  9911. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9912. auto se = detail::scope_exit([&] {
  9913. svr.stop();
  9914. listen_thread.join();
  9915. ASSERT_FALSE(svr.is_running());
  9916. });
  9917. svr.wait_until_ready();
  9918. Client cli("localhost", port);
  9919. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9920. EXPECT_EQ("hello", string(data, data_length));
  9921. return false; // close the socket immediately.
  9922. });
  9923. ASSERT_FALSE(res);
  9924. }
  9925. TEST(GetWithParametersTest, GetWithParameters) {
  9926. Server svr;
  9927. svr.Get("/", [&](const Request &req, Response &) {
  9928. EXPECT_EQ("world", req.get_param_value("hello"));
  9929. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9930. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9931. });
  9932. svr.Get("/params", [&](const Request &req, Response &) {
  9933. EXPECT_EQ("world", req.get_param_value("hello"));
  9934. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9935. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9936. });
  9937. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9938. EXPECT_EQ("resource-id", req.matches[1]);
  9939. EXPECT_EQ("foo", req.get_param_value("param1"));
  9940. EXPECT_EQ("bar", req.get_param_value("param2"));
  9941. });
  9942. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9943. EXPECT_EQ("user-id", req.path_params.at("id"));
  9944. EXPECT_EQ("foo", req.get_param_value("param1"));
  9945. EXPECT_EQ("bar", req.get_param_value("param2"));
  9946. });
  9947. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9948. auto se = detail::scope_exit([&] {
  9949. svr.stop();
  9950. listen_thread.join();
  9951. ASSERT_FALSE(svr.is_running());
  9952. });
  9953. svr.wait_until_ready();
  9954. {
  9955. Client cli(HOST, PORT);
  9956. Params params;
  9957. params.emplace("hello", "world");
  9958. params.emplace("hello2", "world2");
  9959. params.emplace("hello3", "world3");
  9960. auto res = cli.Get("/", params, Headers{});
  9961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9962. EXPECT_EQ(StatusCode::OK_200, res->status);
  9963. }
  9964. {
  9965. Client cli(HOST, PORT);
  9966. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9968. EXPECT_EQ(StatusCode::OK_200, res->status);
  9969. }
  9970. {
  9971. Client cli(HOST, PORT);
  9972. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9974. EXPECT_EQ(StatusCode::OK_200, res->status);
  9975. }
  9976. {
  9977. Client cli(HOST, PORT);
  9978. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9980. EXPECT_EQ(StatusCode::OK_200, res->status);
  9981. }
  9982. }
  9983. TEST(GetWithParametersTest, GetWithParameters2) {
  9984. Server svr;
  9985. svr.Get("/", [&](const Request &req, Response &res) {
  9986. auto text = req.get_param_value("hello");
  9987. res.set_content(text, "text/plain");
  9988. });
  9989. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9990. auto se = detail::scope_exit([&] {
  9991. svr.stop();
  9992. listen_thread.join();
  9993. ASSERT_FALSE(svr.is_running());
  9994. });
  9995. svr.wait_until_ready();
  9996. Client cli("localhost", PORT);
  9997. Params params;
  9998. params.emplace("hello", "world");
  9999. std::string body;
  10000. auto res = cli.Get("/", params, Headers{},
  10001. [&](const char *data, size_t data_length) {
  10002. body.append(data, data_length);
  10003. return true;
  10004. });
  10005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10006. EXPECT_EQ(StatusCode::OK_200, res->status);
  10007. EXPECT_EQ("world", body);
  10008. }
  10009. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10010. Server svr;
  10011. svr.Get("/search", [&](const Request &req, Response &res) {
  10012. auto q = req.get_param_value("q");
  10013. res.set_content(q, "text/plain");
  10014. });
  10015. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10016. auto se = detail::scope_exit([&] {
  10017. svr.stop();
  10018. listen_thread.join();
  10019. ASSERT_FALSE(svr.is_running());
  10020. });
  10021. svr.wait_until_ready();
  10022. Client cli("localhost", PORT);
  10023. // Verify that Get(path, params) works without requiring Headers argument
  10024. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10026. EXPECT_EQ(StatusCode::OK_200, res->status);
  10027. EXPECT_EQ("cpp-httplib", res->body);
  10028. }
  10029. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10030. auto host = "httpbingo.org";
  10031. auto path = std::string{"/range/32"};
  10032. #ifdef CPPHTTPLIB_SSL_ENABLED
  10033. SSLClient cli(host);
  10034. #else
  10035. Client cli(host);
  10036. #endif
  10037. cli.set_default_headers({make_range_header({{1, 10}})});
  10038. cli.set_connection_timeout(5);
  10039. {
  10040. auto res = cli.Get(path);
  10041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10042. EXPECT_EQ("bcdefghijk", res->body);
  10043. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10044. }
  10045. {
  10046. auto res = cli.Get(path);
  10047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10048. EXPECT_EQ("bcdefghijk", res->body);
  10049. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10050. }
  10051. }
  10052. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10053. Server svr;
  10054. svr.set_default_headers({{"Hello", "World"}});
  10055. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10056. res.set_content("ok", "text/plain");
  10057. });
  10058. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10059. auto se = detail::scope_exit([&] {
  10060. svr.stop();
  10061. listen_thread.join();
  10062. ASSERT_FALSE(svr.is_running());
  10063. });
  10064. svr.wait_until_ready();
  10065. Client cli("localhost", PORT);
  10066. auto res = cli.Get("/");
  10067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10068. EXPECT_EQ(StatusCode::OK_200, res->status);
  10069. EXPECT_EQ("ok", res->body);
  10070. EXPECT_EQ("World", res->get_header_value("Hello"));
  10071. }
  10072. #ifdef CPPHTTPLIB_SSL_ENABLED
  10073. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10075. ASSERT_TRUE(svr.is_valid());
  10076. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10077. std::this_thread::sleep_for(std::chrono::seconds(2));
  10078. res.set_content("a", "text/plain");
  10079. });
  10080. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10081. res.set_content("b", "text/plain");
  10082. });
  10083. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10084. auto se = detail::scope_exit([&] {
  10085. svr.stop();
  10086. listen_thread.join();
  10087. ASSERT_FALSE(svr.is_running());
  10088. });
  10089. svr.wait_until_ready();
  10090. SSLClient cli("localhost", PORT);
  10091. cli.enable_server_certificate_verification(false);
  10092. cli.set_keep_alive(true);
  10093. cli.set_read_timeout(std::chrono::seconds(1));
  10094. auto resa = cli.Get("/a");
  10095. ASSERT_TRUE(!resa);
  10096. EXPECT_EQ(Error::Read, resa.error());
  10097. auto resb = cli.Get("/b");
  10098. ASSERT_TRUE(resb);
  10099. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10100. EXPECT_EQ("b", resb->body);
  10101. }
  10102. // Closing an idle keep-alive connection sends close_notify and returns. The
  10103. // server must not wait for the client's close_notify: an idle client never
  10104. // sends one, so the worker would be held until the read timeout expires, and
  10105. // stop() would wait for it.
  10106. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10108. ASSERT_TRUE(svr.is_valid());
  10109. svr.set_keep_alive_timeout(1);
  10110. svr.set_read_timeout(10, 0);
  10111. svr.Get("/", [](const Request &, Response &res) {
  10112. res.set_content("ok", "text/plain");
  10113. });
  10114. auto port = svr.bind_to_any_port(HOST);
  10115. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10116. auto se = detail::scope_exit([&] {
  10117. if (listen_thread.joinable()) {
  10118. svr.stop();
  10119. listen_thread.join();
  10120. }
  10121. });
  10122. svr.wait_until_ready();
  10123. SSLClient cli(HOST, port);
  10124. cli.enable_server_certificate_verification(false);
  10125. cli.set_keep_alive(true);
  10126. auto res = cli.Get("/");
  10127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10128. EXPECT_EQ(StatusCode::OK_200, res->status);
  10129. // Stay idle past the keep-alive timeout so the server closes the connection.
  10130. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10131. auto start = std::chrono::steady_clock::now();
  10132. svr.stop();
  10133. listen_thread.join();
  10134. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10135. std::chrono::steady_clock::now() - start)
  10136. .count();
  10137. EXPECT_LT(elapsed, 3000);
  10138. }
  10139. #endif
  10140. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10141. protected:
  10142. ServerTestWithAI_PASSIVE()
  10143. : cli_(HOST, PORT)
  10144. #ifdef CPPHTTPLIB_SSL_ENABLED
  10145. ,
  10146. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10147. #endif
  10148. {
  10149. #ifdef CPPHTTPLIB_SSL_ENABLED
  10150. cli_.enable_server_certificate_verification(false);
  10151. #endif
  10152. }
  10153. virtual void SetUp() {
  10154. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10155. res.set_content("Hello World!", "text/plain");
  10156. });
  10157. t_ = thread(
  10158. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10159. svr_.wait_until_ready();
  10160. }
  10161. virtual void TearDown() {
  10162. svr_.stop();
  10163. t_.join();
  10164. }
  10165. #ifdef CPPHTTPLIB_SSL_ENABLED
  10166. SSLClient cli_;
  10167. SSLServer svr_;
  10168. #else
  10169. Client cli_;
  10170. Server svr_;
  10171. #endif
  10172. thread t_;
  10173. };
  10174. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10175. auto res = cli_.Get("/hi");
  10176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10177. EXPECT_EQ(StatusCode::OK_200, res->status);
  10178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10179. EXPECT_EQ("Hello World!", res->body);
  10180. }
  10181. class ServerUpDownTest : public ::testing::Test {
  10182. protected:
  10183. ServerUpDownTest() : cli_(HOST, PORT) {}
  10184. virtual void SetUp() {
  10185. t_ = thread([&]() {
  10186. svr_.bind_to_any_port(HOST);
  10187. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10188. ASSERT_TRUE(svr_.listen_after_bind());
  10189. });
  10190. svr_.wait_until_ready();
  10191. }
  10192. virtual void TearDown() {
  10193. svr_.stop();
  10194. t_.join();
  10195. }
  10196. Client cli_;
  10197. Server svr_;
  10198. thread t_;
  10199. };
  10200. TEST_F(ServerUpDownTest, QuickStartStop) {
  10201. // Should not crash, especially when run with
  10202. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10203. }
  10204. class PayloadMaxLengthTest : public ::testing::Test {
  10205. protected:
  10206. PayloadMaxLengthTest()
  10207. : cli_(HOST, PORT)
  10208. #ifdef CPPHTTPLIB_SSL_ENABLED
  10209. ,
  10210. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10211. #endif
  10212. {
  10213. #ifdef CPPHTTPLIB_SSL_ENABLED
  10214. cli_.enable_server_certificate_verification(false);
  10215. #endif
  10216. }
  10217. virtual void SetUp() {
  10218. svr_.set_payload_max_length(8);
  10219. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10220. res.set_content("test", "text/plain");
  10221. });
  10222. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10223. svr_.wait_until_ready();
  10224. }
  10225. virtual void TearDown() {
  10226. svr_.stop();
  10227. t_.join();
  10228. }
  10229. #ifdef CPPHTTPLIB_SSL_ENABLED
  10230. SSLClient cli_;
  10231. SSLServer svr_;
  10232. #else
  10233. Client cli_;
  10234. Server svr_;
  10235. #endif
  10236. thread t_;
  10237. };
  10238. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10239. auto res = cli_.Post("/test", "123456789", "text/plain");
  10240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10241. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10242. res = cli_.Post("/test", "12345678", "text/plain");
  10243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10244. EXPECT_EQ(StatusCode::OK_200, res->status);
  10245. }
  10246. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10247. // Test chunked encoding with payload exceeding the 8-byte limit
  10248. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10249. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10251. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10252. }
  10253. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10254. // Test chunked encoding with payload within the 8-byte limit
  10255. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10256. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10258. EXPECT_EQ(StatusCode::OK_200, res->status);
  10259. }
  10260. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10261. // Test using send_request to send chunked data exceeding payload limit
  10262. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10263. "Host: " +
  10264. std::string(HOST) + ":" + std::to_string(PORT) +
  10265. "\r\n"
  10266. "Transfer-Encoding: chunked\r\n"
  10267. "Connection: close\r\n"
  10268. "\r\n"
  10269. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10270. "0123456789\r\n"
  10271. "0\r\n" // End chunk
  10272. "\r\n";
  10273. std::string response;
  10274. bool result = send_request(1, chunked_request, &response);
  10275. if (!result) {
  10276. // If send_request fails, it might be because the server closed the
  10277. // connection due to payload limit enforcement, which is acceptable
  10278. SUCCEED()
  10279. << "Server rejected oversized chunked request (connection closed)";
  10280. } else {
  10281. // If we got a response, check if it's an error response or connection was
  10282. // closed early Short response length indicates connection was closed due to
  10283. // payload limit
  10284. if (response.length() <= 10) {
  10285. SUCCEED() << "Server closed connection for oversized chunked request";
  10286. } else {
  10287. // Check for error status codes
  10288. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10289. response.find("Payload Too Large") != std::string::npos ||
  10290. response.find("400") != std::string::npos);
  10291. }
  10292. }
  10293. }
  10294. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10295. // Test request without Content-Length header exceeding payload limit
  10296. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10297. "Host: " +
  10298. std::string(HOST) + ":" +
  10299. std::to_string(PORT) +
  10300. "\r\n"
  10301. "Connection: close\r\n"
  10302. "\r\n";
  10303. // Add payload exceeding the 8-byte limit
  10304. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10305. request_without_content_length += large_payload;
  10306. std::string response;
  10307. bool result = send_request(1, request_without_content_length, &response);
  10308. if (!result) {
  10309. // If send_request fails, server likely closed connection due to payload
  10310. // limit
  10311. SUCCEED() << "Server rejected oversized request without Content-Length "
  10312. "(connection closed)";
  10313. } else {
  10314. // Check if server responded with error or closed connection early
  10315. if (response.length() <= 10) {
  10316. SUCCEED() << "Server closed connection for oversized request without "
  10317. "Content-Length";
  10318. } else {
  10319. // Check for error status codes
  10320. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10321. response.find("Payload Too Large") != std::string::npos ||
  10322. response.find("400") != std::string::npos);
  10323. }
  10324. }
  10325. }
  10326. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10327. // Test request without Content-Length header within payload limit
  10328. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10329. "Host: " +
  10330. std::string(HOST) + ":" +
  10331. std::to_string(PORT) +
  10332. "\r\n"
  10333. "Connection: close\r\n"
  10334. "\r\n";
  10335. // Add payload within the 8-byte limit
  10336. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10337. request_without_content_length += small_payload;
  10338. std::string response;
  10339. bool result = send_request(1, request_without_content_length, &response);
  10340. // For requests without Content-Length, the server may have different behavior
  10341. // The key is that it should not reject due to payload limit for small
  10342. // payloads
  10343. if (result) {
  10344. // Check for any HTTP response (success or error, but not connection closed)
  10345. if (response.length() > 10) {
  10346. SUCCEED()
  10347. << "Server processed request without Content-Length within limit";
  10348. } else {
  10349. // Short response might indicate connection closed, which is acceptable
  10350. SUCCEED() << "Server closed connection for request without "
  10351. "Content-Length (acceptable behavior)";
  10352. }
  10353. } else {
  10354. // Connection failure might be due to protocol requirements
  10355. SUCCEED() << "Connection issue with request without Content-Length "
  10356. "(environment-specific)";
  10357. }
  10358. }
  10359. class LargePayloadMaxLengthTest : public ::testing::Test {
  10360. protected:
  10361. LargePayloadMaxLengthTest()
  10362. : cli_(HOST, PORT)
  10363. #ifdef CPPHTTPLIB_SSL_ENABLED
  10364. ,
  10365. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10366. #endif
  10367. {
  10368. #ifdef CPPHTTPLIB_SSL_ENABLED
  10369. cli_.enable_server_certificate_verification(false);
  10370. #endif
  10371. }
  10372. virtual void SetUp() {
  10373. // Set 10MB payload limit
  10374. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10375. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10376. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10377. res.set_content("Large payload test", "text/plain");
  10378. });
  10379. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10380. svr_.wait_until_ready();
  10381. }
  10382. virtual void TearDown() {
  10383. svr_.stop();
  10384. t_.join();
  10385. }
  10386. #ifdef CPPHTTPLIB_SSL_ENABLED
  10387. SSLClient cli_;
  10388. SSLServer svr_;
  10389. #else
  10390. Client cli_;
  10391. Server svr_;
  10392. #endif
  10393. thread t_;
  10394. };
  10395. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10396. // Test chunked encoding with payload within 10MB limit
  10397. std::string medium_payload(5 * 1024 * 1024,
  10398. 'A'); // 5MB payload, within 10MB limit
  10399. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10401. EXPECT_EQ(StatusCode::OK_200, res->status);
  10402. }
  10403. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10404. // Test chunked encoding with payload exceeding 10MB limit
  10405. std::string large_payload(12 * 1024 * 1024,
  10406. 'B'); // 12MB payload, exceeds 10MB limit
  10407. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10408. // Server may either return 413 or close the connection
  10409. if (res) {
  10410. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10411. } else {
  10412. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10413. }
  10414. }
  10415. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10416. // Test request without Content-Length header within 10MB limit
  10417. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10418. "Host: " +
  10419. std::string(HOST) + ":" +
  10420. std::to_string(PORT) +
  10421. "\r\n"
  10422. "Connection: close\r\n"
  10423. "\r\n";
  10424. // Add 1MB payload (within 10MB limit)
  10425. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10426. request_without_content_length += medium_payload;
  10427. std::string response;
  10428. bool result = send_request(5, request_without_content_length, &response);
  10429. if (result) {
  10430. // Should get a proper HTTP response for payloads within limit
  10431. if (response.length() > 10) {
  10432. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10433. "10MB limit";
  10434. } else {
  10435. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10436. "Content-Length)";
  10437. }
  10438. } else {
  10439. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10440. }
  10441. }
  10442. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10443. // Test request without Content-Length header exceeding 10MB limit
  10444. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10445. "Host: " +
  10446. std::string(HOST) + ":" +
  10447. std::to_string(PORT) +
  10448. "\r\n"
  10449. "Connection: close\r\n"
  10450. "\r\n";
  10451. // Add 12MB payload (exceeds 10MB limit)
  10452. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10453. request_without_content_length += large_payload;
  10454. std::string response;
  10455. bool result = send_request(10, request_without_content_length, &response);
  10456. if (!result) {
  10457. // Server should close connection due to payload limit
  10458. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10459. "(connection closed)";
  10460. } else {
  10461. // Check for error response
  10462. if (response.length() <= 10) {
  10463. SUCCEED()
  10464. << "Server closed connection for 12MB request exceeding 10MB limit";
  10465. } else {
  10466. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10467. response.find("Payload Too Large") != std::string::npos ||
  10468. response.find("400") != std::string::npos);
  10469. }
  10470. }
  10471. }
  10472. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10473. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10474. // path.
  10475. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10476. Server svr;
  10477. const size_t LIMIT = 64 * 1024; // 64KB
  10478. svr.set_payload_max_length(LIMIT);
  10479. size_t total = 0;
  10480. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10481. const ContentReader &content_reader) {
  10482. content_reader([&](const char * /*data*/, size_t len) {
  10483. total += len;
  10484. return true;
  10485. });
  10486. res.status = 200;
  10487. res.set_content("stream_ok", "text/plain");
  10488. });
  10489. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10490. auto se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. // Prepare 256KB raw data and gzip-compress it
  10497. std::string raw(256 * 1024, 'A');
  10498. std::string gz;
  10499. {
  10500. z_stream zs{};
  10501. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10502. Z_DEFAULT_STRATEGY);
  10503. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10504. zs.avail_in = static_cast<uInt>(raw.size());
  10505. char outbuf[4096];
  10506. int ret;
  10507. do {
  10508. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10509. zs.avail_out = sizeof(outbuf);
  10510. ret = deflate(&zs, Z_FINISH);
  10511. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10512. } while (ret != Z_STREAM_END);
  10513. deflateEnd(&zs);
  10514. }
  10515. Client cli(HOST, PORT);
  10516. cli.set_connection_timeout(std::chrono::seconds(5));
  10517. Headers headers = {{"Content-Encoding", "gzip"}};
  10518. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10519. "application/octet-stream");
  10520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10521. // Server must reject oversized decompressed payloads with 413.
  10522. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10523. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10524. EXPECT_LE(total, LIMIT);
  10525. }
  10526. #ifndef CPPHTTPLIB_SSL_ENABLED
  10527. // For a request with neither Content-Length nor Transfer-Encoding, the
  10528. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10529. // compressed wire bytes straight to the ContentReader without ever routing
  10530. // them through the decompressor, so payload_max_length_ only bounded the
  10531. // compressed size on the wire, not the decompressed size.
  10532. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10533. Server svr;
  10534. const size_t LIMIT = 64 * 1024; // 64KB
  10535. svr.set_payload_max_length(LIMIT);
  10536. size_t total = 0;
  10537. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10538. const ContentReader &content_reader) {
  10539. content_reader([&](const char * /*data*/, size_t len) {
  10540. total += len;
  10541. return true;
  10542. });
  10543. res.status = 200;
  10544. res.set_content("stream_ok", "text/plain");
  10545. });
  10546. auto port = svr.bind_to_any_port(HOST);
  10547. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10548. auto se = detail::scope_exit([&] {
  10549. svr.stop();
  10550. thread.join();
  10551. ASSERT_FALSE(svr.is_running());
  10552. });
  10553. svr.wait_until_ready();
  10554. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10555. // StreamingGzipDecompression test above.
  10556. std::string raw(256 * 1024, 'A');
  10557. std::string gz;
  10558. {
  10559. httplib::detail::gzip_compressor compressor;
  10560. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10561. [&](const char *chunk, size_t len) {
  10562. gz.append(chunk, len);
  10563. return true;
  10564. });
  10565. ASSERT_TRUE(result);
  10566. }
  10567. // Send the gzip body over raw TCP with neither Content-Length nor
  10568. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10569. // kicks in.
  10570. std::string req = "POST /stream HTTP/1.1\r\n"
  10571. "Host: " +
  10572. std::string(HOST) + ":" + std::to_string(port) +
  10573. "\r\n"
  10574. "Content-Encoding: gzip\r\n"
  10575. "Connection: close\r\n"
  10576. "\r\n" +
  10577. gz;
  10578. std::string response;
  10579. ASSERT_TRUE(send_request(5, req, &response, port));
  10580. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10581. EXPECT_LE(total, LIMIT);
  10582. }
  10583. #endif
  10584. #endif
  10585. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10586. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10587. // the payload must be passed through untouched instead of being rejected.
  10588. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10589. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10590. Server svr;
  10591. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10592. res.set_content(body, "image/jpeg");
  10593. res.set_header("Content-Encoding", "UTF-8");
  10594. });
  10595. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10596. res.set_content(body, "image/jpeg");
  10597. res.set_header("Content-Encoding", "identity");
  10598. });
  10599. svr.Post("/echo", [](const Request &req, Response &res) {
  10600. res.set_content(req.body, "image/jpeg");
  10601. });
  10602. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10603. auto se = detail::scope_exit([&] {
  10604. svr.stop();
  10605. t.join();
  10606. ASSERT_FALSE(svr.is_running());
  10607. });
  10608. svr.wait_until_ready();
  10609. Client cli(HOST, PORT);
  10610. {
  10611. auto res = cli.Get("/image");
  10612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10613. EXPECT_EQ(StatusCode::OK_200, res->status);
  10614. EXPECT_EQ(body, res->body);
  10615. }
  10616. {
  10617. auto res = cli.Get("/identity");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ(StatusCode::OK_200, res->status);
  10620. EXPECT_EQ(body, res->body);
  10621. }
  10622. {
  10623. // The same applies to a request body reaching the server.
  10624. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10625. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10627. EXPECT_EQ(StatusCode::OK_200, res->status);
  10628. EXPECT_EQ(body, res->body);
  10629. }
  10630. }
  10631. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10632. // gzip-encoded response even when the build has no zlib support.
  10633. static const char GZIPPED_HELLO_WORLD[] = {
  10634. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10635. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10636. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10637. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10638. // A content coding is a whole token, not something the field value merely
  10639. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10640. // as "fibre" look like Brotli, and turned a multi-coding value like
  10641. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10642. // it was never meant to see.
  10643. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10644. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10645. Server svr;
  10646. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10647. res.set_content(body, "image/jpeg");
  10648. res.set_header("Content-Encoding", "fibre");
  10649. });
  10650. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10651. res.set_content(body, "image/jpeg");
  10652. res.set_header("Content-Encoding", "gzip, br");
  10653. });
  10654. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10655. res.set_content(body, "image/jpeg");
  10656. res.set_header("Content-Encoding", "x-zstd-ish");
  10657. });
  10658. auto port = svr.bind_to_any_port(HOST);
  10659. thread t = thread([&]() { svr.listen_after_bind(); });
  10660. auto se = detail::scope_exit([&] {
  10661. svr.stop();
  10662. t.join();
  10663. ASSERT_FALSE(svr.is_running());
  10664. });
  10665. svr.wait_until_ready();
  10666. Client cli(HOST, port);
  10667. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10668. auto res = cli.Get(path);
  10669. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10670. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10671. // Not a coding we recognize, so the payload comes back untouched
  10672. EXPECT_EQ(body, res->body) << path;
  10673. }
  10674. }
  10675. // A content coding cpp-httplib recognizes but was not built with must be
  10676. // reported as such. Handing the still-compressed payload back to the caller
  10677. // would silently corrupt it.
  10678. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10679. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10680. Server svr;
  10681. // "image/jpeg" keeps the server from applying a content coding of its own,
  10682. // so the hand-crafted Content-Encoding below survives.
  10683. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10684. res.set_content(gzipped, "image/jpeg");
  10685. res.set_header("Content-Encoding", "gzip");
  10686. });
  10687. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10688. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10689. res.set_content(gzipped, "image/jpeg");
  10690. res.set_header("Content-Encoding", "GZIP");
  10691. });
  10692. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10693. auto se = detail::scope_exit([&] {
  10694. svr.stop();
  10695. t.join();
  10696. ASSERT_FALSE(svr.is_running());
  10697. });
  10698. svr.wait_until_ready();
  10699. Client cli(HOST, PORT);
  10700. {
  10701. auto res = cli.Get("/gzipped");
  10702. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10704. EXPECT_EQ("Hello World!", res->body);
  10705. #else
  10706. ASSERT_FALSE(res);
  10707. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10708. #endif
  10709. }
  10710. {
  10711. // open_stream() must behave the same way.
  10712. auto handle = cli.open_stream("GET", "/gzipped");
  10713. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10714. ASSERT_TRUE(handle.is_valid());
  10715. std::string received;
  10716. char buf[256];
  10717. ssize_t n;
  10718. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10719. received.append(buf, static_cast<size_t>(n));
  10720. }
  10721. EXPECT_EQ("Hello World!", received);
  10722. #else
  10723. EXPECT_FALSE(handle.is_valid());
  10724. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10725. #endif
  10726. }
  10727. {
  10728. // A differently-cased coding must not be mistaken for an unknown one, or
  10729. // the body would be handed back still compressed.
  10730. auto res = cli.Get("/gzipped-uppercase");
  10731. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10733. EXPECT_EQ("Hello World!", res->body);
  10734. #else
  10735. ASSERT_FALSE(res);
  10736. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10737. #endif
  10738. }
  10739. }
  10740. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10741. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10742. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10743. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10744. // body a second time and appending a second Content-Encoding field line, so
  10745. // clients that decode one coding per listed value handed back raw gzip bytes.
  10746. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10747. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10748. Server svr;
  10749. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10750. // keeps the server from applying a coding of its own.
  10751. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10752. res.set_content(gzipped, "text/plain");
  10753. res.set_header("Content-Encoding", "gzip");
  10754. });
  10755. auto port = svr.bind_to_any_port(HOST);
  10756. thread t = thread([&]() { svr.listen_after_bind(); });
  10757. auto se = detail::scope_exit([&] {
  10758. svr.stop();
  10759. t.join();
  10760. ASSERT_FALSE(svr.is_running());
  10761. });
  10762. svr.wait_until_ready();
  10763. Client cli(HOST, port);
  10764. Headers headers = {{"Accept-Encoding", "gzip"}};
  10765. auto res = cli.Get("/pre-gzipped", headers);
  10766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10767. EXPECT_EQ(StatusCode::OK_200, res->status);
  10768. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10769. EXPECT_EQ("Hello World!", res->body);
  10770. }
  10771. // A chunked provider settles its coding where the headers are written and
  10772. // reuses it at write time. Both ends of that have to hold: a handler's own
  10773. // Content-Encoding suppresses the coding, and a response without one is still
  10774. // compressed as it always was.
  10775. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10776. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10777. const std::string plain = "Hello World! Hello World! Hello World!";
  10778. Server svr;
  10779. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10780. res.set_header("Content-Encoding", "gzip");
  10781. res.set_chunked_content_provider(
  10782. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10783. sink.write(gzipped.data(), gzipped.size());
  10784. sink.done();
  10785. return true;
  10786. });
  10787. });
  10788. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10789. res.set_chunked_content_provider(
  10790. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10791. sink.write(plain.data(), plain.size());
  10792. sink.done();
  10793. return true;
  10794. });
  10795. });
  10796. auto port = svr.bind_to_any_port(HOST);
  10797. thread t = thread([&]() { svr.listen_after_bind(); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. t.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. Client cli(HOST, port);
  10805. Headers headers = {{"Accept-Encoding", "gzip"}};
  10806. {
  10807. auto res = cli.Get("/pre-gzipped", headers);
  10808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10809. EXPECT_EQ(StatusCode::OK_200, res->status);
  10810. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10811. EXPECT_EQ("Hello World!", res->body);
  10812. }
  10813. {
  10814. auto res = cli.Get("/negotiated", headers);
  10815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10816. EXPECT_EQ(StatusCode::OK_200, res->status);
  10817. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10818. EXPECT_EQ(plain, res->body);
  10819. }
  10820. }
  10821. #endif
  10822. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10823. // the same message as the comma-joined one, so both have to be read the same
  10824. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10825. // single gzip coding, and a body the sender says was encoded twice was handed
  10826. // back after one pass, still compressed but presented as decoded.
  10827. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10828. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10829. Server svr;
  10830. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10831. res.set_content(body, "image/jpeg");
  10832. res.headers.emplace("Content-Encoding", "gzip");
  10833. res.headers.emplace("Content-Encoding", "gzip");
  10834. });
  10835. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10836. res.set_content(body, "image/jpeg");
  10837. res.set_header("Content-Encoding", "gzip, gzip");
  10838. });
  10839. auto port = svr.bind_to_any_port(HOST);
  10840. thread t = thread([&]() { svr.listen_after_bind(); });
  10841. auto se = detail::scope_exit([&] {
  10842. svr.stop();
  10843. t.join();
  10844. ASSERT_FALSE(svr.is_running());
  10845. });
  10846. svr.wait_until_ready();
  10847. Client cli(HOST, port);
  10848. // Two codings is not something cpp-httplib decodes, so both representations
  10849. // take the pass-through path rather than one of them being gunzipped once.
  10850. for (const char *path : {"/split", "/joined"}) {
  10851. auto res = cli.Get(path);
  10852. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10853. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10854. EXPECT_EQ(body, res->body) << path;
  10855. }
  10856. }
  10857. // Regression test for DoS vulnerability: a malicious server sending a response
  10858. // without Content-Length header must not cause unbounded memory consumption on
  10859. // the client side. The client should stop reading after a reasonable limit,
  10860. // similar to the server-side set_payload_max_length protection.
  10861. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10862. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10863. #ifndef _WIN32
  10864. signal(SIGPIPE, SIG_IGN);
  10865. #endif
  10866. auto server_thread = std::thread([] {
  10867. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10868. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10869. default_socket_options(srv);
  10870. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10871. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10872. sockaddr_in addr{};
  10873. addr.sin_family = AF_INET;
  10874. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10875. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10876. int opt = 1;
  10877. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10878. #ifdef _WIN32
  10879. reinterpret_cast<const char *>(&opt),
  10880. #else
  10881. &opt,
  10882. #endif
  10883. sizeof(opt));
  10884. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10885. ::listen(srv, 1);
  10886. sockaddr_in cli_addr{};
  10887. socklen_t cli_len = sizeof(cli_addr);
  10888. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10889. if (cli != INVALID_SOCKET) {
  10890. char buf[4096];
  10891. ::recv(cli, buf, sizeof(buf), 0);
  10892. // Malicious response: no Content-Length, no chunked encoding
  10893. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10894. "Connection: close\r\n"
  10895. "\r\n";
  10896. ::send(cli,
  10897. #ifdef _WIN32
  10898. static_cast<const char *>(response_header.c_str()),
  10899. static_cast<int>(response_header.size()),
  10900. #else
  10901. response_header.c_str(), response_header.size(),
  10902. #endif
  10903. 0);
  10904. // Send 10MB of data
  10905. std::string chunk(64 * 1024, 'A');
  10906. size_t total_sent = 0;
  10907. while (total_sent < MALICIOUS_DATA_SIZE) {
  10908. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10909. auto sent = ::send(cli,
  10910. #ifdef _WIN32
  10911. static_cast<const char *>(chunk.c_str()),
  10912. static_cast<int>(to_send),
  10913. #else
  10914. chunk.c_str(), to_send,
  10915. #endif
  10916. 0);
  10917. if (sent <= 0) break;
  10918. total_sent += static_cast<size_t>(sent);
  10919. }
  10920. detail::close_socket(cli);
  10921. }
  10922. detail::close_socket(srv);
  10923. });
  10924. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10925. size_t total_read = 0;
  10926. {
  10927. Client cli("127.0.0.1", PORT + 2);
  10928. cli.set_read_timeout(5, 0);
  10929. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10930. auto stream = cli.open_stream("GET", "/malicious");
  10931. ASSERT_TRUE(stream.is_valid());
  10932. char buffer[64 * 1024];
  10933. ssize_t n;
  10934. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10935. total_read += static_cast<size_t>(n);
  10936. }
  10937. } // StreamHandle and Client destroyed here, closing the socket
  10938. server_thread.join();
  10939. // With set_payload_max_length, the client must stop reading before consuming
  10940. // all 10MB. The read loop should be cut off at or near the configured limit.
  10941. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10942. << "Client read " << total_read << " bytes, exceeding the configured "
  10943. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10944. }
  10945. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10946. // the entire response body without truncation.
  10947. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10948. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10949. #ifndef _WIN32
  10950. signal(SIGPIPE, SIG_IGN);
  10951. #endif
  10952. auto server_thread = std::thread([] {
  10953. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10954. default_socket_options(srv);
  10955. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10956. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10957. sockaddr_in addr{};
  10958. addr.sin_family = AF_INET;
  10959. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10960. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10961. int opt = 1;
  10962. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10963. #ifdef _WIN32
  10964. reinterpret_cast<const char *>(&opt),
  10965. #else
  10966. &opt,
  10967. #endif
  10968. sizeof(opt));
  10969. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10970. ::listen(srv, 1);
  10971. sockaddr_in cli_addr{};
  10972. socklen_t cli_len = sizeof(cli_addr);
  10973. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10974. if (cli != INVALID_SOCKET) {
  10975. char buf[4096];
  10976. ::recv(cli, buf, sizeof(buf), 0);
  10977. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10978. "Connection: close\r\n"
  10979. "\r\n";
  10980. ::send(cli,
  10981. #ifdef _WIN32
  10982. static_cast<const char *>(response_header.c_str()),
  10983. static_cast<int>(response_header.size()),
  10984. #else
  10985. response_header.c_str(), response_header.size(),
  10986. #endif
  10987. 0);
  10988. std::string chunk(64 * 1024, 'A');
  10989. size_t total_sent = 0;
  10990. while (total_sent < DATA_SIZE) {
  10991. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10992. auto sent = ::send(cli,
  10993. #ifdef _WIN32
  10994. static_cast<const char *>(chunk.c_str()),
  10995. static_cast<int>(to_send),
  10996. #else
  10997. chunk.c_str(), to_send,
  10998. #endif
  10999. 0);
  11000. if (sent <= 0) break;
  11001. total_sent += static_cast<size_t>(sent);
  11002. }
  11003. #ifdef _WIN32
  11004. ::shutdown(cli, SD_SEND);
  11005. #else
  11006. ::shutdown(cli, SHUT_WR);
  11007. #endif
  11008. // Drain until the client closes its end, ensuring all data is delivered
  11009. char drain[1024];
  11010. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11011. detail::close_socket(cli);
  11012. }
  11013. detail::close_socket(srv);
  11014. });
  11015. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11016. size_t total_read = 0;
  11017. {
  11018. Client cli("127.0.0.1", PORT + 2);
  11019. cli.set_read_timeout(5, 0);
  11020. cli.set_payload_max_length(0); // 0 means no limit
  11021. auto stream = cli.open_stream("GET", "/data");
  11022. ASSERT_TRUE(stream.is_valid());
  11023. char buffer[64 * 1024];
  11024. ssize_t n;
  11025. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11026. total_read += static_cast<size_t>(n);
  11027. }
  11028. }
  11029. server_thread.join();
  11030. EXPECT_EQ(total_read, DATA_SIZE)
  11031. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11032. << " bytes without truncation, but only read " << total_read << " bytes.";
  11033. }
  11034. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11035. // enormous Content-Length must not cause the client to pre-allocate a huge
  11036. // response body buffer. The reservation is capped at payload_max_length_, and
  11037. // the read itself fails when the body exceeds the limit.
  11038. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11039. #ifndef _WIN32
  11040. signal(SIGPIPE, SIG_IGN);
  11041. #endif
  11042. auto server_thread = std::thread([] {
  11043. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11044. default_socket_options(srv);
  11045. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11046. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11047. sockaddr_in addr{};
  11048. addr.sin_family = AF_INET;
  11049. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11050. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11051. int opt = 1;
  11052. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11053. #ifdef _WIN32
  11054. reinterpret_cast<const char *>(&opt),
  11055. #else
  11056. &opt,
  11057. #endif
  11058. sizeof(opt));
  11059. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11060. ::listen(srv, 1);
  11061. sockaddr_in cli_addr{};
  11062. socklen_t cli_len = sizeof(cli_addr);
  11063. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11064. if (cli != INVALID_SOCKET) {
  11065. char buf[4096];
  11066. ::recv(cli, buf, sizeof(buf), 0);
  11067. // Malicious response: claim a 20GB body but send only a tiny payload.
  11068. std::string response = "HTTP/1.1 200 OK\r\n"
  11069. "Content-Length: 20000000000\r\n"
  11070. "\r\n"
  11071. "abc";
  11072. ::send(cli,
  11073. #ifdef _WIN32
  11074. static_cast<const char *>(response.c_str()),
  11075. static_cast<int>(response.size()),
  11076. #else
  11077. response.c_str(), response.size(),
  11078. #endif
  11079. 0);
  11080. detail::close_socket(cli);
  11081. }
  11082. detail::close_socket(srv);
  11083. });
  11084. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11085. {
  11086. Client cli("127.0.0.1", PORT + 2);
  11087. cli.set_read_timeout(5, 0);
  11088. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11089. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11090. // (server claims more bytes than payload_max_length permits), but it must
  11091. // not exhaust memory before getting there.
  11092. auto res = cli.Get("/malicious");
  11093. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11094. }
  11095. server_thread.join();
  11096. }
  11097. // Verify that content_receiver bypasses the default payload_max_length,
  11098. // allowing streaming downloads larger than 100MB without requiring an explicit
  11099. // set_payload_max_length call.
  11100. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11101. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11102. #ifndef _WIN32
  11103. signal(SIGPIPE, SIG_IGN);
  11104. #endif
  11105. auto server_thread = std::thread([] {
  11106. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11107. default_socket_options(srv);
  11108. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11109. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11110. sockaddr_in addr{};
  11111. addr.sin_family = AF_INET;
  11112. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11113. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11114. int opt = 1;
  11115. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11116. #ifdef _WIN32
  11117. reinterpret_cast<const char *>(&opt),
  11118. #else
  11119. &opt,
  11120. #endif
  11121. sizeof(opt));
  11122. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11123. ::listen(srv, 1);
  11124. sockaddr_in cli_addr{};
  11125. socklen_t cli_len = sizeof(cli_addr);
  11126. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11127. if (cli != INVALID_SOCKET) {
  11128. char buf[4096];
  11129. ::recv(cli, buf, sizeof(buf), 0);
  11130. // Response with Content-Length larger than default 100MB limit
  11131. auto content_length = std::to_string(DATA_SIZE);
  11132. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11133. "Content-Length: " +
  11134. content_length +
  11135. "\r\n"
  11136. "Connection: close\r\n"
  11137. "\r\n";
  11138. ::send(cli,
  11139. #ifdef _WIN32
  11140. static_cast<const char *>(response_header.c_str()),
  11141. static_cast<int>(response_header.size()),
  11142. #else
  11143. response_header.c_str(), response_header.size(),
  11144. #endif
  11145. 0);
  11146. std::string chunk(64 * 1024, 'A');
  11147. size_t total_sent = 0;
  11148. while (total_sent < DATA_SIZE) {
  11149. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11150. auto sent = ::send(cli,
  11151. #ifdef _WIN32
  11152. static_cast<const char *>(chunk.c_str()),
  11153. static_cast<int>(to_send),
  11154. #else
  11155. chunk.c_str(), to_send,
  11156. #endif
  11157. 0);
  11158. if (sent <= 0) break;
  11159. total_sent += static_cast<size_t>(sent);
  11160. }
  11161. detail::close_socket(cli);
  11162. }
  11163. detail::close_socket(srv);
  11164. });
  11165. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11166. size_t total_received = 0;
  11167. {
  11168. Client cli("127.0.0.1", PORT + 2);
  11169. cli.set_read_timeout(10, 0);
  11170. // Do NOT call set_payload_max_length — use the default 100MB limit
  11171. auto res =
  11172. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11173. total_received += data_length;
  11174. return true;
  11175. });
  11176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11177. EXPECT_EQ(StatusCode::OK_200, res->status);
  11178. }
  11179. server_thread.join();
  11180. EXPECT_EQ(total_received, DATA_SIZE)
  11181. << "With content_receiver, the client should read all " << DATA_SIZE
  11182. << " bytes despite the default 100MB payload_max_length, but only read "
  11183. << total_received << " bytes.";
  11184. }
  11185. // Verify that an explicit set_payload_max_length smaller than the response is
  11186. // enforced even when a content_receiver is used.
  11187. TEST(ClientVulnerabilityTest,
  11188. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11189. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11190. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11191. #ifndef _WIN32
  11192. signal(SIGPIPE, SIG_IGN);
  11193. #endif
  11194. auto server_thread = std::thread([] {
  11195. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11196. default_socket_options(srv);
  11197. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11198. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11199. sockaddr_in addr{};
  11200. addr.sin_family = AF_INET;
  11201. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11202. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11203. int opt = 1;
  11204. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11205. #ifdef _WIN32
  11206. reinterpret_cast<const char *>(&opt),
  11207. #else
  11208. &opt,
  11209. #endif
  11210. sizeof(opt));
  11211. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11212. ::listen(srv, 1);
  11213. sockaddr_in cli_addr{};
  11214. socklen_t cli_len = sizeof(cli_addr);
  11215. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11216. if (cli != INVALID_SOCKET) {
  11217. char buf[4096];
  11218. ::recv(cli, buf, sizeof(buf), 0);
  11219. auto content_length = std::to_string(DATA_SIZE);
  11220. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11221. "Content-Length: " +
  11222. content_length +
  11223. "\r\n"
  11224. "Connection: close\r\n"
  11225. "\r\n";
  11226. ::send(cli,
  11227. #ifdef _WIN32
  11228. static_cast<const char *>(response_header.c_str()),
  11229. static_cast<int>(response_header.size()),
  11230. #else
  11231. response_header.c_str(), response_header.size(),
  11232. #endif
  11233. 0);
  11234. std::string chunk(64 * 1024, 'A');
  11235. size_t total_sent = 0;
  11236. while (total_sent < DATA_SIZE) {
  11237. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11238. auto sent = ::send(cli,
  11239. #ifdef _WIN32
  11240. static_cast<const char *>(chunk.c_str()),
  11241. static_cast<int>(to_send),
  11242. #else
  11243. chunk.c_str(), to_send,
  11244. #endif
  11245. 0);
  11246. if (sent <= 0) break;
  11247. total_sent += static_cast<size_t>(sent);
  11248. }
  11249. detail::close_socket(cli);
  11250. }
  11251. detail::close_socket(srv);
  11252. });
  11253. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11254. size_t total_received = 0;
  11255. {
  11256. Client cli("127.0.0.1", PORT + 2);
  11257. cli.set_read_timeout(10, 0);
  11258. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11259. auto res =
  11260. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11261. total_received += data_length;
  11262. return true;
  11263. });
  11264. // Should fail because 200MB exceeds the explicit 150MB limit
  11265. EXPECT_FALSE(res);
  11266. }
  11267. server_thread.join();
  11268. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11269. << "Client with content_receiver should respect the explicit "
  11270. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11271. << total_received << " bytes.";
  11272. }
  11273. // Verify that an explicit set_payload_max_length larger than the response
  11274. // allows the content_receiver to read all data successfully.
  11275. TEST(ClientVulnerabilityTest,
  11276. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11277. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11278. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11279. #ifndef _WIN32
  11280. signal(SIGPIPE, SIG_IGN);
  11281. #endif
  11282. auto server_thread = std::thread([] {
  11283. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11284. default_socket_options(srv);
  11285. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11286. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11287. sockaddr_in addr{};
  11288. addr.sin_family = AF_INET;
  11289. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11290. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11291. int opt = 1;
  11292. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11293. #ifdef _WIN32
  11294. reinterpret_cast<const char *>(&opt),
  11295. #else
  11296. &opt,
  11297. #endif
  11298. sizeof(opt));
  11299. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11300. ::listen(srv, 1);
  11301. sockaddr_in cli_addr{};
  11302. socklen_t cli_len = sizeof(cli_addr);
  11303. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11304. if (cli != INVALID_SOCKET) {
  11305. char buf[4096];
  11306. ::recv(cli, buf, sizeof(buf), 0);
  11307. auto content_length = std::to_string(DATA_SIZE);
  11308. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11309. "Content-Length: " +
  11310. content_length +
  11311. "\r\n"
  11312. "Connection: close\r\n"
  11313. "\r\n";
  11314. ::send(cli,
  11315. #ifdef _WIN32
  11316. static_cast<const char *>(response_header.c_str()),
  11317. static_cast<int>(response_header.size()),
  11318. #else
  11319. response_header.c_str(), response_header.size(),
  11320. #endif
  11321. 0);
  11322. std::string chunk(64 * 1024, 'A');
  11323. size_t total_sent = 0;
  11324. while (total_sent < DATA_SIZE) {
  11325. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11326. auto sent = ::send(cli,
  11327. #ifdef _WIN32
  11328. static_cast<const char *>(chunk.c_str()),
  11329. static_cast<int>(to_send),
  11330. #else
  11331. chunk.c_str(), to_send,
  11332. #endif
  11333. 0);
  11334. if (sent <= 0) break;
  11335. total_sent += static_cast<size_t>(sent);
  11336. }
  11337. #ifdef _WIN32
  11338. ::shutdown(cli, SD_SEND);
  11339. #else
  11340. ::shutdown(cli, SHUT_WR);
  11341. #endif
  11342. char drain[1024];
  11343. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11344. detail::close_socket(cli);
  11345. }
  11346. detail::close_socket(srv);
  11347. });
  11348. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11349. size_t total_received = 0;
  11350. {
  11351. Client cli("127.0.0.1", PORT + 2);
  11352. cli.set_read_timeout(10, 0);
  11353. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11354. auto res =
  11355. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11356. total_received += data_length;
  11357. return true;
  11358. });
  11359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11360. EXPECT_EQ(StatusCode::OK_200, res->status);
  11361. }
  11362. server_thread.join();
  11363. EXPECT_EQ(total_received, DATA_SIZE)
  11364. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11365. << " bytes (larger than " << DATA_SIZE
  11366. << " bytes response), content_receiver should read all data, but only "
  11367. "read "
  11368. << total_received << " bytes.";
  11369. }
  11370. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11371. // Regression test for "zip bomb" attack on the client side: a malicious server
  11372. // sends a small gzip-compressed response that decompresses to a huge payload.
  11373. // The client must enforce payload_max_length on the decompressed size.
  11374. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11375. constexpr size_t DECOMPRESSED_SIZE =
  11376. 10 * 1024 * 1024; // 10MB after decompression
  11377. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11378. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11379. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11380. std::string compressed;
  11381. {
  11382. httplib::detail::gzip_compressor compressor;
  11383. bool ok =
  11384. compressor.compress(uncompressed.data(), uncompressed.size(),
  11385. /*last=*/true, [&](const char *buf, size_t len) {
  11386. compressed.append(buf, len);
  11387. return true;
  11388. });
  11389. ASSERT_TRUE(ok);
  11390. }
  11391. // Sanity: compressed data should be much smaller than the decompressed size
  11392. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11393. #ifndef _WIN32
  11394. signal(SIGPIPE, SIG_IGN);
  11395. #endif
  11396. // Set up the listening socket in the main thread so the server is guaranteed
  11397. // to be ready before the client connects (eliminates race condition).
  11398. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11399. default_socket_options(srv);
  11400. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11401. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11402. sockaddr_in addr{};
  11403. addr.sin_family = AF_INET;
  11404. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11405. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11406. int opt = 1;
  11407. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11408. #ifdef _WIN32
  11409. reinterpret_cast<const char *>(&opt),
  11410. #else
  11411. &opt,
  11412. #endif
  11413. sizeof(opt));
  11414. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11415. ASSERT_EQ(0, ::listen(srv, 1));
  11416. auto server_thread = std::thread([&compressed, srv] {
  11417. sockaddr_in cli_addr{};
  11418. socklen_t cli_len = sizeof(cli_addr);
  11419. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11420. if (cli != INVALID_SOCKET) {
  11421. // Read the full HTTP request (until \r\n\r\n)
  11422. char buf[4096];
  11423. size_t total = 0;
  11424. while (total < sizeof(buf)) {
  11425. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11426. if (n <= 0) break;
  11427. total += static_cast<size_t>(n);
  11428. // Check for end of headers
  11429. if (total >= 4) {
  11430. std::string req(buf, total);
  11431. if (req.find("\r\n\r\n") != std::string::npos) break;
  11432. }
  11433. }
  11434. // Malicious response: gzip-compressed body, no Content-Length
  11435. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11436. "Content-Encoding: gzip\r\n"
  11437. "Connection: close\r\n"
  11438. "\r\n";
  11439. ::send(cli,
  11440. #ifdef _WIN32
  11441. static_cast<const char *>(response_header.c_str()),
  11442. static_cast<int>(response_header.size()),
  11443. #else
  11444. response_header.c_str(), response_header.size(),
  11445. #endif
  11446. 0);
  11447. // Send the compressed payload (small on the wire, huge when decompressed)
  11448. size_t total_sent = 0;
  11449. while (total_sent < compressed.size()) {
  11450. auto to_send = std::min(compressed.size() - total_sent,
  11451. static_cast<size_t>(64 * 1024));
  11452. auto sent =
  11453. ::send(cli,
  11454. #ifdef _WIN32
  11455. static_cast<const char *>(compressed.c_str() + total_sent),
  11456. static_cast<int>(to_send),
  11457. #else
  11458. compressed.c_str() + total_sent, to_send,
  11459. #endif
  11460. 0);
  11461. if (sent <= 0) break;
  11462. total_sent += static_cast<size_t>(sent);
  11463. }
  11464. detail::close_socket(cli);
  11465. }
  11466. });
  11467. auto se = detail::scope_exit([&] {
  11468. detail::close_socket(srv);
  11469. server_thread.join();
  11470. });
  11471. size_t total_decompressed = 0;
  11472. {
  11473. Client cli("127.0.0.1", PORT + 3);
  11474. cli.set_read_timeout(5, 0);
  11475. cli.set_decompress(true);
  11476. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11477. auto stream = cli.open_stream("GET", "/zipbomb");
  11478. ASSERT_TRUE(stream.is_valid());
  11479. char buffer[64 * 1024];
  11480. ssize_t n;
  11481. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11482. total_decompressed += static_cast<size_t>(n);
  11483. }
  11484. }
  11485. // The decompressed size must be capped by payload_max_length. Without
  11486. // protection, the client would decompress the full 10MB from a tiny
  11487. // compressed payload, enabling a zip bomb DoS attack.
  11488. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11489. << "Client decompressed " << total_decompressed
  11490. << " bytes from a gzip response. The decompressed size should be "
  11491. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11492. }
  11493. #endif
  11494. TEST(HostAndPortPropertiesTest, NoSSL) {
  11495. httplib::Client cli("www.google.com", 1234);
  11496. ASSERT_EQ("www.google.com", cli.host());
  11497. ASSERT_EQ(1234, cli.port());
  11498. }
  11499. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11500. httplib::Client cli("www.google.com:1234");
  11501. ASSERT_EQ("www.google.com", cli.host());
  11502. ASSERT_EQ(1234, cli.port());
  11503. }
  11504. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11505. // Port number that overflows int — should not crash, client becomes invalid
  11506. httplib::Client cli("http://www.google.com:99999999999999999999");
  11507. ASSERT_FALSE(cli.is_valid());
  11508. }
  11509. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11510. // Port 99999 exceeds valid range (1-65535) — should not crash
  11511. httplib::Client cli("http://www.google.com:99999");
  11512. ASSERT_FALSE(cli.is_valid());
  11513. }
  11514. #ifdef CPPHTTPLIB_SSL_ENABLED
  11515. TEST(HostAndPortPropertiesTest, SSL) {
  11516. httplib::SSLClient cli("www.google.com");
  11517. ASSERT_EQ("www.google.com", cli.host());
  11518. ASSERT_EQ(443, cli.port());
  11519. }
  11520. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11521. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11522. std::string cert;
  11523. read_file(CA_CERT_FILE, cert);
  11524. httplib::SSLClient httplib_client("www.google.com");
  11525. // Load CA store first time
  11526. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11527. // Load CA store second time (update)
  11528. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11529. // Verify client is still valid and can make connections
  11530. httplib_client.enable_server_certificate_verification(true);
  11531. auto res = httplib_client.Get("/");
  11532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11533. // Google may return 200 or 301 depending on various factors
  11534. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11535. res->status == StatusCode::MovedPermanently_301);
  11536. }
  11537. TEST(SSLClientTest, ServerNameIndication_Online) {
  11538. auto host = "httpbingo.org";
  11539. auto path = std::string{"/get"};
  11540. SSLClient cli(host, 443);
  11541. auto res = cli.Get(path);
  11542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11543. ASSERT_EQ(StatusCode::OK_200, res->status);
  11544. }
  11545. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11546. // Use a site that will cause SSL verification failure due to self-signed cert
  11547. SSLClient cli("self-signed.badssl.com", 443);
  11548. cli.enable_server_certificate_verification(true);
  11549. auto res = cli.Get("/");
  11550. ASSERT_TRUE(!res);
  11551. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11552. // Verify backend error is captured for SSLServerVerification
  11553. // This occurs when certificate verification fails
  11554. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11555. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11556. EXPECT_NE(0UL, res.ssl_backend_error());
  11557. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11558. // For OpenSSL, ssl_error is 0 for verification errors
  11559. EXPECT_EQ(0, res.ssl_error());
  11560. #if !defined(_WIN32) || \
  11561. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11562. // On non-Windows or when Windows Schannel is disabled, the error comes
  11563. // from OpenSSL's verification
  11564. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11565. res.ssl_backend_error());
  11566. #endif
  11567. #endif
  11568. }
  11569. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11570. // Use a site where hostname doesn't match the certificate
  11571. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11572. SSLClient cli("wrong.host.badssl.com", 443);
  11573. cli.enable_server_certificate_verification(true);
  11574. cli.enable_server_hostname_verification(true);
  11575. auto res = cli.Get("/");
  11576. ASSERT_TRUE(!res);
  11577. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11578. // Verify backend error is captured for hostname verification failure
  11579. EXPECT_NE(0UL, res.ssl_backend_error());
  11580. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11581. // For OpenSSL, ssl_error is 0 for verification errors
  11582. EXPECT_EQ(0, res.ssl_error());
  11583. #if !defined(_WIN32) || \
  11584. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11585. // On non-Windows or when Windows Schannel is disabled, the error comes
  11586. // from OpenSSL's hostname verification
  11587. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11588. res.ssl_backend_error());
  11589. #endif
  11590. #endif
  11591. }
  11592. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11593. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11594. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11595. SSLClient cli("www.google.com", 443);
  11596. cli.enable_server_certificate_verification(true);
  11597. auto res = cli.Get("/");
  11598. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11599. }
  11600. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11601. SSLClient cli("www.google.com", 443);
  11602. cli.enable_server_certificate_verification(true);
  11603. cli.enable_windows_certificate_verification(false);
  11604. auto res = cli.Get("/");
  11605. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11606. }
  11607. #endif
  11608. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11609. Client cli("https://google.com");
  11610. auto res = cli.Get("/");
  11611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11612. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11613. }
  11614. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11615. SSLClient cli("google.com");
  11616. cli.set_ca_cert_path(CA_CERT_FILE);
  11617. auto res = cli.Get("/");
  11618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11619. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11620. }
  11621. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11622. SSLClient cli("google.com");
  11623. cli.enable_server_certificate_verification(true);
  11624. cli.set_ca_cert_path("hello");
  11625. auto res = cli.Get("/");
  11626. ASSERT_TRUE(!res);
  11627. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11628. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11629. // should be set
  11630. EXPECT_EQ(0, res.ssl_error());
  11631. // Verify backend error is captured for SSLLoadingCerts
  11632. // This error occurs when loading CA certificates fails
  11633. EXPECT_NE(0UL, res.ssl_backend_error());
  11634. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11635. // OpenSSL specific error codes:
  11636. // > openssl errstr 0x80000002
  11637. // error:80000002:system library::No such file or directory
  11638. // > openssl errstr 0xA000126
  11639. // error:0A000126:SSL routines::unexpected eof while reading
  11640. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11641. res.ssl_backend_error() == 0xA000126);
  11642. #endif
  11643. }
  11644. TEST(SSLClientTest, ServerCertificateVerification4) {
  11645. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11646. ASSERT_TRUE(svr.is_valid());
  11647. svr.Get("/test", [&](const Request &, Response &res) {
  11648. res.set_content("test", "text/plain");
  11649. svr.stop();
  11650. ASSERT_TRUE(true);
  11651. });
  11652. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11653. auto se = detail::scope_exit([&] {
  11654. t.join();
  11655. ASSERT_FALSE(svr.is_running());
  11656. });
  11657. svr.wait_until_ready();
  11658. SSLClient cli("127.0.0.1", PORT);
  11659. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11660. cli.enable_server_certificate_verification(true);
  11661. cli.set_connection_timeout(30);
  11662. auto res = cli.Get("/test");
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. ASSERT_EQ(StatusCode::OK_200, res->status);
  11665. }
  11666. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11667. std::string cert;
  11668. read_file(CA_CERT_FILE, cert);
  11669. SSLClient cli("google.com");
  11670. cli.load_ca_cert_store(cert.data(), cert.size());
  11671. const auto res = cli.Get("/");
  11672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11673. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11674. }
  11675. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11676. // clang-format off
  11677. static constexpr char cert[] =
  11678. "GlobalSign Root CA\n"
  11679. "==================\n"
  11680. "-----BEGIN CERTIFICATE-----\n"
  11681. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11682. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11683. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11684. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11685. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11686. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11687. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11688. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11689. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11690. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11691. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11692. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11693. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11694. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11695. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11696. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11697. "-----END CERTIFICATE-----\n";
  11698. // clang-format on
  11699. SSLClient cli("google.com");
  11700. cli.load_ca_cert_store(cert, sizeof(cert));
  11701. const auto res = cli.Get("/");
  11702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11703. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11704. }
  11705. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11706. SSLClient cli("www.youtube.com");
  11707. cli.set_ca_cert_path(CA_CERT_FILE);
  11708. cli.enable_server_certificate_verification(true);
  11709. cli.set_follow_location(true);
  11710. auto res = cli.Get("/");
  11711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11712. ASSERT_EQ(StatusCode::OK_200, res->status);
  11713. }
  11714. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11715. SSLClient cli("wWw.YouTube.Com");
  11716. cli.set_ca_cert_path(CA_CERT_FILE);
  11717. cli.enable_server_certificate_verification(true);
  11718. cli.enable_server_hostname_verification(true);
  11719. cli.set_follow_location(true);
  11720. auto res = cli.Get("/");
  11721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11722. ASSERT_EQ(StatusCode::OK_200, res->status);
  11723. }
  11724. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11725. SSLClient cli("gOoGlE.COm");
  11726. cli.enable_server_certificate_verification(true);
  11727. cli.enable_server_hostname_verification(true);
  11728. cli.set_follow_location(true);
  11729. auto res = cli.Get("/");
  11730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11731. ASSERT_EQ(StatusCode::OK_200, res->status);
  11732. }
  11733. TEST(SSLClientTest, Issue2004_Online) {
  11734. Client client("https://google.com");
  11735. client.set_follow_location(true);
  11736. auto res = client.Get("/");
  11737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11738. ASSERT_EQ(StatusCode::OK_200, res->status);
  11739. auto body = res->body;
  11740. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11741. }
  11742. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11743. // Create SSLClient with invalid cert/key to make is_valid() return false
  11744. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11745. "nonexistent_key.pem");
  11746. // is_valid() should be false due to cert loading failure
  11747. ASSERT_FALSE(cli.is_valid());
  11748. auto res = cli.Get("/");
  11749. ASSERT_FALSE(res);
  11750. EXPECT_EQ(Error::SSLConnection, res.error());
  11751. }
  11752. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11753. // Test for Issue #2251: SSL error not properly reported when client cert
  11754. // and key paths are swapped or mismatched
  11755. // This simulates the scenario where user accidentally swaps the cert and key
  11756. // files
  11757. // Using client cert file as private key and vice versa (completely wrong)
  11758. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11759. // Should fail validation due to cert/key mismatch
  11760. ASSERT_FALSE(cli.is_valid());
  11761. // Attempt to make a request should fail with proper error
  11762. auto res = cli.Get("/");
  11763. ASSERT_FALSE(res);
  11764. EXPECT_EQ(Error::SSLConnection, res.error());
  11765. // SSL error should be recorded in the Result object (this is the key fix for
  11766. // Issue #2251)
  11767. auto backend_error = res.ssl_backend_error();
  11768. EXPECT_NE(0u, backend_error);
  11769. }
  11770. // Tests cert/key mismatch detection at the TLS context level
  11771. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11772. // Test that using mismatched cert/key causes connection failure.
  11773. // We verify this at the SSLClient level rather than through internal
  11774. // TLS API functions.
  11775. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11776. cli.enable_server_certificate_verification(false);
  11777. cli.set_connection_timeout(2);
  11778. // The mismatch should cause a connection or handshake error
  11779. auto res = cli.Get("/test");
  11780. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11781. // Either way, the request should fail
  11782. EXPECT_FALSE(res);
  11783. }
  11784. #endif
  11785. #if 0
  11786. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11787. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11788. ASSERT_TRUE(cli != nullptr);
  11789. cli->set_address_family(AF_INET6);
  11790. cli->set_interface("en0");
  11791. auto res = cli->Get("/get");
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. ASSERT_EQ(StatusCode::OK_200, res->status);
  11794. }
  11795. #endif
  11796. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11797. #ifdef CPPHTTPLIB_SSL_ENABLED
  11798. void ClientCertPresent(
  11799. const std::string &client_cert_file,
  11800. const std::string &client_private_key_file,
  11801. const std::string &client_encrypted_private_key_pass = std::string()) {
  11802. using namespace httplib::tls;
  11803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11804. CLIENT_CA_CERT_DIR);
  11805. ASSERT_TRUE(svr.is_valid());
  11806. svr.Get("/test", [&](const Request &req, Response &res) {
  11807. res.set_content("test", "text/plain");
  11808. auto cert = req.peer_cert();
  11809. ASSERT_TRUE(static_cast<bool>(cert));
  11810. std::string common_name = cert.subject_cn();
  11811. EXPECT_EQ("Common Name", common_name);
  11812. });
  11813. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11814. auto se = detail::scope_exit([&] {
  11815. svr.stop();
  11816. t.join();
  11817. ASSERT_FALSE(svr.is_running());
  11818. });
  11819. svr.wait_until_ready();
  11820. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11821. client_encrypted_private_key_pass);
  11822. cli.enable_server_certificate_verification(false);
  11823. cli.set_connection_timeout(30);
  11824. auto res = cli.Get("/test");
  11825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11826. ASSERT_EQ(StatusCode::OK_200, res->status);
  11827. }
  11828. TEST(SSLClientServerTest, ClientCertPresent) {
  11829. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11830. }
  11831. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11832. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11833. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11834. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11835. }
  11836. // PEM memory-based constructor tests (works with all TLS backends)
  11837. void PemMemoryClientCertPresent(
  11838. const std::string &client_cert_file,
  11839. const std::string &client_private_key_file,
  11840. const std::string &client_encrypted_private_key_pass = std::string()) {
  11841. // Read PEM files into memory
  11842. std::string server_cert_pem, server_key_pem;
  11843. std::string client_ca_pem;
  11844. std::string client_cert_pem, client_key_pem;
  11845. read_file(SERVER_CERT_FILE, server_cert_pem);
  11846. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11847. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11848. read_file(client_cert_file, client_cert_pem);
  11849. read_file(client_private_key_file, client_key_pem);
  11850. // Create server with PEM memory
  11851. SSLServer::PemMemory server_pem = {
  11852. server_cert_pem.c_str(),
  11853. server_cert_pem.size(),
  11854. server_key_pem.c_str(),
  11855. server_key_pem.size(),
  11856. client_ca_pem.c_str(),
  11857. client_ca_pem.size(),
  11858. nullptr // no password for server key
  11859. };
  11860. SSLServer svr(server_pem);
  11861. ASSERT_TRUE(svr.is_valid());
  11862. svr.Get("/test", [&](const Request &, Response &res) {
  11863. res.set_content("test", "text/plain");
  11864. });
  11865. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11866. auto se = detail::scope_exit([&] {
  11867. svr.stop();
  11868. t.join();
  11869. ASSERT_FALSE(svr.is_running());
  11870. });
  11871. svr.wait_until_ready();
  11872. // Create client with PEM memory
  11873. const char *password = client_encrypted_private_key_pass.empty()
  11874. ? nullptr
  11875. : client_encrypted_private_key_pass.c_str();
  11876. SSLClient::PemMemory client_pem = {
  11877. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11878. client_key_pem.size(), password};
  11879. SSLClient cli(HOST, PORT, client_pem);
  11880. cli.enable_server_certificate_verification(false);
  11881. cli.set_connection_timeout(30);
  11882. auto res = cli.Get("/test");
  11883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11884. ASSERT_EQ(StatusCode::OK_200, res->status);
  11885. }
  11886. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11887. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11888. }
  11889. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11890. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11891. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11892. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11893. }
  11894. TEST(SSLClientServerTest, ClientCertMissing) {
  11895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11896. CLIENT_CA_CERT_DIR);
  11897. ASSERT_TRUE(svr.is_valid());
  11898. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11899. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11900. auto se = detail::scope_exit([&] {
  11901. svr.stop();
  11902. t.join();
  11903. ASSERT_FALSE(svr.is_running());
  11904. });
  11905. svr.wait_until_ready();
  11906. SSLClient cli(HOST, PORT);
  11907. cli.set_connection_timeout(30);
  11908. auto res = cli.Get("/test");
  11909. ASSERT_TRUE(!res);
  11910. // When client cert is missing and server requires it, connection fails
  11911. // Error type depends on backend implementation
  11912. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11913. res.error() == Error::SSLConnection);
  11914. // Verify backend error is captured
  11915. // Note: This test may have different error codes depending on the exact
  11916. // verification failure
  11917. EXPECT_NE(0UL, res.ssl_backend_error());
  11918. }
  11919. TEST(SSLClientServerTest, TrustDirOptional) {
  11920. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11921. ASSERT_TRUE(svr.is_valid());
  11922. svr.Get("/test", [&](const Request &, Response &res) {
  11923. res.set_content("test", "text/plain");
  11924. });
  11925. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11926. auto se = detail::scope_exit([&] {
  11927. svr.stop();
  11928. t.join();
  11929. ASSERT_FALSE(svr.is_running());
  11930. });
  11931. svr.wait_until_ready();
  11932. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11933. cli.enable_server_certificate_verification(false);
  11934. cli.set_connection_timeout(30);
  11935. auto res = cli.Get("/test");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. ASSERT_EQ(StatusCode::OK_200, res->status);
  11938. }
  11939. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11940. class NoListenSSLServer : public SSLServer {
  11941. public:
  11942. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11943. const char *client_ca_cert_file_path,
  11944. const char *client_ca_cert_dir_path = nullptr)
  11945. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11946. client_ca_cert_dir_path),
  11947. stop_(false) {}
  11948. std::atomic_bool stop_;
  11949. private:
  11950. bool process_and_close_socket(socket_t /*sock*/) override {
  11951. // Don't create SSL context
  11952. while (!stop_.load()) {
  11953. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11954. }
  11955. return true;
  11956. }
  11957. };
  11958. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11959. CLIENT_CA_CERT_FILE);
  11960. ASSERT_TRUE(svr.is_valid());
  11961. svr.Get("/test", [&](const Request &, Response &res) {
  11962. res.set_content("test", "text/plain");
  11963. });
  11964. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11965. auto se = detail::scope_exit([&] {
  11966. svr.stop_ = true;
  11967. svr.stop();
  11968. t.join();
  11969. ASSERT_FALSE(svr.is_running());
  11970. });
  11971. svr.wait_until_ready();
  11972. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11973. cli.enable_server_certificate_verification(false);
  11974. cli.set_connection_timeout(1);
  11975. auto res = cli.Get("/test");
  11976. ASSERT_TRUE(!res);
  11977. EXPECT_EQ(Error::SSLConnection, res.error());
  11978. // Timeout results in WantRead error code (maps to backend-specific value)
  11979. EXPECT_NE(0, res.ssl_error());
  11980. }
  11981. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11982. // Test SSLServer with client certificate verification using the standard
  11983. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11984. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11985. CLIENT_CA_CERT_DIR);
  11986. ASSERT_TRUE(svr.is_valid());
  11987. svr.Get("/test", [&](const Request &req, Response &res) {
  11988. res.set_content("test", "text/plain");
  11989. auto cert = req.peer_cert();
  11990. ASSERT_TRUE(static_cast<bool>(cert));
  11991. auto common_name = cert.subject_cn();
  11992. EXPECT_EQ("Common Name", common_name);
  11993. });
  11994. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11995. auto se = detail::scope_exit([&] {
  11996. svr.stop();
  11997. t.join();
  11998. ASSERT_FALSE(svr.is_running());
  11999. });
  12000. svr.wait_until_ready();
  12001. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12002. cli.enable_server_certificate_verification(false);
  12003. cli.set_connection_timeout(30);
  12004. auto res = cli.Get("/test");
  12005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12006. ASSERT_EQ(StatusCode::OK_200, res->status);
  12007. }
  12008. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12009. // Verifies that wildcard matching and exact matching work consistently
  12010. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12011. using namespace httplib::tls;
  12012. // We need a running server to test against
  12013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12014. ASSERT_TRUE(svr.is_valid());
  12015. svr.Get("/test", [](const Request &, Response &res) {
  12016. res.set_content("ok", "text/plain");
  12017. });
  12018. thread t([&]() { svr.listen(HOST, PORT); });
  12019. auto se = detail::scope_exit([&] {
  12020. svr.stop();
  12021. t.join();
  12022. });
  12023. svr.wait_until_ready();
  12024. bool verify_callback_called = false;
  12025. bool verify_result_wrong = false;
  12026. SSLClient cli(HOST, PORT);
  12027. cli.enable_server_certificate_verification(true);
  12028. cli.set_ca_cert_path(CA_CERT_FILE);
  12029. cli.set_connection_timeout(5);
  12030. // Note: Test certificate has CN="Common Name", not "localhost"
  12031. bool verify_result_cn = false;
  12032. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12033. verify_callback_called = true;
  12034. if (!ctx.cert) return false;
  12035. // Test 1: "Common Name" should match (our test server cert CN)
  12036. verify_result_cn = ctx.check_hostname("Common Name");
  12037. // Test 2: wrong hostname should not match
  12038. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12039. return true; // Accept for the purpose of this test
  12040. });
  12041. auto res = cli.Get("/test");
  12042. // The request may succeed or fail depending on cert configuration
  12043. // but the callback should have been called
  12044. ASSERT_TRUE(verify_callback_called)
  12045. << "Verify callback should have been called";
  12046. // CN="Common Name" should match our test certificate
  12047. //
  12048. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12049. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12050. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12051. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12052. // <openssl/base.h>, which is included transitively when
  12053. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12054. #if defined(OPENSSL_IS_BORINGSSL)
  12055. EXPECT_FALSE(verify_result_cn)
  12056. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12057. #else
  12058. EXPECT_TRUE(verify_result_cn)
  12059. << "verify_hostname should match 'Common Name' (certificate CN)";
  12060. #endif
  12061. // Wrong hostname should not match
  12062. EXPECT_FALSE(verify_result_wrong)
  12063. << "verify_hostname should not match 'wronghost.example.com'";
  12064. }
  12065. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12066. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12067. // X509_check_ip behavior and must hold for every backend.
  12068. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12069. using namespace httplib::tls;
  12070. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12071. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12072. ASSERT_TRUE(svr.is_valid());
  12073. svr.Get("/test", [](const Request &, Response &res) {
  12074. res.set_content("ok", "text/plain");
  12075. });
  12076. thread t([&]() { svr.listen(HOST, PORT); });
  12077. auto se = detail::scope_exit([&] {
  12078. svr.stop();
  12079. t.join();
  12080. });
  12081. svr.wait_until_ready();
  12082. bool verify_callback_called = false;
  12083. bool ip_matched_via_cn = true;
  12084. SSLClient cli(HOST, PORT);
  12085. cli.enable_server_certificate_verification(true);
  12086. cli.set_ca_cert_path(CA_CERT_FILE);
  12087. cli.set_connection_timeout(5);
  12088. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12089. verify_callback_called = true;
  12090. if (!ctx.cert) return false;
  12091. // The IP appears only in the CN, so it must NOT be accepted.
  12092. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12093. return true; // Accept for the purpose of this test
  12094. });
  12095. cli.Get("/test");
  12096. ASSERT_TRUE(verify_callback_called)
  12097. << "Verify callback should have been called";
  12098. EXPECT_FALSE(ip_matched_via_cn)
  12099. << "An IP host must not be authenticated via the certificate CN";
  12100. }
  12101. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12102. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12103. using namespace httplib::tls;
  12104. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12105. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12106. ASSERT_TRUE(svr.is_valid());
  12107. svr.Get("/test", [](const Request &, Response &res) {
  12108. res.set_content("ok", "text/plain");
  12109. });
  12110. thread t([&]() { svr.listen(HOST, PORT); });
  12111. auto se = detail::scope_exit([&] {
  12112. svr.stop();
  12113. t.join();
  12114. });
  12115. svr.wait_until_ready();
  12116. bool verify_callback_called = false;
  12117. bool san_matched = false;
  12118. bool wrong_ipv6_matched = true;
  12119. bool cn_ipv6_matched = true;
  12120. SSLClient cli(HOST, PORT);
  12121. cli.enable_server_certificate_verification(true);
  12122. cli.set_ca_cert_path(CA_CERT_FILE);
  12123. cli.set_connection_timeout(5);
  12124. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12125. verify_callback_called = true;
  12126. if (!ctx.cert) return false;
  12127. // Matches the IPv6 iPAddress SAN.
  12128. san_matched = ctx.check_hostname("2001:db8::1");
  12129. // A different IPv6 address must not match.
  12130. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12131. // "::1" lives only in the CN, so it must not be accepted.
  12132. cn_ipv6_matched = ctx.check_hostname("::1");
  12133. return true; // Accept for the purpose of this test
  12134. });
  12135. cli.Get("/test");
  12136. ASSERT_TRUE(verify_callback_called)
  12137. << "Verify callback should have been called";
  12138. EXPECT_TRUE(san_matched)
  12139. << "verify_hostname should match an IPv6 iPAddress SAN";
  12140. EXPECT_FALSE(wrong_ipv6_matched)
  12141. << "verify_hostname should not match a non-matching IPv6 address";
  12142. EXPECT_FALSE(cn_ipv6_matched)
  12143. << "An IPv6 host must not be authenticated via the certificate CN";
  12144. }
  12145. #endif
  12146. // mbedTLS-specific callback constructor test
  12147. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12148. #ifdef CPPHTTPLIB_SSL_ENABLED
  12149. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12150. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12151. ASSERT_TRUE(svr.is_valid());
  12152. // Set up a handler to verify client certificate is present
  12153. bool client_cert_verified = false;
  12154. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12155. // Verify that client certificate was provided
  12156. client_cert_verified = true;
  12157. res.set_content("success", "text/plain");
  12158. });
  12159. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. t.join();
  12163. ASSERT_FALSE(svr.is_running());
  12164. });
  12165. svr.wait_until_ready();
  12166. // Client with certificate
  12167. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12168. cli.enable_server_certificate_verification(false);
  12169. cli.set_connection_timeout(30);
  12170. auto res = cli.Get("/test");
  12171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12172. ASSERT_EQ(StatusCode::OK_200, res->status);
  12173. ASSERT_TRUE(client_cert_verified);
  12174. EXPECT_EQ("success", res->body);
  12175. }
  12176. #endif
  12177. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12178. // backends
  12179. #ifdef CPPHTTPLIB_SSL_ENABLED
  12180. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12181. using namespace httplib::tls;
  12182. // Test that when client CA cert file is provided,
  12183. // the server properly requests and validates client certificates
  12184. // Create a server with client authentication
  12185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12186. ASSERT_TRUE(svr.is_valid());
  12187. bool handler_called = false;
  12188. svr.Get("/test", [&](const Request &req, Response &res) {
  12189. handler_called = true;
  12190. // Verify that a client certificate was provided
  12191. auto cert = req.peer_cert();
  12192. ASSERT_TRUE(static_cast<bool>(cert));
  12193. // Get the issuer name
  12194. std::string issuer_str = cert.issuer_name();
  12195. ASSERT_FALSE(issuer_str.empty());
  12196. // The client certificate should be issued by our test CA
  12197. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12198. res.set_content("authenticated", "text/plain");
  12199. });
  12200. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12201. auto se = detail::scope_exit([&] {
  12202. svr.stop();
  12203. t.join();
  12204. ASSERT_FALSE(svr.is_running());
  12205. });
  12206. svr.wait_until_ready();
  12207. // Connect with a client certificate issued by the CA
  12208. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12209. cli.enable_server_certificate_verification(false);
  12210. cli.set_connection_timeout(30);
  12211. auto res = cli.Get("/test");
  12212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12213. ASSERT_EQ(StatusCode::OK_200, res->status);
  12214. ASSERT_TRUE(handler_called);
  12215. EXPECT_EQ("authenticated", res->body);
  12216. }
  12217. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12218. using namespace httplib::tls;
  12219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12220. ASSERT_TRUE(svr.is_valid());
  12221. svr.Get("/test", [](const Request &, Response &res) {
  12222. res.set_content("ok", "text/plain");
  12223. });
  12224. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12225. auto se = detail::scope_exit([&] {
  12226. svr.stop();
  12227. t.join();
  12228. });
  12229. svr.wait_until_ready();
  12230. SSLClient cli(HOST, PORT);
  12231. cli.enable_server_certificate_verification(false);
  12232. cli.set_connection_timeout(30);
  12233. bool cert_checked = false;
  12234. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12235. if (ctx.cert) {
  12236. auto sans = ctx.sans();
  12237. // Test certificate may or may not have SANs - just verify the API
  12238. // works If SANs exist, verify the types are valid
  12239. for (const auto &san : sans) {
  12240. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12241. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12242. san.type == SanType::OTHER);
  12243. EXPECT_FALSE(san.value.empty());
  12244. }
  12245. cert_checked = true;
  12246. }
  12247. return true;
  12248. });
  12249. auto res = cli.Get("/test");
  12250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12251. EXPECT_TRUE(cert_checked);
  12252. }
  12253. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12254. using namespace httplib::tls;
  12255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12256. ASSERT_TRUE(svr.is_valid());
  12257. svr.Get("/test", [](const Request &, Response &res) {
  12258. res.set_content("ok", "text/plain");
  12259. });
  12260. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12261. auto se = detail::scope_exit([&] {
  12262. svr.stop();
  12263. t.join();
  12264. });
  12265. svr.wait_until_ready();
  12266. SSLClient cli(HOST, PORT);
  12267. cli.enable_server_certificate_verification(false);
  12268. cli.set_connection_timeout(30);
  12269. bool validity_checked = false;
  12270. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12271. if (ctx.cert) {
  12272. time_t not_before = 0, not_after = 0;
  12273. bool result = ctx.validity(not_before, not_after);
  12274. EXPECT_TRUE(result);
  12275. // Verify that not_before < now < not_after for a valid cert
  12276. time_t now = time(nullptr);
  12277. EXPECT_LT(not_before, now);
  12278. EXPECT_GT(not_after, now);
  12279. validity_checked = true;
  12280. }
  12281. return true;
  12282. });
  12283. auto res = cli.Get("/test");
  12284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12285. EXPECT_TRUE(validity_checked);
  12286. }
  12287. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12288. using namespace httplib::tls;
  12289. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12290. ASSERT_TRUE(svr.is_valid());
  12291. svr.Get("/test", [](const Request &, Response &res) {
  12292. res.set_content("ok", "text/plain");
  12293. });
  12294. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12295. auto se = detail::scope_exit([&] {
  12296. svr.stop();
  12297. t.join();
  12298. });
  12299. svr.wait_until_ready();
  12300. SSLClient cli(HOST, PORT);
  12301. cli.enable_server_certificate_verification(false);
  12302. cli.set_connection_timeout(30);
  12303. bool serial_checked = false;
  12304. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12305. if (ctx.cert) {
  12306. std::string serial = ctx.serial();
  12307. EXPECT_FALSE(serial.empty());
  12308. // Serial should be a hex string
  12309. for (char c : serial) {
  12310. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12311. (c >= 'a' && c <= 'f'));
  12312. }
  12313. serial_checked = true;
  12314. }
  12315. return true;
  12316. });
  12317. auto res = cli.Get("/test");
  12318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12319. EXPECT_TRUE(serial_checked);
  12320. }
  12321. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12322. // Test 1: Valid CA file - no error should be recorded
  12323. {
  12324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12325. CLIENT_CA_CERT_FILE);
  12326. ASSERT_TRUE(svr.is_valid());
  12327. // With valid setup, last_ssl_error should be 0
  12328. EXPECT_EQ(0, svr.ssl_last_error());
  12329. }
  12330. // Test 2: Invalid CA file content
  12331. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12332. {
  12333. // Create a temporary file with completely invalid content
  12334. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12335. {
  12336. std::ofstream ofs(temp_invalid_ca);
  12337. ofs << "This is not a certificate file at all\n";
  12338. ofs << "Just plain text content\n";
  12339. }
  12340. // Create server with invalid CA file
  12341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12342. // Clean up temporary file
  12343. std::remove(temp_invalid_ca);
  12344. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12345. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12346. // Note: SSL_CTX_load_verify_locations typically fails first,
  12347. // but our error handling code path is still exercised
  12348. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12349. }
  12350. }
  12351. TEST(VerifyCallbackTest, VerifyContextFields) {
  12352. using namespace httplib::tls;
  12353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12354. ASSERT_TRUE(svr.is_valid());
  12355. svr.Get("/test", [](const Request &, Response &res) {
  12356. res.set_content("ok", "text/plain");
  12357. });
  12358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12359. auto se = detail::scope_exit([&] {
  12360. svr.stop();
  12361. t.join();
  12362. });
  12363. svr.wait_until_ready();
  12364. SSLClient cli(HOST, PORT);
  12365. cli.enable_server_certificate_verification(false);
  12366. cli.set_connection_timeout(30);
  12367. int callback_count = 0;
  12368. bool saw_leaf_cert = false;
  12369. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12370. if (ctx.cert) {
  12371. callback_count++;
  12372. // We should see at least one certificate (the leaf)
  12373. std::string cn = ctx.subject_cn();
  12374. if (!cn.empty()) { saw_leaf_cert = true; }
  12375. // Verify context fields are populated
  12376. EXPECT_NE(ctx.session, nullptr);
  12377. EXPECT_GE(ctx.depth, 0);
  12378. }
  12379. return true;
  12380. });
  12381. auto res = cli.Get("/test");
  12382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12383. EXPECT_GT(callback_count, 0);
  12384. EXPECT_TRUE(saw_leaf_cert);
  12385. }
  12386. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12387. using httplib::tls::TlsError;
  12388. // Test that verify_error_to_string returns empty for success
  12389. std::string success_str = TlsError::verify_error_to_string(0);
  12390. EXPECT_TRUE(success_str.empty());
  12391. // Test that verify_error_to_string returns non-empty for error codes
  12392. // Using a common error code (certificate expired)
  12393. std::string error_str =
  12394. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12395. EXPECT_FALSE(error_str.empty());
  12396. }
  12397. TEST(SessionVerifierTest, CertificateAccepted) {
  12398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12399. ASSERT_TRUE(svr.is_valid());
  12400. svr.Get("/test", [](const Request &, Response &res) {
  12401. res.set_content("ok", "text/plain");
  12402. });
  12403. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12404. auto se = detail::scope_exit([&] {
  12405. svr.stop();
  12406. t.join();
  12407. });
  12408. svr.wait_until_ready();
  12409. SSLClient cli(HOST, PORT);
  12410. cli.enable_server_certificate_verification(false);
  12411. cli.set_connection_timeout(30);
  12412. bool callback_called = false;
  12413. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12414. EXPECT_NE(session, nullptr);
  12415. callback_called = true;
  12416. return SSLVerifierResponse::CertificateAccepted;
  12417. });
  12418. auto res = cli.Get("/test");
  12419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12420. EXPECT_EQ(200, res->status);
  12421. EXPECT_TRUE(callback_called);
  12422. }
  12423. TEST(SessionVerifierTest, CertificateRejected) {
  12424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12425. ASSERT_TRUE(svr.is_valid());
  12426. svr.Get("/test", [](const Request &, Response &res) {
  12427. res.set_content("ok", "text/plain");
  12428. });
  12429. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12430. auto se = detail::scope_exit([&] {
  12431. svr.stop();
  12432. t.join();
  12433. });
  12434. svr.wait_until_ready();
  12435. SSLClient cli(HOST, PORT);
  12436. cli.enable_server_certificate_verification(false);
  12437. cli.set_connection_timeout(30);
  12438. bool callback_called = false;
  12439. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12440. EXPECT_NE(session, nullptr);
  12441. callback_called = true;
  12442. return SSLVerifierResponse::CertificateRejected;
  12443. });
  12444. auto res = cli.Get("/test");
  12445. EXPECT_FALSE(res);
  12446. EXPECT_TRUE(callback_called);
  12447. }
  12448. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12450. ASSERT_TRUE(svr.is_valid());
  12451. svr.Get("/test", [](const Request &, Response &res) {
  12452. res.set_content("ok", "text/plain");
  12453. });
  12454. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12455. auto se = detail::scope_exit([&] {
  12456. svr.stop();
  12457. t.join();
  12458. });
  12459. svr.wait_until_ready();
  12460. // NoDecisionMade with verification disabled should succeed (no default check)
  12461. SSLClient cli(HOST, PORT);
  12462. cli.enable_server_certificate_verification(false);
  12463. cli.set_connection_timeout(30);
  12464. bool callback_called = false;
  12465. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12466. EXPECT_NE(session, nullptr);
  12467. callback_called = true;
  12468. return SSLVerifierResponse::NoDecisionMade;
  12469. });
  12470. auto res = cli.Get("/test");
  12471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12472. EXPECT_EQ(200, res->status);
  12473. EXPECT_TRUE(callback_called);
  12474. }
  12475. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12477. ASSERT_TRUE(svr.is_valid());
  12478. svr.Get("/test", [](const Request &, Response &res) {
  12479. res.set_content("ok", "text/plain");
  12480. });
  12481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12482. auto se = detail::scope_exit([&] {
  12483. svr.stop();
  12484. t.join();
  12485. });
  12486. svr.wait_until_ready();
  12487. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12488. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12489. // so we only check that the request fails, not whether the callback was
  12490. // called.
  12491. SSLClient cli(HOST, PORT);
  12492. cli.enable_server_certificate_verification(true);
  12493. cli.set_connection_timeout(30);
  12494. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12495. EXPECT_NE(session, nullptr);
  12496. return SSLVerifierResponse::NoDecisionMade;
  12497. });
  12498. auto res = cli.Get("/test");
  12499. EXPECT_FALSE(res);
  12500. }
  12501. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12502. // Test SSL server using PemMemory constructor with client CA certificates
  12503. // Read PEM files
  12504. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12505. read_file(SERVER_CERT_FILE, server_cert_pem);
  12506. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12507. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12508. // Create SSLServer with PemMemory constructor including client CA
  12509. SSLServer::PemMemory server_pem = {
  12510. server_cert_pem.c_str(),
  12511. server_cert_pem.size(),
  12512. server_key_pem.c_str(),
  12513. server_key_pem.size(),
  12514. client_ca_pem.c_str(),
  12515. client_ca_pem.size(),
  12516. nullptr // no password for server key
  12517. };
  12518. SSLServer svr(server_pem);
  12519. ASSERT_TRUE(svr.is_valid());
  12520. // No SSL error should be recorded for valid setup
  12521. EXPECT_EQ(0, svr.ssl_last_error());
  12522. // Set up server endpoints
  12523. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12524. res.set_content("ok", "text/plain");
  12525. });
  12526. // Start server in a thread
  12527. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12528. svr.wait_until_ready();
  12529. // Connect with client certificate (using constructor with paths)
  12530. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12531. cli.enable_server_certificate_verification(false);
  12532. auto res = cli.Get("/test-pem-ca");
  12533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12534. EXPECT_EQ(200, res->status);
  12535. EXPECT_EQ("ok", res->body);
  12536. svr.stop();
  12537. server_thread.join();
  12538. }
  12539. #endif
  12540. #ifdef _WIN32
  12541. TEST(CleanupTest, WSACleanup) {
  12542. int ret = WSACleanup();
  12543. ASSERT_EQ(0, ret);
  12544. }
  12545. #endif
  12546. #ifndef CPPHTTPLIB_SSL_ENABLED
  12547. TEST(NoSSLSupport, SimpleInterface) {
  12548. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12549. }
  12550. #endif
  12551. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12552. TEST(InvalidScheme, SimpleInterface) {
  12553. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12554. }
  12555. #endif
  12556. TEST(NoScheme, SimpleInterface) {
  12557. Client cli("yahoo.com:80");
  12558. ASSERT_TRUE(cli.is_valid());
  12559. }
  12560. TEST(SendAPI, SimpleInterface_Online) {
  12561. Client cli("http://yahoo.com");
  12562. Request req;
  12563. req.method = "GET";
  12564. req.path = "/";
  12565. auto res = cli.send(req);
  12566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12567. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12568. }
  12569. TEST(SendAPI, WithParamsInRequest) {
  12570. Server svr;
  12571. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12572. EXPECT_TRUE(req.has_param("test"));
  12573. EXPECT_EQ("test_value", req.get_param_value("test"));
  12574. });
  12575. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12576. auto se = detail::scope_exit([&] {
  12577. svr.stop();
  12578. t.join();
  12579. ASSERT_FALSE(svr.is_running());
  12580. });
  12581. svr.wait_until_ready();
  12582. Client cli(HOST, PORT);
  12583. {
  12584. Request req;
  12585. req.method = "GET";
  12586. req.path = "/";
  12587. req.params.emplace("test", "test_value");
  12588. auto res = cli.send(req);
  12589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12590. }
  12591. {
  12592. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12594. }
  12595. }
  12596. TEST(ClientImplMethods, GetSocketTest) {
  12597. httplib::Server svr;
  12598. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12599. res.status = StatusCode::OK_200;
  12600. });
  12601. auto port = svr.bind_to_any_port("127.0.0.1");
  12602. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. thread.join();
  12606. ASSERT_FALSE(svr.is_running());
  12607. });
  12608. svr.wait_until_ready();
  12609. {
  12610. httplib::Client cli("127.0.0.1", port);
  12611. cli.set_keep_alive(true);
  12612. // Use the behavior of cpp-httplib of opening the connection
  12613. // only when the first request happens. If that changes,
  12614. // this test would be obsolete.
  12615. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12616. // This also implicitly tests the server. But other tests would fail much
  12617. // earlier than this one to be considered.
  12618. auto res = cli.Get("/");
  12619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12620. EXPECT_EQ(StatusCode::OK_200, res->status);
  12621. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12622. }
  12623. }
  12624. #ifdef CPPHTTPLIB_SSL_ENABLED
  12625. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12626. Client cli("http://yahoo.com");
  12627. auto res = cli.Get("/");
  12628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12629. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12630. cli.set_follow_location(true);
  12631. res = cli.Get("/");
  12632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12633. EXPECT_EQ(StatusCode::OK_200, res->status);
  12634. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12635. }
  12636. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12637. Client cli("https://yahoo.com");
  12638. auto res = cli.Get("/");
  12639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12640. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12641. cli.set_follow_location(true);
  12642. res = cli.Get("/");
  12643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12644. EXPECT_EQ(StatusCode::OK_200, res->status);
  12645. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12646. }
  12647. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12648. Client cli("https://yahoo.com");
  12649. auto res = cli.Get("/");
  12650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12651. ASSERT_FALSE(!res);
  12652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12653. ASSERT_FALSE(res == nullptr);
  12654. ASSERT_TRUE(res != nullptr);
  12655. EXPECT_EQ(Error::Success, res.error());
  12656. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12657. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12658. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12659. cli.set_follow_location(true);
  12660. res = cli.Get("/");
  12661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12662. EXPECT_EQ(Error::Success, res.error());
  12663. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12664. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12665. EXPECT_EQ(StatusCode::OK_200, res->status);
  12666. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12667. }
  12668. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12669. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12670. Client cli("https://cdnjs.cloudflare.com");
  12671. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12672. Headers{{"Accept-Encoding", "br"}});
  12673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12674. EXPECT_EQ(StatusCode::OK_200, res->status);
  12675. EXPECT_EQ(287630U, res->body.size());
  12676. EXPECT_EQ("application/javascript; charset=utf-8",
  12677. res->get_header_value("Content-Type"));
  12678. }
  12679. #endif
  12680. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12681. #undef REDIR_HOST // Silence compiler warning
  12682. #define REDIR_HOST "https://httpbingo.org"
  12683. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12684. Client cli(REDIR_HOST);
  12685. cli.set_follow_location(true);
  12686. auto res =
  12687. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12689. EXPECT_EQ(StatusCode::OK_200, res->status);
  12690. }
  12691. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12692. Client cli(REDIR_HOST);
  12693. cli.set_follow_location(true);
  12694. Params params;
  12695. params.emplace("url", "http://example.com");
  12696. params.emplace("status_code", "302");
  12697. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12699. EXPECT_EQ(StatusCode::OK_200, res->status);
  12700. }
  12701. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12702. Client cli(REDIR_HOST);
  12703. cli.set_follow_location(true);
  12704. Params params;
  12705. params.emplace("url", "http://example.com");
  12706. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12708. EXPECT_EQ(StatusCode::OK_200, res->status);
  12709. }
  12710. TEST(HttpToHttpsRedirectTest, CertFile) {
  12711. auto ssl_port = PORT + 1;
  12712. Server svr;
  12713. ASSERT_TRUE(svr.is_valid());
  12714. svr.Get("/index", [&](const Request &, Response &res) {
  12715. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12716. "/index");
  12717. svr.stop();
  12718. });
  12719. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12720. ASSERT_TRUE(ssl_svr.is_valid());
  12721. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12722. res.set_content("test", "text/plain");
  12723. ssl_svr.stop();
  12724. });
  12725. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12726. thread t2 =
  12727. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12728. auto se = detail::scope_exit([&] {
  12729. t2.join();
  12730. t.join();
  12731. ASSERT_FALSE(svr.is_running());
  12732. });
  12733. svr.wait_until_ready();
  12734. ssl_svr.wait_until_ready();
  12735. Client cli("127.0.0.1", PORT);
  12736. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12737. cli.enable_server_certificate_verification(true);
  12738. cli.set_follow_location(true);
  12739. cli.set_connection_timeout(30);
  12740. auto res = cli.Get("/index");
  12741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12742. ASSERT_EQ(StatusCode::OK_200, res->status);
  12743. }
  12744. TEST(SSLClientRedirectTest, CertFile) {
  12745. auto ssl_port = PORT + 1;
  12746. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12747. ASSERT_TRUE(ssl_svr1.is_valid());
  12748. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12749. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12750. "/index");
  12751. ssl_svr1.stop();
  12752. });
  12753. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12754. ASSERT_TRUE(ssl_svr2.is_valid());
  12755. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12756. res.set_content("test", "text/plain");
  12757. ssl_svr2.stop();
  12758. });
  12759. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12760. thread t2 =
  12761. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12762. auto se = detail::scope_exit([&] {
  12763. t2.join();
  12764. t.join();
  12765. ASSERT_FALSE(ssl_svr1.is_running());
  12766. });
  12767. ssl_svr1.wait_until_ready();
  12768. ssl_svr2.wait_until_ready();
  12769. SSLClient cli("127.0.0.1", PORT);
  12770. std::string cert;
  12771. read_file(SERVER_CERT2_FILE, cert);
  12772. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12773. cli.enable_server_certificate_verification(true);
  12774. cli.set_follow_location(true);
  12775. cli.set_connection_timeout(30);
  12776. auto res = cli.Get("/index");
  12777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12778. ASSERT_EQ(StatusCode::OK_200, res->status);
  12779. }
  12780. #endif
  12781. #ifdef CPPHTTPLIB_SSL_ENABLED
  12782. // Test that set_ca_cert_store() skips system certs (consistent with
  12783. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12784. // should be trusted - system certs should NOT be loaded.
  12785. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12786. // Load a specific cert that is NOT a system CA cert
  12787. std::string cert;
  12788. read_file(SERVER_CERT2_FILE, cert);
  12789. SSLClient cli("google.com");
  12790. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12791. cli.enable_server_certificate_verification(true);
  12792. // This should FAIL because:
  12793. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12794. // 2. System certs should NOT be loaded when custom store is set
  12795. // If system certs WERE loaded, this would succeed
  12796. auto res = cli.Get("/");
  12797. ASSERT_FALSE(res);
  12798. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12799. }
  12800. // Same as above, but through the native store handle path. Regression test:
  12801. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12802. // merged system certs into the user-provided store.
  12803. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12804. std::string cert;
  12805. read_file(SERVER_CERT2_FILE, cert);
  12806. SSLClient cli("google.com");
  12807. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12808. cli.enable_server_certificate_verification(true);
  12809. auto res = cli.Get("/");
  12810. ASSERT_FALSE(res);
  12811. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12812. }
  12813. // A custom store set via the native handle must still verify a server whose
  12814. // cert it does contain.
  12815. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12816. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12817. ASSERT_TRUE(svr.is_valid());
  12818. svr.Get("/test", [&](const Request &, Response &res) {
  12819. res.set_content("test", "text/plain");
  12820. });
  12821. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12822. auto se = detail::scope_exit([&] {
  12823. svr.stop();
  12824. t.join();
  12825. ASSERT_FALSE(svr.is_running());
  12826. });
  12827. svr.wait_until_ready();
  12828. SSLClient cli("127.0.0.1", PORT);
  12829. std::string cert;
  12830. read_file(SERVER_CERT2_FILE, cert);
  12831. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12832. cli.enable_server_certificate_verification(true);
  12833. cli.set_connection_timeout(30);
  12834. auto res = cli.Get("/test");
  12835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12836. ASSERT_EQ(StatusCode::OK_200, res->status);
  12837. }
  12838. // CA certs loaded through the universal Client must be transferred to the
  12839. // client created internally for following an HTTPS redirect. Regression test:
  12840. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12841. // the CA data for redirect transfer.
  12842. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12843. auto ssl_port = PORT + 1;
  12844. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12845. ASSERT_TRUE(ssl_svr1.is_valid());
  12846. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12847. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12848. "/index");
  12849. });
  12850. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12851. ASSERT_TRUE(ssl_svr2.is_valid());
  12852. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12853. res.set_content("test", "text/plain");
  12854. });
  12855. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12856. thread t2 =
  12857. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12858. auto se = detail::scope_exit([&] {
  12859. ssl_svr2.stop();
  12860. ssl_svr1.stop();
  12861. t2.join();
  12862. t.join();
  12863. ASSERT_FALSE(ssl_svr1.is_running());
  12864. });
  12865. ssl_svr1.wait_until_ready();
  12866. ssl_svr2.wait_until_ready();
  12867. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12868. std::string cert;
  12869. read_file(SERVER_CERT2_FILE, cert);
  12870. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12871. cli.enable_server_certificate_verification(true);
  12872. cli.set_follow_location(true);
  12873. cli.set_connection_timeout(30);
  12874. auto res = cli.Get("/index");
  12875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12876. ASSERT_EQ(StatusCode::OK_200, res->status);
  12877. }
  12878. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12879. // so a host signed by a system CA verifies even though a custom CA is set
  12880. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12881. std::string cert;
  12882. read_file(SERVER_CERT2_FILE, cert);
  12883. SSLClient cli("google.com");
  12884. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12885. cli.enable_system_ca(true);
  12886. cli.enable_server_certificate_verification(true);
  12887. auto res = cli.Get("/");
  12888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12889. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12890. }
  12891. // The custom CA remains effective when combined with the system CA
  12892. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12893. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12894. ASSERT_TRUE(svr.is_valid());
  12895. svr.Get("/test", [&](const Request &, Response &res) {
  12896. res.set_content("test", "text/plain");
  12897. });
  12898. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12899. auto se = detail::scope_exit([&] {
  12900. svr.stop();
  12901. t.join();
  12902. ASSERT_FALSE(svr.is_running());
  12903. });
  12904. svr.wait_until_ready();
  12905. SSLClient cli("127.0.0.1", PORT);
  12906. std::string cert;
  12907. read_file(SERVER_CERT2_FILE, cert);
  12908. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12909. cli.enable_system_ca(true);
  12910. cli.enable_server_certificate_verification(true);
  12911. cli.set_connection_timeout(30);
  12912. auto res = cli.Get("/test");
  12913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12914. ASSERT_EQ(StatusCode::OK_200, res->status);
  12915. }
  12916. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12917. // skip chain verification entirely (only the certificate identity was
  12918. // checked), so a server presenting an untrusted certificate with a matching
  12919. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12920. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12921. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12922. ASSERT_TRUE(svr.is_valid());
  12923. svr.Get("/test", [&](const Request &, Response &res) {
  12924. res.set_content("test", "text/plain");
  12925. });
  12926. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12927. auto se = detail::scope_exit([&] {
  12928. svr.stop();
  12929. t.join();
  12930. ASSERT_FALSE(svr.is_running());
  12931. });
  12932. svr.wait_until_ready();
  12933. SSLClient cli("127.0.0.1", PORT);
  12934. std::string cert;
  12935. // A trusted CA that did not sign the server certificate. The server cert
  12936. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12937. // this connection.
  12938. read_file(CLIENT_CA_CERT_FILE, cert);
  12939. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12940. cli.enable_server_certificate_verification(true);
  12941. cli.set_connection_timeout(30);
  12942. auto res = cli.Get("/test");
  12943. ASSERT_FALSE(res);
  12944. }
  12945. // enable_system_ca(false) prevents system CA loading entirely
  12946. TEST(SSLClientTest, DisableSystemCa_Online) {
  12947. SSLClient cli("google.com");
  12948. cli.enable_system_ca(false);
  12949. cli.enable_server_certificate_verification(true);
  12950. auto res = cli.Get("/");
  12951. ASSERT_FALSE(res);
  12952. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12953. // itself when the CA chain is empty
  12954. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12955. res.error() == Error::SSLConnection);
  12956. }
  12957. // The universal Client forwards enable_system_ca()
  12958. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12959. std::string cert;
  12960. read_file(SERVER_CERT2_FILE, cert);
  12961. Client cli("https://google.com");
  12962. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12963. cli.enable_system_ca(true);
  12964. cli.enable_server_certificate_verification(true);
  12965. auto res = cli.Get("/");
  12966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12967. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12968. }
  12969. // The system CA policy must carry over to the client created internally for
  12970. // following a cross-host HTTPS redirect
  12971. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12972. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12973. ASSERT_TRUE(svr.is_valid());
  12974. svr.Get("/index", [&](const Request &, Response &res) {
  12975. res.set_redirect("https://www.google.com/");
  12976. });
  12977. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12978. auto se = detail::scope_exit([&] {
  12979. svr.stop();
  12980. t.join();
  12981. ASSERT_FALSE(svr.is_running());
  12982. });
  12983. svr.wait_until_ready();
  12984. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12985. std::string cert;
  12986. read_file(SERVER_CERT2_FILE, cert);
  12987. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12988. cli.enable_system_ca(true);
  12989. cli.enable_server_certificate_verification(true);
  12990. cli.set_follow_location(true);
  12991. cli.set_connection_timeout(30);
  12992. // Receiving any response proves the redirect client completed the TLS
  12993. // handshake with a system-CA-signed host
  12994. auto res = cli.Get("/index");
  12995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12996. }
  12997. TEST(MultipartFormDataTest, LargeData) {
  12998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12999. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13000. const ContentReader &content_reader) {
  13001. if (req.is_multipart_form_data()) {
  13002. std::vector<FormData> items;
  13003. content_reader(
  13004. [&](const FormData &file) {
  13005. items.push_back(file);
  13006. return true;
  13007. },
  13008. [&](const char *data, size_t data_length) {
  13009. items.back().content.append(data, data_length);
  13010. return true;
  13011. });
  13012. EXPECT_TRUE(std::string(items[0].name) == "document");
  13013. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13014. EXPECT_TRUE(items[0].filename == "2MB_data");
  13015. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13016. EXPECT_TRUE(items[1].name == "hello");
  13017. EXPECT_TRUE(items[1].content == "world");
  13018. EXPECT_TRUE(items[1].filename == "");
  13019. EXPECT_TRUE(items[1].content_type == "");
  13020. } else {
  13021. std::string body;
  13022. content_reader([&](const char *data, size_t data_length) {
  13023. body.append(data, data_length);
  13024. return true;
  13025. });
  13026. }
  13027. });
  13028. auto port = svr.bind_to_any_port(HOST);
  13029. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13030. auto se = detail::scope_exit([&] {
  13031. svr.stop();
  13032. t.join();
  13033. ASSERT_FALSE(svr.is_running());
  13034. });
  13035. svr.wait_until_ready();
  13036. {
  13037. std::string data(1024 * 1024 * 2, '.');
  13038. std::stringstream buffer;
  13039. buffer << data;
  13040. SSLClient cli(HOST, port);
  13041. cli.enable_server_certificate_verification(false);
  13042. UploadFormDataItems items{
  13043. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13044. {"hello", "world", "", ""},
  13045. };
  13046. auto res = cli.Post("/post", items);
  13047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13048. ASSERT_EQ(StatusCode::OK_200, res->status);
  13049. }
  13050. }
  13051. TEST(MultipartFormDataTest, DataProviderItems) {
  13052. std::random_device seed_gen;
  13053. std::mt19937 random(seed_gen());
  13054. std::string rand1;
  13055. rand1.resize(1000);
  13056. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13057. std::string rand2;
  13058. rand2.resize(3000);
  13059. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13061. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13062. const ContentReader &content_reader) {
  13063. ASSERT_FALSE(req.is_multipart_form_data());
  13064. std::string body;
  13065. content_reader([&](const char *data, size_t data_length) {
  13066. body.append(data, data_length);
  13067. return true;
  13068. });
  13069. EXPECT_EQ(body, "");
  13070. });
  13071. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13072. const ContentReader &content_reader) {
  13073. ASSERT_TRUE(req.is_multipart_form_data());
  13074. std::vector<FormData> items;
  13075. content_reader(
  13076. [&](const FormData &file) {
  13077. items.push_back(file);
  13078. return true;
  13079. },
  13080. [&](const char *data, size_t data_length) {
  13081. items.back().content.append(data, data_length);
  13082. return true;
  13083. });
  13084. ASSERT_TRUE(items.size() == 2);
  13085. EXPECT_EQ(std::string(items[0].name), "name1");
  13086. EXPECT_EQ(items[0].content, "Testing123");
  13087. EXPECT_EQ(items[0].filename, "filename1");
  13088. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13089. EXPECT_EQ(items[1].name, "name2");
  13090. EXPECT_EQ(items[1].content, "Testing456");
  13091. EXPECT_EQ(items[1].filename, "");
  13092. EXPECT_EQ(items[1].content_type, "");
  13093. });
  13094. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13095. const ContentReader &content_reader) {
  13096. ASSERT_TRUE(req.is_multipart_form_data());
  13097. std::vector<FormData> items;
  13098. content_reader(
  13099. [&](const FormData &file) {
  13100. items.push_back(file);
  13101. return true;
  13102. },
  13103. [&](const char *data, size_t data_length) {
  13104. items.back().content.append(data, data_length);
  13105. return true;
  13106. });
  13107. ASSERT_TRUE(items.size() == 2);
  13108. EXPECT_EQ(items[0].name, "name3");
  13109. EXPECT_EQ(items[0].content, rand1);
  13110. EXPECT_EQ(items[0].filename, "filename3");
  13111. EXPECT_EQ(items[0].content_type, "");
  13112. EXPECT_EQ(items[1].name, "name4");
  13113. EXPECT_EQ(items[1].content, rand2);
  13114. EXPECT_EQ(items[1].filename, "filename4");
  13115. EXPECT_EQ(items[1].content_type, "");
  13116. });
  13117. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13118. const ContentReader &content_reader) {
  13119. ASSERT_TRUE(req.is_multipart_form_data());
  13120. std::vector<FormData> items;
  13121. content_reader(
  13122. [&](const FormData &file) {
  13123. items.push_back(file);
  13124. return true;
  13125. },
  13126. [&](const char *data, size_t data_length) {
  13127. items.back().content.append(data, data_length);
  13128. return true;
  13129. });
  13130. ASSERT_TRUE(items.size() == 4);
  13131. EXPECT_EQ(std::string(items[0].name), "name1");
  13132. EXPECT_EQ(items[0].content, "Testing123");
  13133. EXPECT_EQ(items[0].filename, "filename1");
  13134. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13135. EXPECT_EQ(items[1].name, "name2");
  13136. EXPECT_EQ(items[1].content, "Testing456");
  13137. EXPECT_EQ(items[1].filename, "");
  13138. EXPECT_EQ(items[1].content_type, "");
  13139. EXPECT_EQ(items[2].name, "name3");
  13140. EXPECT_EQ(items[2].content, rand1);
  13141. EXPECT_EQ(items[2].filename, "filename3");
  13142. EXPECT_EQ(items[2].content_type, "");
  13143. EXPECT_EQ(items[3].name, "name4");
  13144. EXPECT_EQ(items[3].content, rand2);
  13145. EXPECT_EQ(items[3].filename, "filename4");
  13146. EXPECT_EQ(items[3].content_type, "");
  13147. });
  13148. auto port = svr.bind_to_any_port("localhost");
  13149. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13150. auto se = detail::scope_exit([&] {
  13151. svr.stop();
  13152. t.join();
  13153. ASSERT_FALSE(svr.is_running());
  13154. });
  13155. svr.wait_until_ready();
  13156. {
  13157. SSLClient cli("localhost", port);
  13158. cli.enable_server_certificate_verification(false);
  13159. UploadFormDataItems items{
  13160. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13161. {"name2", "Testing456", "", ""}, // not a file
  13162. };
  13163. {
  13164. auto res = cli.Post("/post-none", {}, {}, {});
  13165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13166. ASSERT_EQ(StatusCode::OK_200, res->status);
  13167. }
  13168. FormDataProviderItems providers;
  13169. {
  13170. auto res =
  13171. cli.Post("/post-items", {}, items, providers); // empty providers
  13172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13173. ASSERT_EQ(StatusCode::OK_200, res->status);
  13174. }
  13175. providers.push_back({"name3",
  13176. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13177. // test the offset is given correctly at each step
  13178. if (!offset)
  13179. sink.os.write(rand1.data(), 30);
  13180. else if (offset == 30)
  13181. sink.os.write(rand1.data() + 30, 300);
  13182. else if (offset == 330)
  13183. sink.os.write(rand1.data() + 330, 670);
  13184. else if (offset == rand1.size())
  13185. sink.done();
  13186. return true;
  13187. },
  13188. "filename3",
  13189. {}});
  13190. providers.push_back({"name4",
  13191. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13192. // test the offset is given correctly at each step
  13193. if (!offset)
  13194. sink.os.write(rand2.data(), 2000);
  13195. else if (offset == 2000)
  13196. sink.os.write(rand2.data() + 2000, 1);
  13197. else if (offset == 2001)
  13198. sink.os.write(rand2.data() + 2001, 999);
  13199. else if (offset == rand2.size())
  13200. sink.done();
  13201. return true;
  13202. },
  13203. "filename4",
  13204. {}});
  13205. {
  13206. auto res = cli.Post("/post-providers", {}, {}, providers);
  13207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13208. ASSERT_EQ(StatusCode::OK_200, res->status);
  13209. }
  13210. {
  13211. auto res = cli.Post("/post-both", {}, items, providers);
  13212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13213. ASSERT_EQ(StatusCode::OK_200, res->status);
  13214. }
  13215. }
  13216. }
  13217. TEST(MultipartFormDataTest, BadHeader) {
  13218. Server svr;
  13219. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13220. res.set_content("ok", "text/plain");
  13221. });
  13222. thread t = thread([&] { svr.listen(HOST, PORT); });
  13223. auto se = detail::scope_exit([&] {
  13224. svr.stop();
  13225. t.join();
  13226. ASSERT_FALSE(svr.is_running());
  13227. });
  13228. svr.wait_until_ready();
  13229. const std::string body =
  13230. "This is the preamble. It is to be ignored, though it\r\n"
  13231. "is a handy place for composition agents to include an\r\n"
  13232. "explanatory note to non-MIME conformant readers.\r\n"
  13233. "\r\n"
  13234. "\r\n"
  13235. "--simple boundary\r\n"
  13236. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13237. ": BAD...\r\n"
  13238. "\r\n"
  13239. "value1\r\n"
  13240. "--simple boundary\r\n"
  13241. "Content-Disposition: form-data; name=\"field2\"; "
  13242. "filename=\"example.txt\"\r\n"
  13243. "\r\n"
  13244. "value2\r\n"
  13245. "--simple boundary--\r\n"
  13246. "This is the epilogue. It is also to be ignored.\r\n";
  13247. std::string content_type =
  13248. R"(multipart/form-data; boundary="simple boundary")";
  13249. Client cli(HOST, PORT);
  13250. auto res = cli.Post("/post", body, content_type.c_str());
  13251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13253. }
  13254. TEST(MultipartFormDataTest, WithPreamble) {
  13255. Server svr;
  13256. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13257. res.set_content("ok", "text/plain");
  13258. });
  13259. thread t = thread([&] { svr.listen(HOST, PORT); });
  13260. auto se = detail::scope_exit([&] {
  13261. svr.stop();
  13262. t.join();
  13263. ASSERT_FALSE(svr.is_running());
  13264. });
  13265. svr.wait_until_ready();
  13266. const std::string body =
  13267. "This is the preamble. It is to be ignored, though it\r\n"
  13268. "is a handy place for composition agents to include an\r\n"
  13269. "explanatory note to non-MIME conformant readers.\r\n"
  13270. "\r\n"
  13271. "\r\n"
  13272. "--simple boundary\r\n"
  13273. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13274. "\r\n"
  13275. "value1\r\n"
  13276. "--simple boundary\r\n"
  13277. "Content-Disposition: form-data; name=\"field2\"; "
  13278. "filename=\"example.txt\"\r\n"
  13279. "\r\n"
  13280. "value2\r\n"
  13281. "--simple boundary--\r\n"
  13282. "This is the epilogue. It is also to be ignored.\r\n";
  13283. std::string content_type =
  13284. R"(multipart/form-data; boundary="simple boundary")";
  13285. Client cli(HOST, PORT);
  13286. auto res = cli.Post("/post", body, content_type.c_str());
  13287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13288. EXPECT_EQ(StatusCode::OK_200, res->status);
  13289. }
  13290. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13292. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13293. const ContentReader &content_reader) {
  13294. if (req.is_multipart_form_data()) {
  13295. std::vector<FormData> items;
  13296. content_reader(
  13297. [&](const FormData &file) {
  13298. items.push_back(file);
  13299. return true;
  13300. },
  13301. [&](const char *data, size_t data_length) {
  13302. items.back().content.append(data, data_length);
  13303. return true;
  13304. });
  13305. EXPECT_TRUE(std::string(items[0].name) == "document");
  13306. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13307. EXPECT_TRUE(items[0].filename == "2MB_data");
  13308. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13309. EXPECT_TRUE(items[1].name == "hello");
  13310. EXPECT_TRUE(items[1].content == "world");
  13311. EXPECT_TRUE(items[1].filename == "");
  13312. EXPECT_TRUE(items[1].content_type == "");
  13313. } else {
  13314. std::string body;
  13315. content_reader([&](const char *data, size_t data_length) {
  13316. body.append(data, data_length);
  13317. return true;
  13318. });
  13319. }
  13320. });
  13321. auto port = svr.bind_to_any_port("localhost");
  13322. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13323. auto se = detail::scope_exit([&] {
  13324. svr.stop();
  13325. t.join();
  13326. ASSERT_FALSE(svr.is_running());
  13327. });
  13328. svr.wait_until_ready();
  13329. {
  13330. std::string data(1024 * 1024 * 2, '.');
  13331. std::stringstream buffer;
  13332. buffer << data;
  13333. SSLClient cli("localhost", port);
  13334. cli.enable_server_certificate_verification(false);
  13335. UploadFormDataItems items{
  13336. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13337. {"hello", "world", "", ""},
  13338. };
  13339. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13341. ASSERT_EQ(StatusCode::OK_200, res->status);
  13342. }
  13343. }
  13344. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13345. std::string data(1024 * 1024 * 2, '&');
  13346. std::stringstream buffer;
  13347. buffer << data;
  13348. Client cli("https://localhost:8080");
  13349. UploadFormDataItems items{
  13350. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13351. {"hello", "world", "", ""},
  13352. };
  13353. for (const char &c : " \t\r\n") {
  13354. auto res =
  13355. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13356. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13357. ASSERT_FALSE(res);
  13358. }
  13359. }
  13360. TEST(MultipartFormDataTest, PutFormData) {
  13361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13362. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13363. const ContentReader &content_reader) {
  13364. if (req.is_multipart_form_data()) {
  13365. std::vector<FormData> items;
  13366. content_reader(
  13367. [&](const FormData &file) {
  13368. items.push_back(file);
  13369. return true;
  13370. },
  13371. [&](const char *data, size_t data_length) {
  13372. items.back().content.append(data, data_length);
  13373. return true;
  13374. });
  13375. EXPECT_TRUE(std::string(items[0].name) == "document");
  13376. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13377. EXPECT_TRUE(items[0].filename == "2MB_data");
  13378. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13379. EXPECT_TRUE(items[1].name == "hello");
  13380. EXPECT_TRUE(items[1].content == "world");
  13381. EXPECT_TRUE(items[1].filename == "");
  13382. EXPECT_TRUE(items[1].content_type == "");
  13383. } else {
  13384. std::string body;
  13385. content_reader([&](const char *data, size_t data_length) {
  13386. body.append(data, data_length);
  13387. return true;
  13388. });
  13389. }
  13390. });
  13391. auto port = svr.bind_to_any_port("localhost");
  13392. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13393. auto se = detail::scope_exit([&] {
  13394. svr.stop();
  13395. t.join();
  13396. ASSERT_FALSE(svr.is_running());
  13397. });
  13398. svr.wait_until_ready();
  13399. {
  13400. std::string data(1024 * 1024 * 2, '&');
  13401. std::stringstream buffer;
  13402. buffer << data;
  13403. SSLClient cli("localhost", port);
  13404. cli.enable_server_certificate_verification(false);
  13405. UploadFormDataItems items{
  13406. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13407. {"hello", "world", "", ""},
  13408. };
  13409. auto res = cli.Put("/put", items);
  13410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13411. ASSERT_EQ(StatusCode::OK_200, res->status);
  13412. }
  13413. }
  13414. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13416. svr.Put("/put_customboundary",
  13417. [&](const Request &req, const Response & /*res*/,
  13418. const ContentReader &content_reader) {
  13419. if (req.is_multipart_form_data()) {
  13420. std::vector<FormData> items;
  13421. content_reader(
  13422. [&](const FormData &file) {
  13423. items.push_back(file);
  13424. return true;
  13425. },
  13426. [&](const char *data, size_t data_length) {
  13427. items.back().content.append(data, data_length);
  13428. return true;
  13429. });
  13430. EXPECT_TRUE(std::string(items[0].name) == "document");
  13431. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13432. EXPECT_TRUE(items[0].filename == "2MB_data");
  13433. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13434. EXPECT_TRUE(items[1].name == "hello");
  13435. EXPECT_TRUE(items[1].content == "world");
  13436. EXPECT_TRUE(items[1].filename == "");
  13437. EXPECT_TRUE(items[1].content_type == "");
  13438. } else {
  13439. std::string body;
  13440. content_reader([&](const char *data, size_t data_length) {
  13441. body.append(data, data_length);
  13442. return true;
  13443. });
  13444. }
  13445. });
  13446. auto port = svr.bind_to_any_port("localhost");
  13447. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13448. auto se = detail::scope_exit([&] {
  13449. svr.stop();
  13450. t.join();
  13451. ASSERT_FALSE(svr.is_running());
  13452. });
  13453. svr.wait_until_ready();
  13454. {
  13455. std::string data(1024 * 1024 * 2, '&');
  13456. std::stringstream buffer;
  13457. buffer << data;
  13458. SSLClient cli("localhost", port);
  13459. cli.enable_server_certificate_verification(false);
  13460. UploadFormDataItems items{
  13461. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13462. {"hello", "world", "", ""},
  13463. };
  13464. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13466. ASSERT_EQ(StatusCode::OK_200, res->status);
  13467. }
  13468. }
  13469. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13470. std::string data(1024 * 1024 * 2, '&');
  13471. std::stringstream buffer;
  13472. buffer << data;
  13473. Client cli("https://localhost:8080");
  13474. cli.enable_server_certificate_verification(false);
  13475. UploadFormDataItems items{
  13476. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13477. {"hello", "world", "", ""},
  13478. };
  13479. for (const char &c : " \t\r\n") {
  13480. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13481. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13482. ASSERT_FALSE(res);
  13483. }
  13484. }
  13485. TEST(MultipartFormDataTest, AlternateFilename) {
  13486. auto handled = false;
  13487. Server svr;
  13488. svr.Post("/test", [&](const Request &req, Response &res) {
  13489. ASSERT_EQ(2u, req.form.files.size());
  13490. ASSERT_EQ(1u, req.form.fields.size());
  13491. // Test files
  13492. const auto &file1 = req.form.get_file("file1");
  13493. ASSERT_EQ("file1", file1.name);
  13494. ASSERT_EQ("A.txt", file1.filename);
  13495. ASSERT_EQ("text/plain", file1.content_type);
  13496. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13497. const auto &file2 = req.form.get_file("file2");
  13498. ASSERT_EQ("file2", file2.name);
  13499. ASSERT_EQ("a.html", file2.filename);
  13500. ASSERT_EQ("text/html", file2.content_type);
  13501. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13502. file2.content);
  13503. // Test text field
  13504. const auto &text = req.form.get_field("text");
  13505. ASSERT_EQ("text default", text);
  13506. res.set_content("ok", "text/plain");
  13507. handled = true;
  13508. });
  13509. thread t = thread([&] { svr.listen(HOST, PORT); });
  13510. auto se = detail::scope_exit([&] {
  13511. svr.stop();
  13512. t.join();
  13513. ASSERT_FALSE(svr.is_running());
  13514. ASSERT_TRUE(handled);
  13515. });
  13516. svr.wait_until_ready();
  13517. auto req = "POST /test HTTP/1.1\r\n"
  13518. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13519. "Content-Length: 399\r\n"
  13520. "\r\n"
  13521. "----------\r\n"
  13522. "Content-Disposition: form-data; name=\"text\"\r\n"
  13523. "\r\n"
  13524. "text default\r\n"
  13525. "----------\r\n"
  13526. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13527. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13528. "Content-Type: text/plain\r\n"
  13529. "\r\n"
  13530. "Content of a.txt.\r\n"
  13531. "\r\n"
  13532. "----------\r\n"
  13533. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13534. "\"a.html\"\r\n"
  13535. "Content-Type: text/html\r\n"
  13536. "\r\n"
  13537. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13538. "\r\n"
  13539. "------------\r\n";
  13540. ASSERT_TRUE(send_request(1, req));
  13541. }
  13542. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13543. auto handled = false;
  13544. Server svr;
  13545. svr.Post("/test", [&](const Request &req, Response &res) {
  13546. // Case-insensitive "utf-8''" prefix with a long value
  13547. const auto &file = req.form.get_file("file1");
  13548. ASSERT_EQ("file1", file.name);
  13549. // 8000 chars exercises both the Content-Disposition parser and the
  13550. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13551. // Prior to the fix, std::regex_match on this header would cause O(N)
  13552. // stack recursion in libstdc++, leading to SIGSEGV.
  13553. std::string expected_filename(8000, 'A');
  13554. ASSERT_EQ(expected_filename, file.filename);
  13555. res.set_content("ok", "text/plain");
  13556. handled = true;
  13557. });
  13558. thread t = thread([&] { svr.listen(HOST, PORT); });
  13559. auto se = detail::scope_exit([&] {
  13560. svr.stop();
  13561. t.join();
  13562. ASSERT_FALSE(svr.is_running());
  13563. ASSERT_TRUE(handled);
  13564. });
  13565. svr.wait_until_ready();
  13566. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13567. // Regression test for GHSA-qq6v-r583-3h69
  13568. std::string long_filename(8000, 'A');
  13569. std::string body = "----------\r\n"
  13570. "Content-Disposition: form-data; name=\"file1\"; "
  13571. "filename*=\"Utf-8''" +
  13572. long_filename +
  13573. "\"\r\n"
  13574. "\r\n"
  13575. "hello\r\n"
  13576. "------------\r\n";
  13577. auto req = "POST /test HTTP/1.1\r\n"
  13578. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13579. "Content-Length: " +
  13580. std::to_string(body.size()) + "\r\n\r\n" + body;
  13581. ASSERT_TRUE(send_request(1, req));
  13582. }
  13583. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13584. auto handled = false;
  13585. Server svr;
  13586. svr.Post("/test", [&](const Request &req, Response &) {
  13587. ASSERT_EQ(2u, req.form.fields.size());
  13588. const auto &text1 = req.form.get_field("text1");
  13589. ASSERT_EQ("text1", text1);
  13590. const auto &text2 = req.form.get_field("text2");
  13591. ASSERT_EQ("text2", text2);
  13592. handled = true;
  13593. });
  13594. thread t = thread([&] { svr.listen(HOST, PORT); });
  13595. auto se = detail::scope_exit([&] {
  13596. svr.stop();
  13597. t.join();
  13598. ASSERT_FALSE(svr.is_running());
  13599. ASSERT_TRUE(handled);
  13600. });
  13601. svr.wait_until_ready();
  13602. auto req = "POST /test HTTP/1.1\r\n"
  13603. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13604. "Content-Length: 146\r\n"
  13605. "\r\n----------\r\n"
  13606. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13607. "\r\n"
  13608. "text1"
  13609. "\r\n----------\r\n"
  13610. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13611. "\r\n"
  13612. "text2"
  13613. "\r\n------------";
  13614. std::string response;
  13615. ASSERT_TRUE(send_request(1, req, &response));
  13616. ASSERT_EQ("200", response.substr(9, 3));
  13617. }
  13618. TEST(MultipartFormDataTest, ContentLength) {
  13619. auto handled = false;
  13620. Server svr;
  13621. svr.Post("/test", [&](const Request &req, Response &) {
  13622. ASSERT_EQ(2u, req.form.fields.size());
  13623. const auto &text1 = req.form.get_field("text1");
  13624. ASSERT_EQ("text1", text1);
  13625. const auto &text2 = req.form.get_field("text2");
  13626. ASSERT_EQ("text2", text2);
  13627. handled = true;
  13628. });
  13629. thread t = thread([&] { svr.listen(HOST, PORT); });
  13630. auto se = detail::scope_exit([&] {
  13631. svr.stop();
  13632. t.join();
  13633. ASSERT_FALSE(svr.is_running());
  13634. ASSERT_TRUE(handled);
  13635. });
  13636. svr.wait_until_ready();
  13637. auto req = "POST /test HTTP/1.1\r\n"
  13638. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13639. "Content-Length: 167\r\n"
  13640. "\r\n----------\r\n"
  13641. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13642. "Content-Length: 5\r\n"
  13643. "\r\n"
  13644. "text1"
  13645. "\r\n----------\r\n"
  13646. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13647. "\r\n"
  13648. "text2"
  13649. "\r\n------------\r\n";
  13650. std::string response;
  13651. ASSERT_TRUE(send_request(1, req, &response));
  13652. ASSERT_EQ("200", response.substr(9, 3));
  13653. }
  13654. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13655. auto handled = false;
  13656. Server svr;
  13657. svr.Post("/test", [&](const Request &req, Response &) {
  13658. ASSERT_EQ(2u, req.form.fields.size());
  13659. const auto &text1 = req.form.get_field("text1");
  13660. ASSERT_EQ("text1", text1);
  13661. // TODO: Add header access for text fields if needed
  13662. const auto &text2 = req.form.get_field("text2");
  13663. ASSERT_EQ("text2", text2);
  13664. // TODO: Header access for text fields needs to be implemented
  13665. // auto &headers = it->second.headers;
  13666. // ASSERT_EQ(3U, headers.size());
  13667. // auto custom_header = headers.find("x-whatever");
  13668. // ASSERT_TRUE(custom_header != headers.end());
  13669. // ASSERT_NE("customvalue", custom_header->second);
  13670. // ASSERT_EQ("CustomValue", custom_header->second);
  13671. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13672. handled = true;
  13673. });
  13674. thread t = thread([&] { svr.listen(HOST, PORT); });
  13675. auto se = detail::scope_exit([&] {
  13676. svr.stop();
  13677. t.join();
  13678. ASSERT_FALSE(svr.is_running());
  13679. ASSERT_TRUE(handled);
  13680. });
  13681. svr.wait_until_ready();
  13682. auto req = "POST /test HTTP/1.1\r\n"
  13683. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13684. "Content-Length: 232\r\n"
  13685. "\r\n----------\r\n"
  13686. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13687. "Content-Length: 5\r\n"
  13688. "X-Test: 1\r\n"
  13689. "\r\n"
  13690. "text1"
  13691. "\r\n----------\r\n"
  13692. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13693. "Content-Type: text/plain\r\n"
  13694. "X-Whatever: CustomValue\r\n"
  13695. "\r\n"
  13696. "text2"
  13697. "\r\n------------\r\n"
  13698. "That should be disregarded. Not even read";
  13699. std::string response;
  13700. ASSERT_TRUE(send_request(1, req, &response));
  13701. ASSERT_EQ("200", response.substr(9, 3));
  13702. }
  13703. TEST(MultipartFormDataTest, LargeHeader) {
  13704. auto handled = false;
  13705. Server svr;
  13706. svr.Post("/test", [&](const Request &req, Response &) {
  13707. ASSERT_EQ(1u, req.form.fields.size());
  13708. const auto &text = req.form.get_field("name1");
  13709. ASSERT_EQ("text1", text);
  13710. handled = true;
  13711. });
  13712. thread t = thread([&] { svr.listen(HOST, PORT); });
  13713. auto se = detail::scope_exit([&] {
  13714. svr.stop();
  13715. t.join();
  13716. ASSERT_FALSE(svr.is_running());
  13717. ASSERT_TRUE(handled);
  13718. });
  13719. svr.wait_until_ready();
  13720. auto boundary = std::string("cpp-httplib-multipart-data");
  13721. std::string content = "--" + boundary +
  13722. "\r\n"
  13723. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13724. "\r\n"
  13725. "text1\r\n"
  13726. "--" +
  13727. boundary + "--\r\n";
  13728. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13729. "Content-Type: multipart/form-data;boundary=" +
  13730. boundary +
  13731. "\r\n"
  13732. "Content-Length: " +
  13733. std::to_string(content.size()) +
  13734. "\r\n"
  13735. "Dummy-Header: ";
  13736. std::string header_suffix = "\r\n"
  13737. "\r\n";
  13738. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13739. size_t header_dummy_size =
  13740. read_buff_size -
  13741. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13742. auto header_dummy = std::string(header_dummy_size, '@');
  13743. auto req = header_prefix + header_dummy + header_suffix + content;
  13744. std::string response;
  13745. ASSERT_TRUE(send_request(1, req, &response));
  13746. ASSERT_EQ("200", response.substr(9, 3));
  13747. }
  13748. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13749. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13750. // (not chunked Transfer-Encoding) after the streaming refactor.
  13751. auto handled = false;
  13752. Server svr;
  13753. svr.Post("/upload", [&](const Request &req, Response &res) {
  13754. auto cl_it = req.headers.find("Content-Length");
  13755. EXPECT_TRUE(cl_it != req.headers.end());
  13756. auto te_it = req.headers.find("Transfer-Encoding");
  13757. EXPECT_TRUE(te_it == req.headers.end());
  13758. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13759. res.set_content("ok", "text/plain");
  13760. handled = true;
  13761. });
  13762. auto port = svr.bind_to_any_port(HOST);
  13763. auto t = thread([&] { svr.listen_after_bind(); });
  13764. auto se = detail::scope_exit([&] {
  13765. svr.stop();
  13766. t.join();
  13767. ASSERT_FALSE(svr.is_running());
  13768. ASSERT_TRUE(handled);
  13769. });
  13770. svr.wait_until_ready();
  13771. UploadFormDataItems items = {
  13772. {"field1", "hello", "", "text/plain"},
  13773. {"file1", "world", "test.txt", "application/octet-stream"},
  13774. };
  13775. Client cli(HOST, port);
  13776. auto res = cli.Post("/upload", {}, items);
  13777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13778. EXPECT_EQ(StatusCode::OK_200, res->status);
  13779. }
  13780. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13781. // Verify that make_multipart_content_provider coalesces many small segments
  13782. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13783. constexpr size_t kItemCount = 1000;
  13784. UploadFormDataItems items;
  13785. items.reserve(kItemCount);
  13786. for (size_t i = 0; i < kItemCount; i++) {
  13787. items.push_back(
  13788. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13789. }
  13790. const std::string boundary = "----test-boundary";
  13791. auto content_length = detail::get_multipart_content_length(items, boundary);
  13792. auto provider = detail::make_multipart_content_provider(items, boundary);
  13793. // Drive the provider the same way write_content_with_progress does
  13794. size_t write_count = 0;
  13795. size_t total_bytes = 0;
  13796. DataSink sink;
  13797. size_t offset = 0;
  13798. sink.write = [&](const char *d, size_t l) -> bool {
  13799. (void)d;
  13800. write_count++;
  13801. total_bytes += l;
  13802. offset += l;
  13803. return true;
  13804. };
  13805. sink.is_writable = []() -> bool { return true; };
  13806. while (offset < content_length) {
  13807. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13808. }
  13809. EXPECT_EQ(content_length, total_bytes);
  13810. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13811. // With buffering into 64KB blocks, write_count should be much smaller.
  13812. auto segment_count = 3 * kItemCount + 1;
  13813. EXPECT_LT(write_count, segment_count / 10);
  13814. }
  13815. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13816. // Integration test: send many UploadFormDataItems and verify the server
  13817. // receives all of them correctly (#2410).
  13818. constexpr size_t kItemCount = 500;
  13819. auto handled = false;
  13820. Server svr;
  13821. svr.Post("/upload", [&](const Request &req, Response &res) {
  13822. EXPECT_EQ(kItemCount, req.form.fields.size());
  13823. for (size_t i = 0; i < kItemCount; i++) {
  13824. auto key = "field" + std::to_string(i);
  13825. auto val = "value" + std::to_string(i);
  13826. auto it = req.form.fields.find(key);
  13827. if (it != req.form.fields.end()) {
  13828. EXPECT_EQ(val, it->second.content);
  13829. } else {
  13830. ADD_FAILURE() << "Missing field: " << key;
  13831. }
  13832. }
  13833. res.set_content("ok", "text/plain");
  13834. handled = true;
  13835. });
  13836. auto port = svr.bind_to_any_port(HOST);
  13837. auto t = thread([&] { svr.listen_after_bind(); });
  13838. auto se = detail::scope_exit([&] {
  13839. svr.stop();
  13840. t.join();
  13841. ASSERT_FALSE(svr.is_running());
  13842. ASSERT_TRUE(handled);
  13843. });
  13844. svr.wait_until_ready();
  13845. UploadFormDataItems items;
  13846. items.reserve(kItemCount);
  13847. for (size_t i = 0; i < kItemCount; i++) {
  13848. items.push_back(
  13849. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13850. }
  13851. Client cli(HOST, port);
  13852. auto res = cli.Post("/upload", items);
  13853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13854. EXPECT_EQ(StatusCode::OK_200, res->status);
  13855. }
  13856. TEST(MultipartFormDataTest, MakeFileProvider) {
  13857. // Verify make_file_provider sends a file's contents correctly.
  13858. const std::string file_content(4096, 'Z');
  13859. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13860. {
  13861. std::ofstream ofs(tmp_path, std::ios::binary);
  13862. ofs.write(file_content.data(),
  13863. static_cast<std::streamsize>(file_content.size()));
  13864. }
  13865. auto handled = false;
  13866. Server svr;
  13867. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13868. const ContentReader &content_reader) {
  13869. ASSERT_TRUE(req.is_multipart_form_data());
  13870. std::vector<FormData> items;
  13871. content_reader(
  13872. [&](const FormData &file) {
  13873. items.push_back(file);
  13874. return true;
  13875. },
  13876. [&](const char *data, size_t data_length) {
  13877. items.back().content.append(data, data_length);
  13878. return true;
  13879. });
  13880. ASSERT_EQ(1u, items.size());
  13881. EXPECT_EQ("myfile", items[0].name);
  13882. EXPECT_EQ("data.bin", items[0].filename);
  13883. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13884. EXPECT_EQ(file_content, items[0].content);
  13885. handled = true;
  13886. });
  13887. auto port = svr.bind_to_any_port(HOST);
  13888. auto t = thread([&] { svr.listen_after_bind(); });
  13889. auto se = detail::scope_exit([&] {
  13890. svr.stop();
  13891. t.join();
  13892. ASSERT_FALSE(svr.is_running());
  13893. ASSERT_TRUE(handled);
  13894. std::remove(tmp_path.c_str());
  13895. });
  13896. svr.wait_until_ready();
  13897. FormDataProviderItems providers;
  13898. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13899. "application/octet-stream"));
  13900. Client cli(HOST, port);
  13901. auto res = cli.Post("/upload", {}, {}, providers);
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_EQ(StatusCode::OK_200, res->status);
  13904. }
  13905. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13906. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13907. // (100) headers is rejected with a 400 Bad Request response.
  13908. Server svr;
  13909. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13910. res.set_content("ok", "text/plain");
  13911. });
  13912. thread t = thread([&] { svr.listen(HOST, PORT); });
  13913. auto se = detail::scope_exit([&] {
  13914. svr.stop();
  13915. t.join();
  13916. ASSERT_FALSE(svr.is_running());
  13917. });
  13918. svr.wait_until_ready();
  13919. // Build a multipart part with 101 custom headers (exceeding
  13920. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13921. std::stringstream body;
  13922. body << "--simpleboundary\r\n"
  13923. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13924. for (int i = 0; i < 101; i++) {
  13925. body << "X-Custom-Header-" << i << ": value\r\n";
  13926. }
  13927. body << "\r\n"
  13928. << "value1\r\n"
  13929. << "--simpleboundary--\r\n";
  13930. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13931. Client cli(HOST, PORT);
  13932. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13934. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13935. }
  13936. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13937. // A body that never contains the declared boundary must not be accumulated
  13938. // while the parser waits for it. Buffering it would also make every read
  13939. // rescan everything seen so far, which is quadratic in the body size.
  13940. Server svr;
  13941. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13942. res.set_content("ok", "text/plain");
  13943. });
  13944. auto port = svr.bind_to_any_port(HOST);
  13945. thread t = thread([&] { svr.listen_after_bind(); });
  13946. auto se = detail::scope_exit([&] {
  13947. svr.stop();
  13948. t.join();
  13949. ASSERT_FALSE(svr.is_running());
  13950. });
  13951. svr.wait_until_ready();
  13952. Client cli(HOST, port);
  13953. cli.set_read_timeout(60, 0);
  13954. cli.set_write_timeout(60, 0);
  13955. // '-' is the worst case: it matches the first character of the boundary, so
  13956. // every position has to be checked against it.
  13957. auto post_dashes = [&](size_t size) {
  13958. const std::string body(size, '-');
  13959. auto start = std::chrono::steady_clock::now();
  13960. auto res =
  13961. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13962. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13963. std::chrono::steady_clock::now() - start)
  13964. .count();
  13965. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13966. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13967. return ms;
  13968. };
  13969. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13970. // Windows.
  13971. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13972. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13973. // Comparing the two sizes rather than checking an absolute duration keeps
  13974. // this meaningful across build types and CI load, both of which move the
  13975. // absolute numbers by more than an order of magnitude. Four times the bytes
  13976. // costs about four times the time when parsing is linear, and about sixteen
  13977. // times when the body is buffered and rescanned.
  13978. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13979. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13980. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13981. << "ms, which suggests the body is being buffered and rescanned";
  13982. }
  13983. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13984. // A boundary can only be followed by CRLF or by "--", so anything else is
  13985. // malformed no matter what comes next. The parser must say so right away
  13986. // instead of buffering the rest of the declared body.
  13987. Server svr;
  13988. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13989. res.set_content("ok", "text/plain");
  13990. });
  13991. auto port = svr.bind_to_any_port(HOST);
  13992. thread t = thread([&] { svr.listen_after_bind(); });
  13993. auto se = detail::scope_exit([&] {
  13994. svr.stop();
  13995. t.join();
  13996. ASSERT_FALSE(svr.is_running());
  13997. });
  13998. svr.wait_until_ready();
  13999. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14000. // buffers instead of failing would still be waiting for the remaining bytes.
  14001. const std::string body = "--zzzz\r\n"
  14002. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14003. "\r\n"
  14004. "text1"
  14005. "\r\n--zzzzXX";
  14006. const std::string req = "POST /post HTTP/1.1\r\n"
  14007. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14008. "Content-Length: 1048576\r\n"
  14009. "\r\n" +
  14010. body;
  14011. std::string response;
  14012. ASSERT_TRUE(send_request(3, req, &response, port));
  14013. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14014. EXPECT_EQ("400", response.substr(9, 3));
  14015. }
  14016. // Posts a multipart body split into two writes, so that the server sees the
  14017. // split at whatever offset the caller chose, and expects the single "text1"
  14018. // field to come through.
  14019. static void expect_split_multipart_ok(const std::string &body1,
  14020. const std::string &body2) {
  14021. auto handled = false;
  14022. Server svr;
  14023. svr.Post("/post", [&](const Request &req, Response &) {
  14024. EXPECT_EQ(1u, req.form.fields.size());
  14025. EXPECT_EQ("text1", req.form.get_field("text1"));
  14026. handled = true;
  14027. });
  14028. auto port = svr.bind_to_any_port(HOST);
  14029. thread t = thread([&] { svr.listen_after_bind(); });
  14030. auto se = detail::scope_exit([&] {
  14031. svr.stop();
  14032. t.join();
  14033. ASSERT_FALSE(svr.is_running());
  14034. ASSERT_TRUE(handled);
  14035. });
  14036. svr.wait_until_ready();
  14037. // "Connection: close" makes the server close once it has answered, so the
  14038. // response drain ends immediately instead of idling until the read timeout.
  14039. const std::string head =
  14040. "POST /post HTTP/1.1\r\n"
  14041. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14042. "Connection: close\r\n"
  14043. "Content-Length: " +
  14044. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14045. std::string response;
  14046. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14047. ASSERT_GE(response.size(), 12u) << "no response";
  14048. EXPECT_EQ("200", response.substr(9, 3));
  14049. }
  14050. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14051. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14052. // ignored, including when it does not arrive in the same read as the
  14053. // close-delimiter itself.
  14054. expect_split_multipart_ok("--zzzz\r\n"
  14055. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14056. "\r\n"
  14057. "text1"
  14058. "\r\n--zzzz--",
  14059. "\r\nthis epilogue must be ignored\r\n");
  14060. }
  14061. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14062. // The initial boundary may be preceded by a preamble of any length and may
  14063. // straddle a read boundary. Discarding data while waiting for it must not
  14064. // throw away a partial boundary sitting at the end of the buffer.
  14065. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14066. "zz\r\n"
  14067. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14068. "\r\n"
  14069. "text1"
  14070. "\r\n--zzzz--\r\n");
  14071. }
  14072. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14073. // The received boundary was only checked for being non-empty, so it could be
  14074. // as long as a header is allowed to be. The parser scans the body for
  14075. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14076. // costs a nearly full comparison at nearly every position, making the
  14077. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14078. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14079. Server svr;
  14080. svr.Post("/post", [](const Request &req, Response &res) {
  14081. EXPECT_EQ(1u, req.form.fields.size());
  14082. EXPECT_EQ("text1", req.form.get_field("text1"));
  14083. res.set_content("ok", "text/plain");
  14084. });
  14085. auto port = svr.bind_to_any_port(HOST);
  14086. thread t = thread([&] { svr.listen_after_bind(); });
  14087. auto se = detail::scope_exit([&] {
  14088. svr.stop();
  14089. t.join();
  14090. ASSERT_FALSE(svr.is_running());
  14091. });
  14092. svr.wait_until_ready();
  14093. Client cli(HOST, port);
  14094. auto post_with_boundary_of_length = [&](size_t len) {
  14095. const std::string boundary(len, 'a');
  14096. const std::string body =
  14097. "--" + boundary +
  14098. "\r\n"
  14099. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14100. "\r\n"
  14101. "text1"
  14102. "\r\n--" +
  14103. boundary + "--\r\n";
  14104. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14105. };
  14106. auto res = post_with_boundary_of_length(70);
  14107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14108. EXPECT_EQ(StatusCode::OK_200, res->status);
  14109. res = post_with_boundary_of_length(71);
  14110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14111. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14112. }
  14113. TEST(MakeFileBodyTest, Basic) {
  14114. const std::string file_content(4096, 'Z');
  14115. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14116. {
  14117. std::ofstream ofs(tmp_path, std::ios::binary);
  14118. ofs.write(file_content.data(),
  14119. static_cast<std::streamsize>(file_content.size()));
  14120. }
  14121. auto handled = false;
  14122. Server svr;
  14123. svr.Post("/upload", [&](const Request &req, Response &res) {
  14124. EXPECT_EQ(file_content, req.body);
  14125. handled = true;
  14126. res.status = StatusCode::OK_200;
  14127. });
  14128. auto port = svr.bind_to_any_port(HOST);
  14129. auto t = thread([&] { svr.listen_after_bind(); });
  14130. auto se = detail::scope_exit([&] {
  14131. svr.stop();
  14132. t.join();
  14133. ASSERT_FALSE(svr.is_running());
  14134. ASSERT_TRUE(handled);
  14135. std::remove(tmp_path.c_str());
  14136. });
  14137. svr.wait_until_ready();
  14138. auto fb = make_file_body(tmp_path);
  14139. ASSERT_GT(fb.first, 0u);
  14140. Client cli(HOST, port);
  14141. auto res =
  14142. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14144. EXPECT_EQ(StatusCode::OK_200, res->status);
  14145. }
  14146. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14147. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14148. {
  14149. std::ofstream ofs(path, std::ios::binary);
  14150. const std::string content(100, 'A');
  14151. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14152. }
  14153. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14154. auto body = make_file_body(path);
  14155. ASSERT_EQ(100u, body.first);
  14156. ASSERT_TRUE(static_cast<bool>(body.second));
  14157. // Rewritten shorter after its length was measured - and, on a server, after
  14158. // that length has already gone out as Content-Length.
  14159. {
  14160. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14161. const std::string content(10, 'A');
  14162. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14163. }
  14164. std::string written;
  14165. DataSink sink;
  14166. sink.write = [&](const char *d, size_t l) {
  14167. written.append(d, l);
  14168. return true;
  14169. };
  14170. // The provider has to report failure. write_content_with_progress() advances
  14171. // its offset only by what was written, so a provider that returns true
  14172. // without completing the length it promised is called again straight away,
  14173. // and again.
  14174. EXPECT_FALSE(body.second(0, body.first, sink));
  14175. EXPECT_EQ(std::string(10, 'A'), written);
  14176. }
  14177. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14178. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14179. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14180. {
  14181. std::ofstream ofs(path, std::ios::binary);
  14182. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14183. }
  14184. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14185. auto body = make_file_body(path);
  14186. ASSERT_EQ(content.size(), body.first);
  14187. ASSERT_TRUE(static_cast<bool>(body.second));
  14188. std::string written;
  14189. DataSink sink;
  14190. sink.write = [&](const char *d, size_t l) {
  14191. written.append(d, l);
  14192. return true;
  14193. };
  14194. EXPECT_TRUE(body.second(0, body.first, sink));
  14195. EXPECT_EQ(content, written);
  14196. }
  14197. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14198. static constexpr unsigned int number_of_tasks{1000000};
  14199. std::atomic_uint count{0};
  14200. std::unique_ptr<TaskQueue> task_queue{
  14201. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14202. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14203. auto queued = task_queue->enqueue(
  14204. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14205. EXPECT_TRUE(queued);
  14206. }
  14207. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14208. task_queue->shutdown();
  14209. #else
  14210. EXPECT_NO_THROW(task_queue->shutdown());
  14211. #endif
  14212. EXPECT_EQ(number_of_tasks, count.load());
  14213. }
  14214. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14215. static constexpr unsigned int number_of_tasks{1000000};
  14216. static constexpr unsigned int qlimit{2};
  14217. unsigned int queued_count{0};
  14218. std::atomic_uint count{0};
  14219. std::unique_ptr<TaskQueue> task_queue{
  14220. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14221. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14222. if (task_queue->enqueue(
  14223. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14224. queued_count++;
  14225. }
  14226. }
  14227. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14228. task_queue->shutdown();
  14229. #else
  14230. EXPECT_NO_THROW(task_queue->shutdown());
  14231. #endif
  14232. EXPECT_EQ(queued_count, count.load());
  14233. EXPECT_TRUE(queued_count <= number_of_tasks);
  14234. EXPECT_TRUE(queued_count >= qlimit);
  14235. }
  14236. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14237. // Use a short idle timeout so a dynamic thread spawns, times out and
  14238. // exits during the test, and the pool keeps working afterwards.
  14239. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14240. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14241. /*idle_timeout_sec=*/1}};
  14242. std::atomic_uint count{0};
  14243. std::condition_variable cv;
  14244. std::mutex mtx;
  14245. bool release = false;
  14246. // Block the base thread so the second task spawns a dynamic thread.
  14247. EXPECT_TRUE(task_queue->enqueue([&] {
  14248. std::unique_lock<std::mutex> lock(mtx);
  14249. while (!release) {
  14250. cv.wait(lock);
  14251. }
  14252. count++;
  14253. }));
  14254. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14255. // Let the dynamic thread finish its task and exceed the idle timeout.
  14256. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14257. {
  14258. std::unique_lock<std::mutex> lock(mtx);
  14259. release = true;
  14260. }
  14261. cv.notify_all();
  14262. // The pool must still accept and run tasks after the dynamic thread exited.
  14263. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14264. task_queue->shutdown();
  14265. EXPECT_EQ(3u, count.load());
  14266. }
  14267. TEST(TaskQueueTest, MaxQueuedRequests) {
  14268. static constexpr unsigned int qlimit{3};
  14269. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14270. std::condition_variable sem_cv;
  14271. std::mutex sem_mtx;
  14272. int credits = 0;
  14273. bool queued;
  14274. /* Fill up the queue with tasks that will block until we give them credits to
  14275. * complete. */
  14276. for (unsigned int n = 0; n <= qlimit;) {
  14277. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14278. std::unique_lock<std::mutex> lock(sem_mtx);
  14279. while (credits <= 0) {
  14280. sem_cv.wait(lock);
  14281. }
  14282. /* Consume the credit and signal the test code if they are all gone. */
  14283. if (--credits == 0) { sem_cv.notify_one(); }
  14284. });
  14285. if (n < qlimit) {
  14286. /* The first qlimit enqueues must succeed. */
  14287. EXPECT_TRUE(queued);
  14288. } else {
  14289. /* The last one will succeed only when the worker thread
  14290. * starts and dequeues the first blocking task. Although
  14291. * not necessary for the correctness of this test, we sleep for
  14292. * a short while to avoid busy waiting. */
  14293. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14294. }
  14295. if (queued) { n++; }
  14296. }
  14297. /* Further enqueues must fail since the queue is full. */
  14298. for (auto i = 0; i < 4; i++) {
  14299. queued = task_queue->enqueue([] {});
  14300. EXPECT_FALSE(queued);
  14301. }
  14302. /* Give the credits to allow the previous tasks to complete. */
  14303. {
  14304. std::unique_lock<std::mutex> lock(sem_mtx);
  14305. credits += qlimit + 1;
  14306. }
  14307. sem_cv.notify_all();
  14308. /* Wait for all the credits to be consumed. */
  14309. {
  14310. std::unique_lock<std::mutex> lock(sem_mtx);
  14311. while (credits > 0) {
  14312. sem_cv.wait(lock);
  14313. }
  14314. }
  14315. /* Check that we are able again to enqueue at least qlimit tasks. */
  14316. for (unsigned int i = 0; i < qlimit; i++) {
  14317. queued = task_queue->enqueue([] {});
  14318. EXPECT_TRUE(queued);
  14319. }
  14320. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14321. task_queue->shutdown();
  14322. #else
  14323. EXPECT_NO_THROW(task_queue->shutdown());
  14324. #endif
  14325. }
  14326. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14327. Server svr;
  14328. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14329. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14330. });
  14331. svr.Get("/hello", [](const Request &req, Response &res) {
  14332. res.set_content(req.get_param_value("key"), "text/plain");
  14333. });
  14334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14335. auto se = detail::scope_exit([&] {
  14336. svr.stop();
  14337. thread.join();
  14338. ASSERT_FALSE(svr.is_running());
  14339. });
  14340. svr.wait_until_ready();
  14341. {
  14342. Client cli(HOST, PORT);
  14343. cli.set_follow_location(true);
  14344. auto res = cli.Get("/");
  14345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14346. EXPECT_EQ(StatusCode::OK_200, res->status);
  14347. EXPECT_EQ("val&key2=val2", res->body);
  14348. }
  14349. }
  14350. #endif
  14351. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14352. Server svr;
  14353. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14354. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14355. });
  14356. svr.Get("/hello", [](const Request &req, Response &res) {
  14357. res.set_content(req.get_param_value("key"), "text/plain");
  14358. });
  14359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14360. auto se = detail::scope_exit([&] {
  14361. svr.stop();
  14362. thread.join();
  14363. ASSERT_FALSE(svr.is_running());
  14364. });
  14365. svr.wait_until_ready();
  14366. {
  14367. Client cli(HOST, PORT);
  14368. cli.set_follow_location(true);
  14369. auto res = cli.Get("/");
  14370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14371. EXPECT_EQ(StatusCode::OK_200, res->status);
  14372. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14373. }
  14374. }
  14375. TEST(RedirectTest, RedirectWithPlusInPath) {
  14376. Server svr;
  14377. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14378. res.set_redirect("/a+b");
  14379. });
  14380. // Route pattern uses regex; escape + as \\+
  14381. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14382. res.set_content(req.path, "text/plain");
  14383. });
  14384. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14385. auto se = detail::scope_exit([&] {
  14386. svr.stop();
  14387. thread.join();
  14388. ASSERT_FALSE(svr.is_running());
  14389. });
  14390. svr.wait_until_ready();
  14391. {
  14392. Client cli(HOST, PORT);
  14393. cli.set_follow_location(true);
  14394. auto res = cli.Get("/");
  14395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14396. EXPECT_EQ(StatusCode::OK_200, res->status);
  14397. EXPECT_EQ("/a+b", res->body);
  14398. }
  14399. }
  14400. #ifdef CPPHTTPLIB_SSL_ENABLED
  14401. TEST(RedirectTest, Issue2185_Online) {
  14402. SSLClient client("github.com");
  14403. client.set_follow_location(true);
  14404. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14405. "Coollab-Windows.zip");
  14406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14407. EXPECT_EQ(StatusCode::OK_200, res->status);
  14408. EXPECT_EQ(9920427U, res->body.size());
  14409. }
  14410. #endif
  14411. TEST(VulnerabilityTest, CRLFInjection) {
  14412. Server svr;
  14413. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14414. res.set_content("Hello 1", "text/plain");
  14415. });
  14416. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14417. res.set_content("Hello 2", "text/plain");
  14418. });
  14419. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14420. res.set_content("Hello 3", "text/plain");
  14421. });
  14422. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14423. res.set_content("Hello 4", "text/plain");
  14424. });
  14425. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14426. for (const auto &x : req.headers) {
  14427. auto key = x.first;
  14428. EXPECT_STRNE("evil", key.c_str());
  14429. }
  14430. });
  14431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14432. auto se = detail::scope_exit([&] {
  14433. svr.stop();
  14434. thread.join();
  14435. ASSERT_FALSE(svr.is_running());
  14436. });
  14437. svr.wait_until_ready();
  14438. {
  14439. Client cli(HOST, PORT);
  14440. cli.Post("/test1", "A=B",
  14441. "application/x-www-form-urlencoded\r\nevil: hello1");
  14442. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14443. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14444. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14445. }
  14446. }
  14447. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14448. auto server_thread = std::thread([] {
  14449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14450. default_socket_options(srv);
  14451. sockaddr_in addr{};
  14452. addr.sin_family = AF_INET;
  14453. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14454. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14455. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14456. ::listen(srv, 1);
  14457. sockaddr_in cli_addr{};
  14458. socklen_t cli_len = sizeof(cli_addr);
  14459. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14460. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14461. std::string buf_all;
  14462. char buf[2048];
  14463. ssize_t n;
  14464. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14465. buf_all.append(buf, static_cast<size_t>(n));
  14466. size_t pos;
  14467. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14468. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14469. auto e = request_block.find("\r\n");
  14470. if (e != std::string::npos) {
  14471. auto request_line = request_block.substr(0, e);
  14472. std::string msg =
  14473. "CRLF injection detected in request line: '" + request_line + "'";
  14474. EXPECT_FALSE(true) << msg;
  14475. }
  14476. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14477. ::send(cli,
  14478. #ifdef _WIN32
  14479. static_cast<const char *>(resp.c_str()),
  14480. static_cast<int>(resp.size()),
  14481. #else
  14482. resp.c_str(), resp.size(),
  14483. #endif
  14484. 0);
  14485. buf_all.erase(0, pos + 4);
  14486. }
  14487. }
  14488. detail::close_socket(cli);
  14489. detail::close_socket(srv);
  14490. });
  14491. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14492. auto cli = Client("127.0.0.1", PORT + 1);
  14493. auto headers = Headers{
  14494. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14495. {"Connection", "keep-alive"}};
  14496. auto res = cli.Get("/hi", headers);
  14497. EXPECT_FALSE(res);
  14498. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14499. server_thread.join();
  14500. }
  14501. TEST(PathParamsTest, StaticMatch) {
  14502. const auto pattern = "/users/all";
  14503. detail::PathParamsMatcher matcher(pattern);
  14504. Request request;
  14505. request.path = "/users/all";
  14506. ASSERT_TRUE(matcher.match(request));
  14507. std::unordered_map<std::string, std::string> expected_params = {};
  14508. EXPECT_EQ(request.path_params, expected_params);
  14509. }
  14510. TEST(PathParamsTest, StaticMismatch) {
  14511. const auto pattern = "/users/all";
  14512. detail::PathParamsMatcher matcher(pattern);
  14513. Request request;
  14514. request.path = "/users/1";
  14515. ASSERT_FALSE(matcher.match(request));
  14516. }
  14517. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14518. const auto pattern = "/users/:id/subscriptions";
  14519. detail::PathParamsMatcher matcher(pattern);
  14520. Request request;
  14521. request.path = "/users/42/subscriptions";
  14522. ASSERT_TRUE(matcher.match(request));
  14523. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14524. EXPECT_EQ(request.path_params, expected_params);
  14525. }
  14526. TEST(PathParamsTest, SingleParamInTheEnd) {
  14527. const auto pattern = "/users/:id";
  14528. detail::PathParamsMatcher matcher(pattern);
  14529. Request request;
  14530. request.path = "/users/24";
  14531. ASSERT_TRUE(matcher.match(request));
  14532. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14533. EXPECT_EQ(request.path_params, expected_params);
  14534. }
  14535. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14536. const auto pattern = "/users/:id/";
  14537. detail::PathParamsMatcher matcher(pattern);
  14538. Request request;
  14539. request.path = "/users/42/";
  14540. ASSERT_TRUE(matcher.match(request));
  14541. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14542. EXPECT_EQ(request.path_params, expected_params);
  14543. }
  14544. TEST(PathParamsTest, EmptyParam) {
  14545. const auto pattern = "/users/:id/";
  14546. detail::PathParamsMatcher matcher(pattern);
  14547. Request request;
  14548. request.path = "/users//";
  14549. ASSERT_TRUE(matcher.match(request));
  14550. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14551. EXPECT_EQ(request.path_params, expected_params);
  14552. }
  14553. TEST(PathParamsTest, FragmentMismatch) {
  14554. const auto pattern = "/users/:id/";
  14555. detail::PathParamsMatcher matcher(pattern);
  14556. Request request;
  14557. request.path = "/admins/24/";
  14558. ASSERT_FALSE(matcher.match(request));
  14559. }
  14560. TEST(PathParamsTest, ExtraFragments) {
  14561. const auto pattern = "/users/:id";
  14562. detail::PathParamsMatcher matcher(pattern);
  14563. Request request;
  14564. request.path = "/users/42/subscriptions";
  14565. ASSERT_FALSE(matcher.match(request));
  14566. }
  14567. TEST(PathParamsTest, MissingTrailingParam) {
  14568. const auto pattern = "/users/:id";
  14569. detail::PathParamsMatcher matcher(pattern);
  14570. Request request;
  14571. request.path = "/users";
  14572. ASSERT_FALSE(matcher.match(request));
  14573. }
  14574. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14575. const auto pattern = "/users/:id/subscriptions";
  14576. detail::PathParamsMatcher matcher(pattern);
  14577. Request request;
  14578. request.path = "/users/subscriptions";
  14579. ASSERT_FALSE(matcher.match(request));
  14580. }
  14581. TEST(PathParamsTest, MultipleParams) {
  14582. const auto pattern = "/users/:userid/subscriptions/:subid";
  14583. detail::PathParamsMatcher matcher(pattern);
  14584. Request request;
  14585. request.path = "/users/42/subscriptions/2";
  14586. ASSERT_TRUE(matcher.match(request));
  14587. std::unordered_map<std::string, std::string> expected_params = {
  14588. {"userid", "42"}, {"subid", "2"}};
  14589. EXPECT_EQ(request.path_params, expected_params);
  14590. }
  14591. TEST(PathParamsTest, SequenceOfParams) {
  14592. const auto pattern = "/values/:x/:y/:z";
  14593. detail::PathParamsMatcher matcher(pattern);
  14594. Request request;
  14595. request.path = "/values/1/2/3";
  14596. ASSERT_TRUE(matcher.match(request));
  14597. std::unordered_map<std::string, std::string> expected_params = {
  14598. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14599. EXPECT_EQ(request.path_params, expected_params);
  14600. }
  14601. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14602. const auto pattern = "/prefix:suffix";
  14603. detail::PathParamsMatcher matcher(pattern);
  14604. Request request;
  14605. request.path = "/prefix:suffix";
  14606. ASSERT_TRUE(matcher.match(request));
  14607. const std::unordered_map<std::string, std::string> expected_params = {};
  14608. EXPECT_EQ(request.path_params, expected_params);
  14609. }
  14610. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14611. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14612. // calling thread's stack on a long enough path for a quantified pattern;
  14613. // RegexMatcher must refuse to run regex matching on paths beyond
  14614. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14615. detail::RegexMatcher matcher("/files/(.*)");
  14616. Request within_limit;
  14617. within_limit.path = "/files/" + std::string(10, 'A');
  14618. EXPECT_TRUE(matcher.match(within_limit));
  14619. Request over_limit;
  14620. over_limit.path =
  14621. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14622. EXPECT_FALSE(matcher.match(over_limit));
  14623. }
  14624. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14625. Server svr;
  14626. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14627. res.set_content("ok", "text/plain");
  14628. });
  14629. auto port = svr.bind_to_any_port(HOST);
  14630. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14631. auto se = detail::scope_exit([&] {
  14632. svr.stop();
  14633. thread.join();
  14634. ASSERT_FALSE(svr.is_running());
  14635. });
  14636. svr.wait_until_ready();
  14637. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14638. // request URI limit; this used to be able to crash the process.
  14639. std::string path =
  14640. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14641. std::string req = "GET " + path +
  14642. " HTTP/1.1\r\n"
  14643. "Host: " +
  14644. std::string(HOST) + ":" + std::to_string(port) +
  14645. "\r\n"
  14646. "Connection: close\r\n"
  14647. "\r\n";
  14648. std::string response;
  14649. ASSERT_TRUE(send_request(5, req, &response, port));
  14650. EXPECT_NE(std::string::npos, response.find("404"));
  14651. }
  14652. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14653. Server svr;
  14654. auto handler = [](const Request & /*req*/, Response &res) {
  14655. res.set_content("hit", "text/plain");
  14656. };
  14657. // No regex metacharacter, so this one is compared literally
  14658. svr.Get("/literal/route", handler);
  14659. // '.' is a regex metacharacter, so this one must keep regex semantics
  14660. svr.Get("/a.c", handler);
  14661. auto port = svr.bind_to_any_port(HOST);
  14662. std::thread t([&]() { svr.listen_after_bind(); });
  14663. auto se = detail::scope_exit([&] {
  14664. svr.stop();
  14665. t.join();
  14666. ASSERT_FALSE(svr.is_running());
  14667. });
  14668. svr.wait_until_ready();
  14669. Client cli(HOST, port);
  14670. struct {
  14671. const char *path;
  14672. int status;
  14673. } cases[] = {
  14674. {"/literal/route", StatusCode::OK_200},
  14675. {"/literal/routes", StatusCode::NotFound_404},
  14676. {"/literal/rout", StatusCode::NotFound_404},
  14677. {"/abc", StatusCode::OK_200},
  14678. {"/a.c", StatusCode::OK_200},
  14679. };
  14680. for (const auto &x : cases) {
  14681. auto res = cli.Get(x.path);
  14682. ASSERT_TRUE(res) << x.path;
  14683. EXPECT_EQ(x.status, res->status) << x.path;
  14684. }
  14685. }
  14686. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14687. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14688. // from exhausting the stack, so it must only constrain routes that actually
  14689. // run a regular expression. A literal route is matched by comparison and
  14690. // stays usable at any length.
  14691. Server svr;
  14692. const std::string pattern =
  14693. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14694. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14695. res.set_content("hit", "text/plain");
  14696. });
  14697. auto port = svr.bind_to_any_port(HOST);
  14698. std::thread t([&]() { svr.listen_after_bind(); });
  14699. auto se = detail::scope_exit([&] {
  14700. svr.stop();
  14701. t.join();
  14702. ASSERT_FALSE(svr.is_running());
  14703. });
  14704. svr.wait_until_ready();
  14705. Client cli(HOST, port);
  14706. auto res = cli.Get(pattern);
  14707. ASSERT_TRUE(res);
  14708. EXPECT_EQ(StatusCode::OK_200, res->status);
  14709. }
  14710. TEST(ParseUrlTest, VariousPatterns) {
  14711. {
  14712. detail::UrlComponents uc;
  14713. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14714. EXPECT_EQ("http", uc.scheme);
  14715. EXPECT_EQ("example.com", uc.host);
  14716. EXPECT_EQ("8080", uc.port);
  14717. EXPECT_EQ("/path", uc.path);
  14718. EXPECT_EQ("?q=1", uc.query);
  14719. }
  14720. {
  14721. detail::UrlComponents uc;
  14722. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14723. EXPECT_EQ("https", uc.scheme);
  14724. EXPECT_EQ("example.com", uc.host);
  14725. EXPECT_TRUE(uc.port.empty());
  14726. EXPECT_EQ("/path", uc.path);
  14727. }
  14728. {
  14729. detail::UrlComponents uc;
  14730. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14731. EXPECT_EQ("::1", uc.host);
  14732. EXPECT_EQ("8080", uc.port);
  14733. EXPECT_EQ("/path", uc.path);
  14734. }
  14735. {
  14736. detail::UrlComponents uc;
  14737. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14738. }
  14739. {
  14740. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14741. // the path while the connection still targets the bracketed host.
  14742. detail::UrlComponents uc;
  14743. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14744. }
  14745. {
  14746. detail::UrlComponents uc;
  14747. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14748. }
  14749. {
  14750. detail::UrlComponents uc;
  14751. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14752. EXPECT_EQ("::1", uc.host);
  14753. EXPECT_TRUE(uc.port.empty());
  14754. EXPECT_EQ("/path", uc.path);
  14755. }
  14756. {
  14757. detail::UrlComponents uc;
  14758. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14759. EXPECT_TRUE(uc.scheme.empty());
  14760. EXPECT_EQ("example.com", uc.host);
  14761. EXPECT_EQ("/path", uc.path);
  14762. EXPECT_EQ("?q=1", uc.query);
  14763. }
  14764. {
  14765. detail::UrlComponents uc;
  14766. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14767. EXPECT_TRUE(uc.host.empty());
  14768. EXPECT_EQ("/path", uc.path);
  14769. EXPECT_EQ("?q=1", uc.query);
  14770. }
  14771. {
  14772. detail::UrlComponents uc;
  14773. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14774. EXPECT_EQ("example.com", uc.host);
  14775. EXPECT_EQ("8080", uc.port);
  14776. }
  14777. {
  14778. // Unix socket path — must not be parsed as host
  14779. detail::UrlComponents uc;
  14780. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14781. EXPECT_TRUE(uc.host.empty());
  14782. }
  14783. {
  14784. detail::UrlComponents uc;
  14785. ASSERT_TRUE(detail::parse_url("", uc));
  14786. EXPECT_TRUE(uc.host.empty());
  14787. EXPECT_TRUE(uc.path.empty());
  14788. }
  14789. {
  14790. detail::UrlComponents uc;
  14791. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14792. }
  14793. {
  14794. detail::UrlComponents uc;
  14795. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14796. }
  14797. {
  14798. // Accepted by parse_url; callers restrict to http/https
  14799. detail::UrlComponents uc;
  14800. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14801. EXPECT_EQ("ftp", uc.scheme);
  14802. }
  14803. {
  14804. detail::UrlComponents uc;
  14805. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14806. }
  14807. {
  14808. detail::UrlComponents uc;
  14809. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14810. }
  14811. }
  14812. TEST(ParseUrlTest, FragmentHandling) {
  14813. {
  14814. detail::UrlComponents uc;
  14815. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14816. EXPECT_EQ("/path", uc.path);
  14817. EXPECT_TRUE(uc.query.empty());
  14818. }
  14819. {
  14820. detail::UrlComponents uc;
  14821. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14822. EXPECT_TRUE(uc.path.empty());
  14823. EXPECT_TRUE(uc.query.empty());
  14824. }
  14825. }
  14826. TEST(ParseUrlTest, UserinfoHandling) {
  14827. // Userinfo with @ but no colon — host includes @
  14828. detail::UrlComponents uc;
  14829. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14830. EXPECT_EQ("user@host.com", uc.host);
  14831. EXPECT_EQ("/path", uc.path);
  14832. }
  14833. TEST(ParseUrlTest, IPv6EdgeCases) {
  14834. {
  14835. detail::UrlComponents uc;
  14836. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14837. EXPECT_TRUE(uc.scheme.empty());
  14838. EXPECT_EQ("::1", uc.host);
  14839. EXPECT_EQ("8080", uc.port);
  14840. }
  14841. {
  14842. // Zone ID '%25' is not in [a-fA-F0-9:]
  14843. detail::UrlComponents uc;
  14844. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14845. }
  14846. }
  14847. TEST(ParseUrlTest, SchemeEdgeCases) {
  14848. {
  14849. detail::UrlComponents uc;
  14850. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14851. }
  14852. {
  14853. detail::UrlComponents uc;
  14854. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14855. }
  14856. {
  14857. detail::UrlComponents uc;
  14858. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14859. }
  14860. }
  14861. TEST(ParseUrlTest, PortEdgeCases) {
  14862. {
  14863. detail::UrlComponents uc;
  14864. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14865. EXPECT_TRUE(uc.port.empty());
  14866. EXPECT_EQ("/path", uc.path);
  14867. }
  14868. {
  14869. // parse_url accepts any port string; validation is done by parse_port
  14870. detail::UrlComponents uc;
  14871. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14872. EXPECT_EQ("abc", uc.port);
  14873. }
  14874. }
  14875. TEST(ParseUrlTest, WebSocketPatterns) {
  14876. {
  14877. detail::UrlComponents uc;
  14878. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14879. EXPECT_EQ("ws", uc.scheme);
  14880. EXPECT_EQ("echo.example.com", uc.host);
  14881. EXPECT_EQ("8080", uc.port);
  14882. EXPECT_EQ("/ws", uc.path);
  14883. }
  14884. {
  14885. detail::UrlComponents uc;
  14886. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14887. EXPECT_EQ("wss", uc.scheme);
  14888. EXPECT_EQ("echo.example.com", uc.host);
  14889. EXPECT_TRUE(uc.port.empty());
  14890. EXPECT_EQ("/ws", uc.path);
  14891. }
  14892. }
  14893. TEST(ParseUrlTest, QueryOnly) {
  14894. detail::UrlComponents uc;
  14895. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14896. EXPECT_TRUE(uc.host.empty());
  14897. EXPECT_TRUE(uc.path.empty());
  14898. EXPECT_EQ("?q=1&r=2", uc.query);
  14899. }
  14900. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14901. detail::UrlComponents uc;
  14902. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14903. EXPECT_TRUE(uc.scheme.empty());
  14904. EXPECT_EQ("example.com", uc.host);
  14905. EXPECT_EQ("443", uc.port);
  14906. EXPECT_EQ("/path", uc.path);
  14907. }
  14908. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14909. // If ipv6 regex working, regex match codepath is taken.
  14910. // else port will default to 80 in Client impl
  14911. int clientImplMagicPort = 80;
  14912. int port = 4321;
  14913. // above ports must be different to avoid false negative
  14914. EXPECT_NE(clientImplMagicPort, port);
  14915. std::string ipV6TestURL = "http://[ff06::c3]";
  14916. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14917. CLIENT_PRIVATE_KEY_FILE);
  14918. EXPECT_EQ(cli.port(), port);
  14919. }
  14920. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14921. auto file_path = "./www/dir/index.html";
  14922. auto dir_path = "./www/dir";
  14923. detail::FileStat stat_file(file_path);
  14924. EXPECT_TRUE(stat_file.is_file());
  14925. EXPECT_FALSE(stat_file.is_dir());
  14926. detail::FileStat stat_dir(dir_path);
  14927. EXPECT_FALSE(stat_dir.is_file());
  14928. EXPECT_TRUE(stat_dir.is_dir());
  14929. }
  14930. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14931. // IPv4 with default HTTP port (80)
  14932. EXPECT_EQ("example.com",
  14933. detail::make_host_and_port_string("example.com", 80, false));
  14934. // IPv4 with default HTTPS port (443)
  14935. EXPECT_EQ("example.com",
  14936. detail::make_host_and_port_string("example.com", 443, true));
  14937. // IPv4 with non-default HTTP port
  14938. EXPECT_EQ("example.com:8080",
  14939. detail::make_host_and_port_string("example.com", 8080, false));
  14940. // IPv4 with non-default HTTPS port
  14941. EXPECT_EQ("example.com:8443",
  14942. detail::make_host_and_port_string("example.com", 8443, true));
  14943. // IPv6 with default HTTP port (80)
  14944. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14945. // IPv6 with default HTTPS port (443)
  14946. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14947. // IPv6 with non-default HTTP port
  14948. EXPECT_EQ("[::1]:8080",
  14949. detail::make_host_and_port_string("::1", 8080, false));
  14950. // IPv6 with non-default HTTPS port
  14951. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14952. // IPv6 full address with default port
  14953. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14954. detail::make_host_and_port_string(
  14955. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14956. // IPv6 full address with non-default port
  14957. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14958. detail::make_host_and_port_string(
  14959. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14960. // IPv6 localhost with non-default port
  14961. EXPECT_EQ("[::1]:3000",
  14962. detail::make_host_and_port_string("::1", 3000, false));
  14963. // IPv6 with zone ID (link-local address) with default port
  14964. EXPECT_EQ("[fe80::1%eth0]",
  14965. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14966. // IPv6 with zone ID (link-local address) with non-default port
  14967. EXPECT_EQ("[fe80::1%eth0]:8080",
  14968. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14969. // Edge case: Port 443 with is_ssl=false (should add port)
  14970. EXPECT_EQ("example.com:443",
  14971. detail::make_host_and_port_string("example.com", 443, false));
  14972. // Edge case: Port 80 with is_ssl=true (should add port)
  14973. EXPECT_EQ("example.com:80",
  14974. detail::make_host_and_port_string("example.com", 80, true));
  14975. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14976. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14977. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14978. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14979. // Security fix: Already bracketed IPv6 should not get double brackets
  14980. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14981. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14982. EXPECT_EQ("[::1]:8080",
  14983. detail::make_host_and_port_string("[::1]", 8080, false));
  14984. EXPECT_EQ("[2001:db8::1]:8080",
  14985. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14986. EXPECT_EQ("[fe80::1%eth0]",
  14987. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14988. EXPECT_EQ("[fe80::1%eth0]:8080",
  14989. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14990. // Edge case: Empty host (should return as-is)
  14991. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14992. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14993. // This is a known limitation but shouldn't crash
  14994. EXPECT_EQ("[host:name]",
  14995. detail::make_host_and_port_string("host:name", 80, false));
  14996. // Port number edge cases (no validation, but should not crash)
  14997. EXPECT_EQ("example.com:0",
  14998. detail::make_host_and_port_string("example.com", 0, false));
  14999. EXPECT_EQ("example.com:-1",
  15000. detail::make_host_and_port_string("example.com", -1, false));
  15001. EXPECT_EQ("example.com:65535",
  15002. detail::make_host_and_port_string("example.com", 65535, false));
  15003. EXPECT_EQ("example.com:65536",
  15004. detail::make_host_and_port_string("example.com", 65536, false));
  15005. }
  15006. #ifdef CPPHTTPLIB_SSL_ENABLED
  15007. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15008. httplib::SSLClient cli("roblox.com", 443);
  15009. cli.set_follow_location(true);
  15010. auto res = cli.Get("/");
  15011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15012. EXPECT_EQ(StatusCode::OK_200, res->status);
  15013. }
  15014. #endif
  15015. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15016. Server svr;
  15017. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15018. EXPECT_EQ(res.status, 400);
  15019. });
  15020. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15021. auto se = detail::scope_exit([&] {
  15022. svr.stop();
  15023. thread.join();
  15024. ASSERT_FALSE(svr.is_running());
  15025. });
  15026. svr.wait_until_ready();
  15027. Client cli(HOST, PORT);
  15028. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15029. }
  15030. TEST(InvalidHeaderCharsTest, is_field_name) {
  15031. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15032. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15033. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15034. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15035. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15036. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15037. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15038. EXPECT_FALSE(detail::fields::is_field_name(""));
  15039. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15040. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15041. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15042. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15043. }
  15044. TEST(InvalidHeaderCharsTest, is_field_value) {
  15045. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15046. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15047. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15048. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15049. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15050. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15051. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15052. EXPECT_TRUE(detail::fields::is_field_value(""));
  15053. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15054. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15055. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15056. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15057. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15058. }
  15059. TEST(InvalidHeaderCharsTest, OnServer) {
  15060. Server svr;
  15061. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15062. std::string header = "Not Set";
  15063. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15064. res.set_header(header, "value");
  15065. res.set_content("Page Content Page Content", "text/plain");
  15066. });
  15067. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15068. std::string header = "Not Set";
  15069. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15070. res.set_header("X-Test", header);
  15071. res.set_content("Page Content Page Content", "text/plain");
  15072. });
  15073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15074. auto se = detail::scope_exit([&] {
  15075. svr.stop();
  15076. thread.join();
  15077. ASSERT_FALSE(svr.is_running());
  15078. });
  15079. svr.wait_until_ready();
  15080. Client cli(HOST, PORT);
  15081. {
  15082. auto res = cli.Get(
  15083. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15085. EXPECT_EQ("Page Content Page Content", res->body);
  15086. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15087. }
  15088. {
  15089. auto res = cli.Get(
  15090. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15092. EXPECT_EQ("Page Content Page Content", res->body);
  15093. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15094. }
  15095. }
  15096. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15097. auto handled = false;
  15098. Server svr;
  15099. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15100. thread t = thread([&] { svr.listen(HOST, PORT); });
  15101. auto se = detail::scope_exit([&] {
  15102. svr.stop();
  15103. t.join();
  15104. ASSERT_FALSE(svr.is_running());
  15105. ASSERT_FALSE(handled);
  15106. });
  15107. svr.wait_until_ready();
  15108. auto req = "POST /test HTTP/1.1\r\n"
  15109. "Content-Length: x\r\n"
  15110. "\r\n";
  15111. std::string response;
  15112. ASSERT_TRUE(send_request(1, req, &response));
  15113. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15114. response.substr(0, response.find("\r\n")));
  15115. }
  15116. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15117. // case-insensitive, and a server that receives a 100-continue expectation in
  15118. // an HTTP/1.0 request MUST ignore it.
  15119. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15120. std::string response;
  15121. ASSERT_TRUE(send_request(1, req, &response, port));
  15122. *got_100 = response.find("100 Continue") != std::string::npos;
  15123. }
  15124. class ExpectTokenTest : public ::testing::Test {
  15125. protected:
  15126. void SetUp() override {
  15127. svr_.Post("/p", [](const Request &, Response &res) {
  15128. res.set_content("ok", "text/plain");
  15129. });
  15130. port_ = svr_.bind_to_any_port(HOST);
  15131. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15132. svr_.wait_until_ready();
  15133. }
  15134. void TearDown() override {
  15135. svr_.stop();
  15136. if (thread_.joinable()) { thread_.join(); }
  15137. }
  15138. std::string request(const char *version, const char *expect_value) const {
  15139. return std::string("POST /p ") + version +
  15140. "\r\n"
  15141. "Host: localhost\r\n"
  15142. "Content-Length: 2\r\n"
  15143. "Connection: close\r\n"
  15144. "Expect: " +
  15145. expect_value +
  15146. "\r\n"
  15147. "\r\n"
  15148. "hi";
  15149. }
  15150. Server svr_;
  15151. int port_ = 0;
  15152. thread thread_;
  15153. };
  15154. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15155. bool got_100 = false;
  15156. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15157. EXPECT_TRUE(got_100);
  15158. }
  15159. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15160. bool got_100 = true;
  15161. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15162. EXPECT_FALSE(got_100);
  15163. }
  15164. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15165. bool got_100 = false;
  15166. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15167. EXPECT_TRUE(got_100);
  15168. }
  15169. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15170. bool got_100 = false;
  15171. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15172. EXPECT_TRUE(got_100);
  15173. }
  15174. // `100 Continue` is sent only when the server starts reading the body, so a
  15175. // request rejected before that never invites the client to send it. The
  15176. // requests below carry the expectation but withhold the body, as a client
  15177. // waiting for `100 Continue` would.
  15178. // A POST that expects `100 Continue` and withholds its two-byte body.
  15179. static std::string expect_headers_only(const std::string &path) {
  15180. return "POST " + path +
  15181. " HTTP/1.1\r\n"
  15182. "Host: localhost\r\n"
  15183. "Content-Length: 2\r\n"
  15184. "Expect: 100-continue\r\n"
  15185. "\r\n";
  15186. }
  15187. class ExpectLazyContinueTest : public ::testing::Test {
  15188. protected:
  15189. void SetUp() override {
  15190. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15191. if (req.path == "/pre-routing") {
  15192. res.status = StatusCode::Unauthorized_401;
  15193. return Server::HandlerResponse::Handled;
  15194. }
  15195. return Server::HandlerResponse::Unhandled;
  15196. });
  15197. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15198. if (req.matched_route == "/pre-request") {
  15199. res.status = StatusCode::Forbidden_403;
  15200. return Server::HandlerResponse::Handled;
  15201. }
  15202. return Server::HandlerResponse::Unhandled;
  15203. });
  15204. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15205. res.set_content("ok", "text/plain");
  15206. });
  15207. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15208. res.set_content("ok", "text/plain");
  15209. });
  15210. svr_.Post("/reader-used", [](const Request &, Response &res,
  15211. const ContentReader &content_reader) {
  15212. std::string body;
  15213. content_reader([&](const char *data, size_t len) {
  15214. body.append(data, len);
  15215. return true;
  15216. });
  15217. res.set_content(body, "text/plain");
  15218. });
  15219. svr_.Post("/reader-unused",
  15220. [](const Request &, Response &res, const ContentReader &) {
  15221. res.set_content("ignored", "text/plain");
  15222. });
  15223. port_ = svr_.bind_to_any_port(HOST);
  15224. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15225. svr_.wait_until_ready();
  15226. }
  15227. void TearDown() override {
  15228. svr_.stop();
  15229. if (thread_.joinable()) { thread_.join(); }
  15230. }
  15231. // Sends `req` and reads until the server closes the connection. Returns
  15232. // false if the read had to wait for the client-side timeout instead.
  15233. bool send_until_closed(const std::string &req, std::string *resp) const {
  15234. auto start = std::chrono::steady_clock::now();
  15235. if (!send_request(3, req, resp, port_)) { return false; }
  15236. auto elapsed = std::chrono::steady_clock::now() - start;
  15237. return elapsed < std::chrono::seconds(2);
  15238. }
  15239. // The final response comes without `100 Continue`, and the server closes
  15240. // the connection since the body may or may not follow.
  15241. void expect_final_without_interim(const std::string &path,
  15242. const char *status_line) const {
  15243. std::string resp;
  15244. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15245. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15246. EXPECT_EQ(0u, resp.find(status_line));
  15247. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15248. }
  15249. Server svr_;
  15250. int port_ = 0;
  15251. thread thread_;
  15252. };
  15253. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15254. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15255. }
  15256. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15257. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15258. }
  15259. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15260. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15261. }
  15262. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15263. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15264. }
  15265. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15266. // The body follows once `100 Continue` has had time to arrive.
  15267. auto req = expect_headers_only("/reader-used");
  15268. req.insert(req.size() - 2, "Connection: close\r\n");
  15269. std::string resp;
  15270. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15271. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15272. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15273. EXPECT_NE(std::string::npos, resp.find("hi"));
  15274. }
  15275. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15276. // Large enough for the client to add `Expect: 100-continue` itself.
  15277. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15278. std::atomic<bool> body_sent{false};
  15279. Client cli(HOST, port_);
  15280. auto res = cli.Post(
  15281. "/pre-request", length,
  15282. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15283. body_sent = true;
  15284. std::string chunk(len, 'x');
  15285. sink.write(chunk.data(), chunk.size());
  15286. return true;
  15287. },
  15288. "application/octet-stream");
  15289. ASSERT_TRUE(res);
  15290. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15291. EXPECT_FALSE(body_sent);
  15292. }
  15293. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15294. Server svr;
  15295. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15296. return StatusCode::ExpectationFailed_417;
  15297. });
  15298. svr.Post("/p", [](const Request &, Response &res) {
  15299. res.set_content("ok", "text/plain");
  15300. });
  15301. auto port = svr.bind_to_any_port(HOST);
  15302. thread t = thread([&] { svr.listen_after_bind(); });
  15303. auto se = detail::scope_exit([&] {
  15304. svr.stop();
  15305. t.join();
  15306. });
  15307. svr.wait_until_ready();
  15308. std::string resp;
  15309. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15310. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15311. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15312. // Exactly one response: the route handler must not run after the 417.
  15313. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15314. }
  15315. #ifndef _WIN32
  15316. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15317. static constexpr char reject[] = "Unauthorized";
  15318. static constexpr char accept[] = "Upload accepted";
  15319. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15320. Server svr;
  15321. svr.set_expect_100_continue_handler(
  15322. [](const Request & /*req*/, Response &res) {
  15323. res.status = StatusCode::Unauthorized_401;
  15324. res.set_content(reject, "text/plain");
  15325. return res.status;
  15326. });
  15327. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15328. res.set_content(accept, "text/plain");
  15329. });
  15330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15331. auto se = detail::scope_exit([&] {
  15332. svr.stop();
  15333. thread.join();
  15334. ASSERT_FALSE(svr.is_running());
  15335. });
  15336. svr.wait_until_ready();
  15337. {
  15338. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15339. curl_easy_init(), &curl_easy_cleanup};
  15340. ASSERT_NE(curl, nullptr);
  15341. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15342. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15343. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15344. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15345. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15346. &curl_slist_free_all};
  15347. ASSERT_NE(list, nullptr);
  15348. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15349. struct read_data {
  15350. size_t read_size;
  15351. size_t total_size;
  15352. } data = {0, total_size};
  15353. using read_callback_t =
  15354. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15355. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15356. void *userdata) -> size_t {
  15357. read_data *d = (read_data *)userdata;
  15358. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15359. std::fill_n(ptr, size * nmemb, 'A');
  15360. d->read_size += size * nmemb;
  15361. return size * nmemb;
  15362. };
  15363. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15364. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15365. std::vector<char> buffer;
  15366. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15367. using write_callback_t =
  15368. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15369. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15370. void *userdata) -> size_t {
  15371. std::vector<char> *buf = (std::vector<char> *)userdata;
  15372. buf->reserve(buf->size() + size * nmemb + 1);
  15373. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15374. return size * nmemb;
  15375. };
  15376. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15377. {
  15378. const auto res = curl_easy_perform(curl.get());
  15379. ASSERT_EQ(res, CURLE_OK);
  15380. }
  15381. {
  15382. auto response_code = long{};
  15383. const auto res =
  15384. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15385. ASSERT_EQ(res, CURLE_OK);
  15386. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15387. }
  15388. {
  15389. auto dl = curl_off_t{};
  15390. const auto res =
  15391. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15392. ASSERT_EQ(res, CURLE_OK);
  15393. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15394. }
  15395. {
  15396. buffer.push_back('\0');
  15397. ASSERT_STRCASEEQ(buffer.data(), reject);
  15398. }
  15399. }
  15400. }
  15401. #endif
  15402. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15403. // Regression test for #2458.
  15404. //
  15405. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15406. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15407. // ticket can make the client socket spuriously readable during the
  15408. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15409. // the client withholds the body and then blocks reading a response that never
  15410. // comes, failing with `Failed to read connection`.
  15411. //
  15412. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15413. // within the timeout. This raw OpenSSL server deliberately never sends
  15414. // `100 Continue`; the client must still deliver the body and receive 200.
  15415. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15416. signal(SIGPIPE, SIG_IGN);
  15417. const auto port = PORT + 4;
  15418. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15419. ASSERT_NE(srv, INVALID_SOCKET);
  15420. int opt = 1;
  15421. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15422. sockaddr_in addr{};
  15423. addr.sin_family = AF_INET;
  15424. addr.sin_port = htons(static_cast<uint16_t>(port));
  15425. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15426. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15427. ASSERT_EQ(0, ::listen(srv, 1));
  15428. std::atomic<size_t> server_body_bytes{0};
  15429. auto server_thread = std::thread([&] {
  15430. sockaddr_in cli_addr{};
  15431. socklen_t cli_len = sizeof(cli_addr);
  15432. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15433. if (cli == INVALID_SOCKET) { return; }
  15434. // Bound the lifetime of the server side so a buggy client (which never
  15435. // sends the body) cannot make this thread block forever on join.
  15436. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15437. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15438. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15439. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15440. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15441. SSL *ssl = SSL_new(ctx);
  15442. SSL_set_fd(ssl, static_cast<int>(cli));
  15443. if (SSL_accept(ssl) > 0) {
  15444. // Read the request headers. Reading here also flushes the TLS 1.3
  15445. // session tickets to the client. Deliberately do NOT send
  15446. // `100 Continue`.
  15447. std::string buf;
  15448. char tmp[1024];
  15449. while (buf.find("\r\n\r\n") == std::string::npos) {
  15450. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15451. if (n <= 0) { break; }
  15452. buf.append(tmp, static_cast<size_t>(n));
  15453. }
  15454. // A correct client sends the body now; count what arrives.
  15455. auto pos = buf.find("\r\n\r\n");
  15456. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15457. while (body < 4096) {
  15458. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15459. if (n <= 0) { break; }
  15460. body += static_cast<size_t>(n);
  15461. }
  15462. server_body_bytes = body;
  15463. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15464. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15465. SSL_shutdown(ssl);
  15466. }
  15467. SSL_free(ssl);
  15468. detail::close_socket(cli);
  15469. SSL_CTX_free(ctx);
  15470. });
  15471. auto se = detail::scope_exit([&] {
  15472. server_thread.join();
  15473. detail::close_socket(srv);
  15474. });
  15475. SSLClient cli("127.0.0.1", port);
  15476. cli.enable_server_certificate_verification(false);
  15477. cli.set_connection_timeout(5, 0);
  15478. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15479. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15480. std::string body(4096, 'A');
  15481. auto res = cli.Put("/api/test", body, "application/json");
  15482. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15483. EXPECT_EQ(StatusCode::OK_200, res->status);
  15484. EXPECT_EQ(body.size(), server_body_bytes.load());
  15485. }
  15486. #endif
  15487. template <typename S, typename C>
  15488. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15489. svr.Get("/stream", [&](const Request &, Response &res) {
  15490. auto data = new std::string("01234567890123456789");
  15491. res.set_content_provider(
  15492. data->size(), "text/plain",
  15493. [&, data](size_t offset, size_t length, DataSink &sink) {
  15494. const size_t DATA_CHUNK_SIZE = 4;
  15495. const auto &d = *data;
  15496. std::this_thread::sleep_for(std::chrono::seconds(1));
  15497. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15498. return true;
  15499. },
  15500. [data](bool success) {
  15501. EXPECT_FALSE(success);
  15502. delete data;
  15503. });
  15504. });
  15505. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15506. auto i = new size_t(0);
  15507. res.set_content_provider(
  15508. "text/plain",
  15509. [i](size_t, DataSink &sink) {
  15510. if (*i < 5) {
  15511. std::this_thread::sleep_for(std::chrono::seconds(1));
  15512. sink.write("abcd", 4);
  15513. (*i)++;
  15514. } else {
  15515. sink.done();
  15516. }
  15517. return true;
  15518. },
  15519. [i](bool success) {
  15520. EXPECT_FALSE(success);
  15521. delete i;
  15522. });
  15523. });
  15524. svr.Get("/chunked", [&](const Request &, Response &res) {
  15525. auto i = new size_t(0);
  15526. res.set_chunked_content_provider(
  15527. "text/plain",
  15528. [i](size_t, DataSink &sink) {
  15529. if (*i < 5) {
  15530. std::this_thread::sleep_for(std::chrono::seconds(1));
  15531. sink.os << "abcd";
  15532. (*i)++;
  15533. } else {
  15534. sink.done();
  15535. }
  15536. return true;
  15537. },
  15538. [i](bool success) {
  15539. EXPECT_FALSE(success);
  15540. delete i;
  15541. });
  15542. });
  15543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15544. auto se = detail::scope_exit([&] {
  15545. svr.stop();
  15546. listen_thread.join();
  15547. ASSERT_FALSE(svr.is_running());
  15548. });
  15549. svr.wait_until_ready();
  15550. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15551. {
  15552. auto start = std::chrono::steady_clock::now();
  15553. auto res = cli.Get("/stream");
  15554. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15555. std::chrono::steady_clock::now() - start)
  15556. .count();
  15557. ASSERT_FALSE(res);
  15558. EXPECT_EQ(Error::Read, res.error());
  15559. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15560. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15561. }
  15562. {
  15563. auto start = std::chrono::steady_clock::now();
  15564. auto res = cli.Get("/stream_without_length");
  15565. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15566. std::chrono::steady_clock::now() - start)
  15567. .count();
  15568. ASSERT_FALSE(res);
  15569. EXPECT_EQ(Error::Read, res.error());
  15570. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15571. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15572. }
  15573. {
  15574. auto start = std::chrono::steady_clock::now();
  15575. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15576. EXPECT_EQ("abcd", string(data, data_length));
  15577. return true;
  15578. });
  15579. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15580. std::chrono::steady_clock::now() - start)
  15581. .count();
  15582. ASSERT_FALSE(res);
  15583. EXPECT_EQ(Error::Read, res.error());
  15584. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15585. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15586. }
  15587. }
  15588. TEST(MaxTimeoutTest, ContentStream) {
  15589. time_t timeout = 2000;
  15590. time_t threshold = 200;
  15591. Server svr;
  15592. Client cli("localhost", PORT);
  15593. max_timeout_test(svr, cli, timeout, threshold);
  15594. }
  15595. #ifdef CPPHTTPLIB_SSL_ENABLED
  15596. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15597. time_t timeout = 2000;
  15598. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15600. SSLClient cli("localhost", PORT);
  15601. cli.enable_server_certificate_verification(false);
  15602. max_timeout_test(svr, cli, timeout, threshold);
  15603. }
  15604. #endif
  15605. class EventDispatcher {
  15606. public:
  15607. EventDispatcher() {}
  15608. bool wait_event(DataSink *sink) {
  15609. unique_lock<mutex> lk(m_);
  15610. int id = id_;
  15611. // Wait with timeout to prevent hanging if client disconnects
  15612. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15613. [&] { return cid_ == id; })) {
  15614. return false; // Timeout occurred
  15615. }
  15616. sink->write(message_.data(), message_.size());
  15617. return true;
  15618. }
  15619. void send_event(const string &message) {
  15620. lock_guard<mutex> lk(m_);
  15621. cid_ = id_++;
  15622. message_ = message;
  15623. cv_.notify_all();
  15624. }
  15625. private:
  15626. mutex m_;
  15627. condition_variable cv_;
  15628. atomic_int id_{0};
  15629. atomic_int cid_{-1};
  15630. string message_;
  15631. };
  15632. TEST(ClientInThreadTest, Issue2068) {
  15633. EventDispatcher ed;
  15634. Server svr;
  15635. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15636. res.set_chunked_content_provider("text/event-stream",
  15637. [&](size_t /*offset*/, DataSink &sink) {
  15638. return ed.wait_event(&sink);
  15639. });
  15640. });
  15641. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15642. svr.wait_until_ready();
  15643. thread event_thread([&] {
  15644. int id = 0;
  15645. while (svr.is_running()) {
  15646. this_thread::sleep_for(chrono::milliseconds(500));
  15647. std::stringstream ss;
  15648. ss << "data: " << id << "\n\n";
  15649. ed.send_event(ss.str());
  15650. id++;
  15651. }
  15652. });
  15653. auto se = detail::scope_exit([&] {
  15654. svr.stop();
  15655. listen_thread.join();
  15656. event_thread.join();
  15657. ASSERT_FALSE(svr.is_running());
  15658. });
  15659. {
  15660. auto client = detail::make_unique<Client>(HOST, PORT);
  15661. client->set_read_timeout(std::chrono::minutes(10));
  15662. std::atomic<bool> stop{false};
  15663. std::thread t([&] {
  15664. client->Get("/event1",
  15665. [&](const char *, size_t) -> bool { return !stop; });
  15666. });
  15667. std::this_thread::sleep_for(std::chrono::seconds(2));
  15668. stop = true;
  15669. client->stop();
  15670. t.join();
  15671. // Reset client after thread has finished
  15672. client.reset();
  15673. }
  15674. }
  15675. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15676. auto handled = false;
  15677. Server svr;
  15678. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15679. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15680. auto se = detail::scope_exit([&] {
  15681. svr.stop();
  15682. t.join();
  15683. ASSERT_FALSE(svr.is_running());
  15684. ASSERT_FALSE(handled);
  15685. });
  15686. svr.wait_until_ready();
  15687. // Two Content-Length headers with different values — must be rejected
  15688. auto req = "POST /test HTTP/1.1\r\n"
  15689. "Content-Length: 5\r\n"
  15690. "Content-Length: 10\r\n"
  15691. "\r\n"
  15692. "hello";
  15693. std::string response;
  15694. ASSERT_TRUE(send_request(1, req, &response));
  15695. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15696. response.substr(0, response.find("\r\n")));
  15697. }
  15698. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15699. auto handled = false;
  15700. Server svr;
  15701. svr.Post("/test", [&](const Request &, Response &res) {
  15702. handled = true;
  15703. res.set_content("ok", "text/plain");
  15704. });
  15705. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15706. auto se = detail::scope_exit([&] {
  15707. svr.stop();
  15708. t.join();
  15709. ASSERT_FALSE(svr.is_running());
  15710. ASSERT_TRUE(handled);
  15711. });
  15712. svr.wait_until_ready();
  15713. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15714. auto req = "POST /test HTTP/1.1\r\n"
  15715. "Content-Length: 5\r\n"
  15716. "Content-Length: 5\r\n"
  15717. "\r\n"
  15718. "hello";
  15719. std::string response;
  15720. ASSERT_TRUE(send_request(1, req, &response));
  15721. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15722. }
  15723. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15724. Server svr;
  15725. svr.Get("/", [](const Request &req, Response &res) {
  15726. EXPECT_EQ(2U, req.trailers.size());
  15727. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15728. // Denied
  15729. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15730. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15731. // Accepted
  15732. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15733. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15734. EXPECT_TRUE(req.has_trailer("X-World"));
  15735. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15736. res.set_content("ok", "text/plain");
  15737. });
  15738. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15739. auto se = detail::scope_exit([&] {
  15740. svr.stop();
  15741. t.join();
  15742. ASSERT_FALSE(svr.is_running());
  15743. });
  15744. svr.wait_until_ready();
  15745. const std::string req = "GET / HTTP/1.1\r\n"
  15746. "Transfer-Encoding: chunked\r\n"
  15747. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15748. "\r\n"
  15749. "0\r\n"
  15750. "Content-Length: 10\r\n"
  15751. "Host: internal.local\r\n"
  15752. "Content-Type: malicious/content\r\n"
  15753. "Cookie: any\r\n"
  15754. "Set-Cookie: any\r\n"
  15755. "X-Forwarded-For: attacker.com\r\n"
  15756. "X-Real-Ip: 1.1.1.1\r\n"
  15757. "X-Hello: hello\r\n"
  15758. "X-World: world\r\n"
  15759. "\r\n";
  15760. std::string res;
  15761. ASSERT_TRUE(send_request(1, req, &res));
  15762. }
  15763. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15764. // several field lines, and the combined value is what has to be parsed. A
  15765. // Trailer field split across lines therefore declares every name it lists;
  15766. // reading only the first line silently drops the trailers the later lines
  15767. // declare. The prohibited-trailer filter still applies to every line.
  15768. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15769. Server svr;
  15770. size_t observed_trailer_count = 0;
  15771. std::string observed_hello;
  15772. std::string observed_world;
  15773. bool observed_content_length = true;
  15774. svr.Get("/", [&](const Request &req, Response &res) {
  15775. observed_trailer_count = req.trailers.size();
  15776. observed_hello = req.get_trailer_value("X-Hello");
  15777. observed_world = req.get_trailer_value("X-World");
  15778. observed_content_length = req.has_trailer("Content-Length");
  15779. res.set_content("ok", "text/plain");
  15780. });
  15781. auto port = svr.bind_to_any_port(HOST);
  15782. thread t = thread([&]() { svr.listen_after_bind(); });
  15783. auto se = detail::scope_exit([&] {
  15784. svr.stop();
  15785. t.join();
  15786. ASSERT_FALSE(svr.is_running());
  15787. });
  15788. svr.wait_until_ready();
  15789. const std::string req = "GET / HTTP/1.1\r\n"
  15790. "Transfer-Encoding: chunked\r\n"
  15791. "Trailer: X-Hello\r\n"
  15792. "Trailer: X-World, Content-Length\r\n"
  15793. "\r\n"
  15794. "0\r\n"
  15795. "X-Hello: hello\r\n"
  15796. "X-World: world\r\n"
  15797. "Content-Length: 10\r\n"
  15798. "\r\n";
  15799. std::string res;
  15800. ASSERT_TRUE(send_request(1, req, &res, port));
  15801. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  15802. // Accepted: both field lines contribute to the declared set
  15803. EXPECT_EQ(2U, observed_trailer_count);
  15804. EXPECT_EQ(observed_hello, "hello");
  15805. EXPECT_EQ(observed_world, "world");
  15806. // Denied: a prohibited name stays prohibited on a later field line
  15807. EXPECT_FALSE(observed_content_length);
  15808. }
  15809. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  15810. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  15811. // unbounded run of fields that are never declared, because the counter would
  15812. // only advance for declared fields.
  15813. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  15814. Server svr;
  15815. bool handler_called = false;
  15816. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  15817. handler_called = true;
  15818. res.set_content("ok", "text/plain");
  15819. });
  15820. auto port = svr.bind_to_any_port(HOST);
  15821. thread t = thread([&]() { svr.listen_after_bind(); });
  15822. auto se = detail::scope_exit([&] {
  15823. svr.stop();
  15824. t.join();
  15825. ASSERT_FALSE(svr.is_running());
  15826. });
  15827. svr.wait_until_ready();
  15828. // Declare nothing, then send far more undeclared trailer fields than the
  15829. // header-count limit. Parsing must stop and reject the request rather than
  15830. // read every line.
  15831. std::string req = "GET / HTTP/1.1\r\n"
  15832. "Transfer-Encoding: chunked\r\n"
  15833. "\r\n"
  15834. "0\r\n";
  15835. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  15836. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  15837. }
  15838. req += "\r\n";
  15839. std::string res;
  15840. ASSERT_TRUE(send_request(1, req, &res, port));
  15841. // The request is rejected before the handler runs.
  15842. EXPECT_FALSE(handler_called);
  15843. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  15844. }
  15845. // The set of declared trailer names is capped so a peer cannot grow it without
  15846. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  15847. // declared past the cap is not honored, even if the field is actually sent.
  15848. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  15849. Server svr;
  15850. // One name inside the cap and one past it, so the test tracks the cap rather
  15851. // than a fixed count.
  15852. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  15853. const std::string within_cap_name = "X-T-0";
  15854. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  15855. bool observed_within_cap = false;
  15856. bool observed_past_cap = false;
  15857. svr.Get("/", [&](const Request &req, Response &res) {
  15858. observed_within_cap = req.has_trailer(within_cap_name);
  15859. observed_past_cap = req.has_trailer(past_cap_name);
  15860. res.set_content("ok", "text/plain");
  15861. });
  15862. auto port = svr.bind_to_any_port(HOST);
  15863. thread t = thread([&]() { svr.listen_after_bind(); });
  15864. auto se = detail::scope_exit([&] {
  15865. svr.stop();
  15866. t.join();
  15867. ASSERT_FALSE(svr.is_running());
  15868. });
  15869. svr.wait_until_ready();
  15870. // Declare more trailer names than the cap in a single Trailer field, then
  15871. // actually send the first (within the cap) and the last (past it).
  15872. std::string trailer_decl = "Trailer: ";
  15873. for (int i = 0; i < declared_count; i++) {
  15874. if (i != 0) { trailer_decl += ", "; }
  15875. trailer_decl += "X-T-" + std::to_string(i);
  15876. }
  15877. trailer_decl += "\r\n";
  15878. const std::string req = "GET / HTTP/1.1\r\n"
  15879. "Transfer-Encoding: chunked\r\n" +
  15880. trailer_decl +
  15881. "\r\n"
  15882. "0\r\n" +
  15883. within_cap_name + ": a\r\n" + past_cap_name +
  15884. ": b\r\n"
  15885. "\r\n";
  15886. std::string res;
  15887. ASSERT_TRUE(send_request(1, req, &res, port));
  15888. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  15889. // A name within the cap is honored; one declared past the cap is dropped.
  15890. EXPECT_TRUE(observed_within_cap);
  15891. EXPECT_FALSE(observed_past_cap);
  15892. }
  15893. // A direct client that is not listed in trusted_proxies must not be able to
  15894. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  15895. // the peer address on the actual TCP connection determines whether the
  15896. // header is honored.
  15897. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  15898. Server svr;
  15899. // Deliberately does NOT include the loopback address the test client
  15900. // actually connects from, so the direct connection is not a trusted proxy.
  15901. svr.set_trusted_proxies({"203.0.113.66"});
  15902. std::string observed_remote_addr;
  15903. svr.Get("/ip", [&](const Request &req, Response &res) {
  15904. observed_remote_addr = req.remote_addr;
  15905. res.set_content("ok", "text/plain");
  15906. });
  15907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15908. auto se = detail::scope_exit([&] {
  15909. svr.stop();
  15910. t.join();
  15911. ASSERT_FALSE(svr.is_running());
  15912. });
  15913. svr.wait_until_ready();
  15914. Client cli(HOST, PORT);
  15915. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15917. EXPECT_EQ(StatusCode::OK_200, res->status);
  15918. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15919. // ignored entirely and the real connection-level address retained.
  15920. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15921. observed_remote_addr == "127.0.0.1");
  15922. }
  15923. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15924. Server svr;
  15925. std::string observed_remote_addr;
  15926. std::string observed_xff;
  15927. svr.Get("/ip", [&](const Request &req, Response &res) {
  15928. observed_remote_addr = req.remote_addr;
  15929. observed_xff = req.get_header_value("X-Forwarded-For");
  15930. res.set_content("ok", "text/plain");
  15931. });
  15932. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15933. auto se = detail::scope_exit([&] {
  15934. svr.stop();
  15935. t.join();
  15936. ASSERT_FALSE(svr.is_running());
  15937. });
  15938. svr.wait_until_ready();
  15939. Client cli(HOST, PORT);
  15940. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15942. EXPECT_EQ(StatusCode::OK_200, res->status);
  15943. EXPECT_EQ(observed_xff, "203.0.113.66");
  15944. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15945. observed_remote_addr == "127.0.0.1");
  15946. }
  15947. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15948. Server svr;
  15949. svr.set_trusted_proxies({"203.0.113.66"});
  15950. std::string observed_remote_addr;
  15951. std::string observed_xff;
  15952. svr.Get("/ip", [&](const Request &req, Response &res) {
  15953. observed_remote_addr = req.remote_addr;
  15954. observed_xff = req.get_header_value("X-Forwarded-For");
  15955. res.set_content("ok", "text/plain");
  15956. });
  15957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15958. auto se = detail::scope_exit([&] {
  15959. svr.stop();
  15960. t.join();
  15961. ASSERT_FALSE(svr.is_running());
  15962. });
  15963. svr.wait_until_ready();
  15964. Client cli(HOST, PORT);
  15965. auto res = cli.Get("/ip");
  15966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15967. EXPECT_EQ(StatusCode::OK_200, res->status);
  15968. EXPECT_EQ(observed_xff, "");
  15969. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15970. observed_remote_addr == "127.0.0.1");
  15971. }
  15972. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15973. Server svr;
  15974. // Include the loopback address the test client actually connects from, so
  15975. // the direct connection itself is recognized as the trusted proxy hop.
  15976. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15977. std::string observed_remote_addr;
  15978. std::string observed_xff;
  15979. svr.Get("/ip", [&](const Request &req, Response &res) {
  15980. observed_remote_addr = req.remote_addr;
  15981. observed_xff = req.get_header_value("X-Forwarded-For");
  15982. res.set_content("ok", "text/plain");
  15983. });
  15984. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15985. auto se = detail::scope_exit([&] {
  15986. svr.stop();
  15987. t.join();
  15988. ASSERT_FALSE(svr.is_running());
  15989. });
  15990. svr.wait_until_ready();
  15991. Client cli(HOST, PORT);
  15992. auto res = cli.Get(
  15993. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15995. EXPECT_EQ(StatusCode::OK_200, res->status);
  15996. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15997. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15998. }
  15999. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16000. Server svr;
  16001. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16002. std::string observed_remote_addr;
  16003. std::string observed_xff;
  16004. svr.Get("/ip", [&](const Request &req, Response &res) {
  16005. observed_remote_addr = req.remote_addr;
  16006. observed_xff = req.get_header_value("X-Forwarded-For");
  16007. res.set_content("ok", "text/plain");
  16008. });
  16009. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16010. auto se = detail::scope_exit([&] {
  16011. svr.stop();
  16012. t.join();
  16013. ASSERT_FALSE(svr.is_running());
  16014. });
  16015. svr.wait_until_ready();
  16016. Client cli(HOST, PORT);
  16017. auto res = cli.Get(
  16018. "/ip",
  16019. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16021. EXPECT_EQ(StatusCode::OK_200, res->status);
  16022. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16023. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16024. }
  16025. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16026. Server svr;
  16027. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16028. std::string observed_remote_addr;
  16029. std::string observed_xff;
  16030. svr.Get("/ip", [&](const Request &req, Response &res) {
  16031. observed_remote_addr = req.remote_addr;
  16032. observed_xff = req.get_header_value("X-Forwarded-For");
  16033. res.set_content("ok", "text/plain");
  16034. });
  16035. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16036. auto se = detail::scope_exit([&] {
  16037. svr.stop();
  16038. t.join();
  16039. ASSERT_FALSE(svr.is_running());
  16040. });
  16041. svr.wait_until_ready();
  16042. Client cli(HOST, PORT);
  16043. auto res = cli.Get(
  16044. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16046. EXPECT_EQ(StatusCode::OK_200, res->status);
  16047. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16048. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16049. // and must not be selected.
  16050. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16051. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16052. }
  16053. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16054. Server svr;
  16055. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16056. std::string observed_remote_addr;
  16057. svr.Get("/ip", [&](const Request &req, Response &res) {
  16058. observed_remote_addr = req.remote_addr;
  16059. res.set_content("ok", "text/plain");
  16060. });
  16061. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16062. auto se = detail::scope_exit([&] {
  16063. svr.stop();
  16064. t.join();
  16065. ASSERT_FALSE(svr.is_running());
  16066. });
  16067. svr.wait_until_ready();
  16068. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16069. // a forged address and the trusted proxy's own address; the forged value must
  16070. // not win over the address the trusted proxy actually recorded.
  16071. Client cli(HOST, PORT);
  16072. auto res = cli.Get(
  16073. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16075. EXPECT_EQ(StatusCode::OK_200, res->status);
  16076. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16077. }
  16078. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16079. Server svr;
  16080. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16081. std::string observed_remote_addr;
  16082. std::string observed_xff;
  16083. svr.Get("/ip", [&](const Request &req, Response &res) {
  16084. observed_remote_addr = req.remote_addr;
  16085. observed_xff = req.get_header_value("X-Forwarded-For");
  16086. res.set_content("ok", "text/plain");
  16087. });
  16088. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16089. auto se = detail::scope_exit([&] {
  16090. svr.stop();
  16091. t.join();
  16092. ASSERT_FALSE(svr.is_running());
  16093. });
  16094. svr.wait_until_ready();
  16095. Client cli(HOST, PORT);
  16096. auto res = cli.Get(
  16097. "/ip",
  16098. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16100. EXPECT_EQ(StatusCode::OK_200, res->status);
  16101. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16102. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16103. }
  16104. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16105. Server svr;
  16106. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16107. std::string observed_remote_addr;
  16108. std::string observed_xff;
  16109. svr.Get("/ip", [&](const Request &req, Response &res) {
  16110. observed_remote_addr = req.remote_addr;
  16111. observed_xff = req.get_header_value("X-Forwarded-For");
  16112. res.set_content("ok", "text/plain");
  16113. });
  16114. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16115. auto se = detail::scope_exit([&] {
  16116. svr.stop();
  16117. t.join();
  16118. ASSERT_FALSE(svr.is_running());
  16119. });
  16120. svr.wait_until_ready();
  16121. std::string raw_req =
  16122. "GET /ip HTTP/1.1\r\n"
  16123. "Host: localhost\r\n"
  16124. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16125. "Connection: close\r\n"
  16126. "\r\n";
  16127. std::string out;
  16128. ASSERT_TRUE(send_request(5, raw_req, &out));
  16129. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16130. // Header parser trims surrounding whitespace of the header value
  16131. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16132. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16133. }
  16134. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16135. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16136. // their own X-Forwarded-For as a separate field line rather than extending the
  16137. // one the client sent, so every occurrence has to be taken into account.
  16138. // Reading only the first one hands back the address the client chose.
  16139. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16140. Server svr;
  16141. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16142. std::string observed_remote_addr;
  16143. size_t observed_xff_count = 0;
  16144. svr.Get("/ip", [&](const Request &req, Response &res) {
  16145. observed_remote_addr = req.remote_addr;
  16146. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16147. res.set_content("ok", "text/plain");
  16148. });
  16149. auto port = svr.bind_to_any_port(HOST);
  16150. thread t = thread([&]() { svr.listen_after_bind(); });
  16151. auto se = detail::scope_exit([&] {
  16152. svr.stop();
  16153. t.join();
  16154. ASSERT_FALSE(svr.is_running());
  16155. });
  16156. svr.wait_until_ready();
  16157. // The client supplies the first field line; the trusted proxy appends the
  16158. // address it observed as a second one.
  16159. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16160. "Host: localhost\r\n"
  16161. "X-Forwarded-For: 1.2.3.4\r\n"
  16162. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16163. "Connection: close\r\n"
  16164. "\r\n";
  16165. std::string out;
  16166. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16167. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16168. EXPECT_EQ(observed_xff_count, 2U);
  16169. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16170. // The same chain spread over one field line per hop derives the same client
  16171. // address, i.e. the split and the comma-joined representations agree.
  16172. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16173. "Host: localhost\r\n"
  16174. "X-Forwarded-For: 1.2.3.4\r\n"
  16175. "X-Forwarded-For: 198.51.100.23\r\n"
  16176. "X-Forwarded-For: 192.0.2.45\r\n"
  16177. "Connection: close\r\n"
  16178. "\r\n";
  16179. out.clear();
  16180. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16181. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16182. EXPECT_EQ(observed_xff_count, 3U);
  16183. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16184. }
  16185. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16186. // crash the server (it used to call front() on an empty vector inside
  16187. // get_client_ip). The connection-level remote address must be retained instead.
  16188. static void run_malformed_xff_test(const std::string &xff_value) {
  16189. Server svr;
  16190. svr.set_trusted_proxies({"192.0.2.45"});
  16191. std::string observed_remote_addr;
  16192. svr.Get("/ip", [&](const Request &req, Response &res) {
  16193. observed_remote_addr = req.remote_addr;
  16194. res.set_content("ok", "text/plain");
  16195. });
  16196. int port = 0;
  16197. thread t = thread([&]() {
  16198. port = svr.bind_to_any_port(HOST);
  16199. svr.listen_after_bind();
  16200. });
  16201. auto se = detail::scope_exit([&] {
  16202. svr.stop();
  16203. t.join();
  16204. ASSERT_FALSE(svr.is_running());
  16205. });
  16206. svr.wait_until_ready();
  16207. Client cli(HOST, port);
  16208. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16210. EXPECT_EQ(StatusCode::OK_200, res->status);
  16211. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16212. observed_remote_addr == "127.0.0.1");
  16213. }
  16214. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16215. run_malformed_xff_test("");
  16216. }
  16217. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16218. run_malformed_xff_test(",");
  16219. }
  16220. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16221. run_malformed_xff_test(", , ,");
  16222. }
  16223. // The same rule applies to Accept: a request whose acceptable types are spread
  16224. // over several field lines must be negotiated against all of them.
  16225. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16226. // case-insensitive connection options. Comparing the whole field value against
  16227. // one option misses a client that sends several of them, and misses every
  16228. // casing but the one written in the comparison.
  16229. //
  16230. // Sends req, reads the response, then reuses the same socket for a second
  16231. // request to find out whether the server kept the connection.
  16232. static void probe_connection_reuse(int port, const std::string &req,
  16233. bool *announced_close, bool *reusable) {
  16234. auto error = Error::Success;
  16235. auto sock = detail::create_client_socket(
  16236. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16237. /*connection_timeout_sec=*/5, 0,
  16238. /*read_timeout_sec=*/1, 0,
  16239. /*write_timeout_sec=*/5, 0, std::string(), error);
  16240. ASSERT_NE(sock, INVALID_SOCKET);
  16241. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16242. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16243. "Host: localhost\r\n"
  16244. "Connection: close\r\n"
  16245. "\r\n";
  16246. std::string first_response;
  16247. std::string second_response;
  16248. detail::process_client_socket(
  16249. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16250. [&](Stream &strm) {
  16251. if (strm.write(req.data(), req.size()) !=
  16252. static_cast<ssize_t>(req.size())) {
  16253. return false;
  16254. }
  16255. char buf[512];
  16256. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16257. // Headers plus the two-byte body of the handler below
  16258. while (reader.getline()) {
  16259. first_response += reader.ptr();
  16260. if (first_response.find("ok") != std::string::npos) { break; }
  16261. }
  16262. if (strm.write(second.data(), second.size()) !=
  16263. static_cast<ssize_t>(second.size())) {
  16264. return true;
  16265. }
  16266. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16267. while (reader2.getline()) {
  16268. second_response += reader2.ptr();
  16269. if (second_response.find("ok") != std::string::npos) { break; }
  16270. }
  16271. return true;
  16272. });
  16273. *announced_close =
  16274. first_response.find("Connection: close") != std::string::npos;
  16275. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16276. }
  16277. class ConnectionTokenTest : public ::testing::Test {
  16278. protected:
  16279. void SetUp() override {
  16280. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16281. res.set_content("ok", "text/plain");
  16282. });
  16283. port_ = svr_.bind_to_any_port(HOST);
  16284. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16285. svr_.wait_until_ready();
  16286. }
  16287. void TearDown() override {
  16288. svr_.stop();
  16289. if (thread_.joinable()) { thread_.join(); }
  16290. }
  16291. Server svr_;
  16292. int port_ = 0;
  16293. thread thread_;
  16294. };
  16295. // "close" alongside another option still closes the connection, and the
  16296. // response says so rather than leaving the peer to discover it.
  16297. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16298. bool announced_close = false;
  16299. bool reusable = true;
  16300. probe_connection_reuse(port_,
  16301. "GET /keepalive HTTP/1.1\r\n"
  16302. "Host: localhost\r\n"
  16303. "Connection: keep-alive, close\r\n"
  16304. "\r\n",
  16305. &announced_close, &reusable);
  16306. EXPECT_TRUE(announced_close);
  16307. EXPECT_FALSE(reusable);
  16308. }
  16309. // "close" split over two field lines is the same list, so it is honored too.
  16310. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16311. bool announced_close = false;
  16312. bool reusable = true;
  16313. probe_connection_reuse(port_,
  16314. "GET /keepalive HTTP/1.1\r\n"
  16315. "Host: localhost\r\n"
  16316. "Connection: keep-alive\r\n"
  16317. "Connection: close\r\n"
  16318. "\r\n",
  16319. &announced_close, &reusable);
  16320. EXPECT_TRUE(announced_close);
  16321. EXPECT_FALSE(reusable);
  16322. }
  16323. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16324. // keep-alive in the spelling everyone actually sends keeps its connection.
  16325. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16326. bool announced_close = false;
  16327. bool reusable = false;
  16328. probe_connection_reuse(port_,
  16329. "GET /keepalive HTTP/1.0\r\n"
  16330. "Host: localhost\r\n"
  16331. "Connection: keep-alive\r\n"
  16332. "\r\n",
  16333. &announced_close, &reusable);
  16334. EXPECT_FALSE(announced_close);
  16335. EXPECT_TRUE(reusable);
  16336. }
  16337. // A token the value merely contains is not the token itself.
  16338. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16339. bool announced_close = false;
  16340. bool reusable = false;
  16341. probe_connection_reuse(port_,
  16342. "GET /keepalive HTTP/1.1\r\n"
  16343. "Host: localhost\r\n"
  16344. "Connection: notclose\r\n"
  16345. "\r\n",
  16346. &announced_close, &reusable);
  16347. EXPECT_FALSE(announced_close);
  16348. EXPECT_TRUE(reusable);
  16349. }
  16350. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16351. Server svr;
  16352. std::vector<std::string> observed_types;
  16353. svr.Get("/", [&](const Request &req, Response &res) {
  16354. observed_types = req.accept_content_types;
  16355. res.set_content("ok", "text/plain");
  16356. });
  16357. auto port = svr.bind_to_any_port(HOST);
  16358. thread t = thread([&]() { svr.listen_after_bind(); });
  16359. auto se = detail::scope_exit([&] {
  16360. svr.stop();
  16361. t.join();
  16362. ASSERT_FALSE(svr.is_running());
  16363. });
  16364. svr.wait_until_ready();
  16365. Client cli(HOST, port);
  16366. Headers headers;
  16367. headers.emplace("Accept", "text/plain;q=0.5");
  16368. headers.emplace("Accept", "application/json");
  16369. auto res = cli.Get("/", headers);
  16370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16371. EXPECT_EQ(StatusCode::OK_200, res->status);
  16372. // Sorted by q-value, so the second field line's type comes first
  16373. ASSERT_EQ(2U, observed_types.size());
  16374. EXPECT_EQ("application/json", observed_types[0]);
  16375. EXPECT_EQ("text/plain", observed_types[1]);
  16376. }
  16377. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16378. // empty field line must not contribute a bare comma to the combined value.
  16379. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16380. Server svr;
  16381. std::vector<std::string> observed_types;
  16382. svr.Get("/", [&](const Request &req, Response &res) {
  16383. observed_types = req.accept_content_types;
  16384. res.set_content("ok", "text/plain");
  16385. });
  16386. auto port = svr.bind_to_any_port(HOST);
  16387. thread t = thread([&]() { svr.listen_after_bind(); });
  16388. auto se = detail::scope_exit([&] {
  16389. svr.stop();
  16390. t.join();
  16391. ASSERT_FALSE(svr.is_running());
  16392. });
  16393. svr.wait_until_ready();
  16394. // Empty first field line, then a real one
  16395. std::string raw_req = "GET / HTTP/1.1\r\n"
  16396. "Host: localhost\r\n"
  16397. "Accept:\r\n"
  16398. "Accept: application/json\r\n"
  16399. "Connection: close\r\n"
  16400. "\r\n";
  16401. std::string out;
  16402. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16403. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16404. ASSERT_EQ(1U, observed_types.size());
  16405. EXPECT_EQ("application/json", observed_types[0]);
  16406. }
  16407. // The skip in get_combined_header_value() is what keeps an empty field line
  16408. // from contributing a bare comma. Only a trailing empty field line exercises
  16409. // it: a leading one is already covered by the "combined is still empty" check,
  16410. // and parse_accept_header() now ignores the empty element either way, so the
  16411. // request-level test above can no longer tell the two apart.
  16412. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16413. Headers headers;
  16414. headers.emplace("Accept", "text/html");
  16415. headers.emplace("Accept", "");
  16416. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16417. headers.clear();
  16418. headers.emplace("Accept", "");
  16419. headers.emplace("Accept", "application/json");
  16420. EXPECT_EQ("application/json",
  16421. detail::get_combined_header_value(headers, "Accept"));
  16422. }
  16423. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16424. // An encoding offered on a later Accept-Encoding field line is still offered.
  16425. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16426. Server svr;
  16427. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16428. res.set_content(std::string(1024, 'x'), "text/plain");
  16429. });
  16430. auto port = svr.bind_to_any_port(HOST);
  16431. thread t = thread([&]() { svr.listen_after_bind(); });
  16432. auto se = detail::scope_exit([&] {
  16433. svr.stop();
  16434. t.join();
  16435. ASSERT_FALSE(svr.is_running());
  16436. });
  16437. svr.wait_until_ready();
  16438. Client cli(HOST, port);
  16439. cli.set_decompress(false);
  16440. Headers headers;
  16441. headers.emplace("Accept-Encoding", "identity");
  16442. headers.emplace("Accept-Encoding", "gzip");
  16443. auto res = cli.Get("/", headers);
  16444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16445. EXPECT_EQ(StatusCode::OK_200, res->status);
  16446. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16447. }
  16448. #endif
  16449. #ifndef _WIN32
  16450. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16451. Server svr;
  16452. svr.Post("/post", [&](const Request &req, Response &res) {
  16453. res.set_content(req.body, "text/plain");
  16454. });
  16455. svr.Put("/put", [&](const Request &req, Response &res) {
  16456. res.set_content(req.body, "text/plain");
  16457. });
  16458. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16459. res.set_content(req.body, "text/plain");
  16460. });
  16461. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16462. res.set_content(req.body, "text/plain");
  16463. });
  16464. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16465. auto se = detail::scope_exit([&] {
  16466. svr.stop();
  16467. t.join();
  16468. ASSERT_FALSE(svr.is_running());
  16469. });
  16470. svr.wait_until_ready();
  16471. std::string resp;
  16472. // POST without Content-Length
  16473. ASSERT_TRUE(send_request(5,
  16474. "POST /post HTTP/1.1\r\n"
  16475. "Host: localhost\r\n"
  16476. "Connection: close\r\n"
  16477. "\r\n",
  16478. &resp));
  16479. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16480. // PUT without Content-Length
  16481. resp.clear();
  16482. ASSERT_TRUE(send_request(5,
  16483. "PUT /put HTTP/1.1\r\n"
  16484. "Host: localhost\r\n"
  16485. "Connection: close\r\n"
  16486. "\r\n",
  16487. &resp));
  16488. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16489. // PATCH without Content-Length
  16490. resp.clear();
  16491. ASSERT_TRUE(send_request(5,
  16492. "PATCH /patch HTTP/1.1\r\n"
  16493. "Host: localhost\r\n"
  16494. "Connection: close\r\n"
  16495. "\r\n",
  16496. &resp));
  16497. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16498. // DELETE without Content-Length
  16499. resp.clear();
  16500. ASSERT_TRUE(send_request(5,
  16501. "DELETE /delete HTTP/1.1\r\n"
  16502. "Host: localhost\r\n"
  16503. "Connection: close\r\n"
  16504. "\r\n",
  16505. &resp));
  16506. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16507. }
  16508. #endif
  16509. //==============================================================================
  16510. // open_stream() Tests
  16511. //==============================================================================
  16512. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16513. std::string result;
  16514. char buf[8192];
  16515. ssize_t n;
  16516. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16517. result.append(buf, static_cast<size_t>(n));
  16518. }
  16519. return result;
  16520. }
  16521. // Mock stream for unit tests
  16522. class MockStream : public Stream {
  16523. public:
  16524. std::string data;
  16525. size_t pos = 0;
  16526. ssize_t error_after = -1; // -1 = no error
  16527. explicit MockStream(const std::string &d, ssize_t err = -1)
  16528. : data(d), error_after(err) {}
  16529. bool is_readable() const override { return true; }
  16530. bool wait_readable() const override { return true; }
  16531. bool wait_writable() const override { return true; }
  16532. ssize_t read(char *ptr, size_t size) override {
  16533. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16534. if (pos >= data.size()) return 0;
  16535. size_t limit =
  16536. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16537. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16538. std::memcpy(ptr, data.data() + pos, to_read);
  16539. pos += to_read;
  16540. return static_cast<ssize_t>(to_read);
  16541. }
  16542. ssize_t write(const char *, size_t) override { return -1; }
  16543. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16544. ip = "127.0.0.1";
  16545. port = 0;
  16546. }
  16547. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16548. ip = "127.0.0.1";
  16549. port = 0;
  16550. }
  16551. socket_t socket() const override { return INVALID_SOCKET; }
  16552. time_t duration() const override { return 0; }
  16553. };
  16554. TEST(StreamHandleTest, Basic) {
  16555. ClientImpl::StreamHandle handle;
  16556. EXPECT_FALSE(handle.is_valid());
  16557. handle.response = detail::make_unique<Response>();
  16558. handle.error = Error::Connection;
  16559. EXPECT_FALSE(handle.is_valid());
  16560. handle.error = Error::Success;
  16561. EXPECT_TRUE(handle.is_valid());
  16562. }
  16563. TEST(BodyReaderTest, Basic) {
  16564. MockStream stream("Hello, World!");
  16565. detail::BodyReader reader;
  16566. reader.stream = &stream;
  16567. reader.content_length = 13;
  16568. char buf[32];
  16569. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16570. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16571. EXPECT_TRUE(reader.eof);
  16572. }
  16573. TEST(BodyReaderTest, NoStream) {
  16574. detail::BodyReader reader;
  16575. char buf[32];
  16576. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16577. EXPECT_EQ(Error::Connection, reader.last_error);
  16578. }
  16579. TEST(BodyReaderTest, Error) {
  16580. MockStream stream("Hello, World!", 5);
  16581. detail::BodyReader reader;
  16582. reader.stream = &stream;
  16583. reader.content_length = 13;
  16584. char buf[32];
  16585. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16586. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16587. EXPECT_EQ(Error::Read, reader.last_error);
  16588. }
  16589. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16590. // Mock-based StreamHandle tests relying on private internals are removed.
  16591. class OpenStreamTest : public ::testing::Test {
  16592. protected:
  16593. void SetUp() override {
  16594. svr_.Get("/hello", [](const Request &, Response &res) {
  16595. res.set_content("Hello World!", "text/plain");
  16596. });
  16597. svr_.Get("/large", [](const Request &, Response &res) {
  16598. res.set_content(std::string(10000, 'X'), "text/plain");
  16599. });
  16600. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16601. res.set_content("Hello World!", "image/jpeg");
  16602. res.set_header("Content-Encoding", "UTF-8");
  16603. });
  16604. svr_.Get("/chunked", [](const Request &, Response &res) {
  16605. res.set_chunked_content_provider("text/plain",
  16606. [](size_t offset, DataSink &sink) {
  16607. if (offset < 15) {
  16608. sink.write("chunk", 5);
  16609. return true;
  16610. }
  16611. sink.done();
  16612. return true;
  16613. });
  16614. });
  16615. svr_.Get("/compressible", [](const Request &, Response &res) {
  16616. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16617. DataSink &sink) {
  16618. if (offset < 100 * 1024) {
  16619. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16620. sink.write(chunk.data(), chunk.size());
  16621. return true;
  16622. }
  16623. sink.done();
  16624. return true;
  16625. });
  16626. });
  16627. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16628. [](const Request & /*req*/, Response &res) {
  16629. auto i = new int(0);
  16630. res.set_header("Trailer", "Content-Length, X-Allowed");
  16631. res.set_chunked_content_provider(
  16632. "text/plain",
  16633. [i](size_t /*offset*/, DataSink &sink) {
  16634. switch (*i) {
  16635. case 0: sink.os << "123"; break;
  16636. case 1: sink.os << "456"; break;
  16637. case 2: sink.os << "789"; break;
  16638. case 3: {
  16639. sink.done_with_trailer(
  16640. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16641. } break;
  16642. }
  16643. (*i)++;
  16644. return true;
  16645. },
  16646. [i](bool success) {
  16647. EXPECT_TRUE(success);
  16648. delete i;
  16649. });
  16650. });
  16651. // Echo headers endpoint for header-related tests
  16652. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16653. std::string body;
  16654. for (const auto &h : req.headers) {
  16655. body.append(h.first);
  16656. body.push_back(':');
  16657. body.append(h.second);
  16658. body.push_back('\n');
  16659. }
  16660. res.set_content(body, "text/plain");
  16661. });
  16662. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16663. std::string body;
  16664. for (const auto &h : req.headers) {
  16665. body.append(h.first);
  16666. body.push_back(':');
  16667. body.append(h.second);
  16668. body.push_back('\n');
  16669. }
  16670. res.set_content(body, "text/plain");
  16671. });
  16672. port_ = svr_.bind_to_any_port("127.0.0.1");
  16673. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16674. svr_.wait_until_ready();
  16675. }
  16676. void TearDown() override {
  16677. svr_.stop();
  16678. if (thread_.joinable()) thread_.join();
  16679. }
  16680. Server svr_;
  16681. std::thread thread_;
  16682. int port_ = 0;
  16683. };
  16684. TEST_F(OpenStreamTest, Basic) {
  16685. Client cli("127.0.0.1", port_);
  16686. auto handle = cli.open_stream("GET", "/hello");
  16687. EXPECT_TRUE(handle.is_valid());
  16688. EXPECT_EQ("Hello World!", read_all(handle));
  16689. }
  16690. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16691. Client cli("127.0.0.1", port_);
  16692. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16693. ASSERT_TRUE(handle.is_valid());
  16694. EXPECT_EQ("Hello World!", read_all(handle));
  16695. }
  16696. TEST_F(OpenStreamTest, SmallBuffer) {
  16697. Client cli("127.0.0.1", port_);
  16698. auto handle = cli.open_stream("GET", "/hello");
  16699. std::string result;
  16700. char buf[4];
  16701. ssize_t n;
  16702. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16703. result.append(buf, static_cast<size_t>(n));
  16704. EXPECT_EQ("Hello World!", result);
  16705. }
  16706. TEST_F(OpenStreamTest, DefaultHeaders) {
  16707. Client cli("127.0.0.1", port_);
  16708. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16709. {
  16710. auto handle = cli.open_stream("GET", "/echo-headers");
  16711. ASSERT_TRUE(handle.is_valid());
  16712. auto body = read_all(handle);
  16713. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16714. std::string::npos);
  16715. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16716. std::string::npos);
  16717. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16718. }
  16719. // open_stream POST with body and no explicit content_type should NOT add
  16720. // text/plain Content-Type (behavior differs from non-streaming path), but
  16721. // should include Content-Length
  16722. {
  16723. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16724. ASSERT_TRUE(handle.is_valid());
  16725. auto body = read_all(handle);
  16726. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16727. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16728. }
  16729. // open_stream POST with explicit Content-Type should preserve it
  16730. {
  16731. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16732. {{"Content-Type", "application/custom"}},
  16733. "{}", "application/custom");
  16734. ASSERT_TRUE(handle.is_valid());
  16735. auto body = read_all(handle);
  16736. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16737. }
  16738. // User-specified User-Agent must not be overwritten for stream API
  16739. {
  16740. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16741. {{"User-Agent", "MyAgent/1.2"}});
  16742. ASSERT_TRUE(handle.is_valid());
  16743. auto body = read_all(handle);
  16744. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16745. }
  16746. }
  16747. TEST_F(OpenStreamTest, Large) {
  16748. Client cli("127.0.0.1", port_);
  16749. auto handle = cli.open_stream("GET", "/large");
  16750. EXPECT_EQ(10000u, read_all(handle).size());
  16751. }
  16752. TEST_F(OpenStreamTest, ConnectionError) {
  16753. Client cli("127.0.0.1", 9999);
  16754. auto handle = cli.open_stream("GET", "/hello");
  16755. EXPECT_FALSE(handle.is_valid());
  16756. }
  16757. TEST_F(OpenStreamTest, Chunked) {
  16758. Client cli("127.0.0.1", port_);
  16759. auto handle = cli.open_stream("GET", "/chunked");
  16760. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16761. "Transfer-Encoding") == "chunked");
  16762. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16763. }
  16764. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  16765. Client cli("127.0.0.1", port_);
  16766. auto handle =
  16767. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  16768. ASSERT_TRUE(handle.is_valid());
  16769. // Consume body to allow trailers to be received/parsed
  16770. auto body = read_all(handle);
  16771. // Explicitly parse trailers (ensure trailers are available for assertion)
  16772. handle.parse_trailers_if_needed();
  16773. EXPECT_EQ(std::string("123456789"), body);
  16774. // The response should include a Trailer header declaring both names
  16775. ASSERT_TRUE(handle.response);
  16776. EXPECT_TRUE(handle.response->has_header("Trailer"));
  16777. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  16778. handle.response->get_header_value("Trailer"));
  16779. // Prohibited trailer must not be present
  16780. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  16781. // Allowed trailer should be present
  16782. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  16783. EXPECT_EQ(std::string("yes"),
  16784. handle.response->get_trailer_value("X-Allowed"));
  16785. // Verify trailers are NOT present as regular headers
  16786. EXPECT_EQ(std::string(""),
  16787. handle.response->get_header_value("Content-Length"));
  16788. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  16789. }
  16790. static std::thread serve_single_response(std::promise<int> &port_promise,
  16791. const std::string &response) {
  16792. return std::thread([&port_promise, response] {
  16793. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16794. default_socket_options(srv);
  16795. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16796. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  16797. sockaddr_in addr{};
  16798. addr.sin_family = AF_INET;
  16799. addr.sin_port = htons(0); // Let OS assign a free port
  16800. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16801. int opt = 1;
  16802. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  16803. #ifdef _WIN32
  16804. reinterpret_cast<const char *>(&opt),
  16805. #else
  16806. &opt,
  16807. #endif
  16808. sizeof(opt));
  16809. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  16810. ::listen(srv, 1) != 0) {
  16811. port_promise.set_value(-1);
  16812. detail::close_socket(srv);
  16813. return;
  16814. }
  16815. socklen_t addr_len = sizeof(addr);
  16816. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  16817. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  16818. sockaddr_in cli_addr{};
  16819. socklen_t cli_len = sizeof(cli_addr);
  16820. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16821. if (cli != INVALID_SOCKET) {
  16822. // Read the complete HTTP request (until the blank line that terminates
  16823. // headers) before sending the response. If the server closes the socket
  16824. // while the client's request data is still unread in the kernel receive
  16825. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  16826. // connection on both sides: it discards the client's receive buffer
  16827. // (which already holds our response) and causes any in-progress write on
  16828. // the client to fail with ECONNRESET. Reading all request data first
  16829. // ensures close() emits a graceful FIN.
  16830. {
  16831. char rbuf[256];
  16832. std::string req;
  16833. while (req.find("\r\n\r\n") == std::string::npos) {
  16834. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  16835. if (n <= 0) { break; }
  16836. req.append(rbuf, static_cast<size_t>(n));
  16837. }
  16838. }
  16839. ::send(cli,
  16840. #ifdef _WIN32
  16841. static_cast<const char *>(response.c_str()),
  16842. static_cast<int>(response.size()),
  16843. #else
  16844. response.c_str(), response.size(),
  16845. #endif
  16846. 0);
  16847. detail::close_socket(cli);
  16848. }
  16849. detail::close_socket(srv);
  16850. });
  16851. }
  16852. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  16853. #ifndef _WIN32
  16854. signal(SIGPIPE, SIG_IGN);
  16855. #endif
  16856. std::promise<int> port_promise;
  16857. auto port_future = port_promise.get_future();
  16858. auto server_thread =
  16859. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  16860. "Content-Type: text/plain\r\n"
  16861. "Content-Length: not-a-number\r\n"
  16862. "Connection: close\r\n"
  16863. "\r\n"
  16864. "hello");
  16865. auto port = port_future.get();
  16866. ASSERT_GT(port, 0);
  16867. Client cli("127.0.0.1", port);
  16868. auto handle = cli.open_stream("GET", "/");
  16869. EXPECT_FALSE(handle.is_valid());
  16870. server_thread.join();
  16871. }
  16872. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  16873. #ifndef _WIN32
  16874. signal(SIGPIPE, SIG_IGN);
  16875. #endif
  16876. std::promise<int> port_promise;
  16877. auto port_future = port_promise.get_future();
  16878. auto server_thread = serve_single_response(
  16879. port_promise, "HTTP/1.1 200 OK\r\n"
  16880. "Content-Type: text/plain\r\n"
  16881. "Content-Length: 99999999999999999999999999\r\n"
  16882. "Connection: close\r\n"
  16883. "\r\n"
  16884. "hello");
  16885. auto port = port_future.get();
  16886. ASSERT_GT(port, 0);
  16887. // Historically std::stoull would throw std::out_of_range here and crash
  16888. // the process, then parsing silently clamped to a bogus framing length and
  16889. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  16890. // so the stream fails to open, matching the not-a-number case above. The
  16891. // process still must NOT terminate.
  16892. Client cli("127.0.0.1", port);
  16893. auto handle = cli.open_stream("GET", "/");
  16894. EXPECT_FALSE(handle.is_valid());
  16895. server_thread.join();
  16896. }
  16897. // Serves `response` to the single request `fn` makes with a fresh client.
  16898. template <typename Fn>
  16899. static void with_single_response(const std::string &response, Fn fn) {
  16900. #ifndef _WIN32
  16901. signal(SIGPIPE, SIG_IGN);
  16902. #endif
  16903. std::promise<int> port_promise;
  16904. auto port_future = port_promise.get_future();
  16905. auto server_thread = serve_single_response(port_promise, response);
  16906. auto se = detail::scope_exit([&] { server_thread.join(); });
  16907. auto port = port_future.get();
  16908. ASSERT_GT(port, 0);
  16909. Client cli("127.0.0.1", port);
  16910. fn(cli);
  16911. }
  16912. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  16913. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  16914. // the chunked coding and drop Content-Length, so a front-end that trusts
  16915. // Content-Length would disagree about where the body ends (response
  16916. // smuggling). The client must reject such a response.
  16917. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16918. for (const char *te : {"chunked", "gzip, chunked"}) {
  16919. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  16920. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  16921. "\r\n" + "Connection: close\r\n" + "\r\n" +
  16922. "5\r\nhello\r\n0\r\n\r\n";
  16923. with_single_response(response, [&](Client &cli) {
  16924. auto res = cli.Get("/");
  16925. EXPECT_FALSE(static_cast<bool>(res)) << te;
  16926. EXPECT_EQ(Error::Read, res.error()) << te;
  16927. });
  16928. with_single_response(response, [&](Client &cli) {
  16929. auto handle = cli.open_stream("GET", "/");
  16930. EXPECT_FALSE(handle.is_valid()) << te;
  16931. EXPECT_EQ(Error::Read, handle.error) << te;
  16932. });
  16933. }
  16934. }
  16935. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  16936. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  16937. // closing the connection (unlike a request, which must be rejected).
  16938. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  16939. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  16940. "Transfer-Encoding: chunked\r\n"
  16941. "Connection: close\r\n"
  16942. "\r\n"
  16943. "5\r\nhello\r\n0\r\n\r\n",
  16944. "HTTP/1.1 200 OK\r\n"
  16945. "Transfer-Encoding: gzip\r\n"
  16946. "Connection: close\r\n"
  16947. "\r\n"
  16948. "hello"}) {
  16949. with_single_response(response, [&](Client &cli) {
  16950. auto res = cli.Get("/");
  16951. ASSERT_TRUE(static_cast<bool>(res)) << response;
  16952. EXPECT_EQ("hello", res->body);
  16953. });
  16954. with_single_response(response, [&](Client &cli) {
  16955. auto handle = cli.open_stream("GET", "/");
  16956. ASSERT_TRUE(handle.is_valid()) << response;
  16957. EXPECT_EQ("hello", read_all(handle));
  16958. });
  16959. }
  16960. }
  16961. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  16962. // framing headers describe nothing to read and must not be rejected.
  16963. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  16964. const std::string framing = "Content-Length: 5\r\n"
  16965. "Transfer-Encoding: chunked\r\n"
  16966. "Connection: close\r\n"
  16967. "\r\n";
  16968. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  16969. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  16970. });
  16971. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  16972. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  16973. });
  16974. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  16975. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  16976. with_single_response(response, [&](Client &cli) {
  16977. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  16978. });
  16979. with_single_response(response, [&](Client &cli) {
  16980. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  16981. });
  16982. }
  16983. }
  16984. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16985. TEST_F(OpenStreamTest, Gzip) {
  16986. Client cli("127.0.0.1", port_);
  16987. auto handle = cli.open_stream("GET", "/compressible", {},
  16988. {{"Accept-Encoding", "gzip"}});
  16989. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16990. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16991. }
  16992. #endif
  16993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16994. TEST_F(OpenStreamTest, Brotli) {
  16995. Client cli("127.0.0.1", port_);
  16996. auto handle =
  16997. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16998. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16999. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17000. }
  17001. #endif
  17002. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17003. TEST_F(OpenStreamTest, Zstd) {
  17004. Client cli("127.0.0.1", port_);
  17005. auto handle = cli.open_stream("GET", "/compressible", {},
  17006. {{"Accept-Encoding", "zstd"}});
  17007. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17008. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17009. }
  17010. #endif
  17011. #ifdef CPPHTTPLIB_SSL_ENABLED
  17012. class SSLOpenStreamTest : public ::testing::Test {
  17013. protected:
  17014. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17015. void SetUp() override {
  17016. svr_.Get("/hello", [](const Request &, Response &res) {
  17017. res.set_content("Hello SSL World!", "text/plain");
  17018. });
  17019. svr_.Get("/chunked", [](const Request &, Response &res) {
  17020. res.set_chunked_content_provider("text/plain",
  17021. [](size_t offset, DataSink &sink) {
  17022. if (offset < 15) {
  17023. sink.write("chunk", 5);
  17024. return true;
  17025. }
  17026. sink.done();
  17027. return true;
  17028. });
  17029. });
  17030. svr_.Post("/echo", [](const Request &req, Response &res) {
  17031. res.set_content(req.body, req.get_header_value("Content-Type"));
  17032. });
  17033. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17034. std::string body = req.body;
  17035. res.set_chunked_content_provider(
  17036. "text/plain", [body](size_t offset, DataSink &sink) {
  17037. if (offset < body.size()) {
  17038. sink.write(body.data() + offset, body.size() - offset);
  17039. }
  17040. sink.done();
  17041. return true;
  17042. });
  17043. });
  17044. port_ = svr_.bind_to_any_port("127.0.0.1");
  17045. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17046. svr_.wait_until_ready();
  17047. }
  17048. void TearDown() override {
  17049. svr_.stop();
  17050. if (thread_.joinable()) thread_.join();
  17051. }
  17052. SSLServer svr_;
  17053. std::thread thread_;
  17054. int port_ = 0;
  17055. };
  17056. TEST_F(SSLOpenStreamTest, Basic) {
  17057. SSLClient cli("127.0.0.1", port_);
  17058. cli.enable_server_certificate_verification(false);
  17059. auto handle = cli.open_stream("GET", "/hello");
  17060. ASSERT_TRUE(handle.is_valid());
  17061. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17062. }
  17063. TEST_F(SSLOpenStreamTest, Chunked) {
  17064. SSLClient cli("127.0.0.1", port_);
  17065. cli.enable_server_certificate_verification(false);
  17066. auto handle = cli.open_stream("GET", "/chunked");
  17067. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17068. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17069. "Transfer-Encoding") == "chunked");
  17070. auto body = read_all(handle);
  17071. EXPECT_EQ("chunkchunkchunk", body);
  17072. }
  17073. TEST_F(SSLOpenStreamTest, Post) {
  17074. SSLClient cli("127.0.0.1", port_);
  17075. cli.enable_server_certificate_verification(false);
  17076. auto handle =
  17077. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17078. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17079. EXPECT_EQ(200, handle.response->status);
  17080. auto body = read_all(handle);
  17081. EXPECT_EQ("Hello SSL POST", body);
  17082. }
  17083. TEST_F(SSLOpenStreamTest, PostChunked) {
  17084. SSLClient cli("127.0.0.1", port_);
  17085. cli.enable_server_certificate_verification(false);
  17086. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17087. "Chunked SSL Data", "text/plain");
  17088. ASSERT_TRUE(handle.is_valid());
  17089. EXPECT_EQ(200, handle.response->status);
  17090. auto body = read_all(handle);
  17091. EXPECT_EQ("Chunked SSL Data", body);
  17092. }
  17093. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17094. // Content-Length is terminated by the server closing the connection. When the
  17095. // SSL peer sends a close_notify after the body, the client must treat it as a
  17096. // clean EOF and return a successful response rather than an error.
  17097. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17099. ASSERT_TRUE(svr.is_valid());
  17100. svr.set_keep_alive_max_count(1);
  17101. const std::string expected_body = "Hello from connection-close response!";
  17102. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17103. res.set_content_provider("text/plain",
  17104. [&](size_t offset, DataSink &sink) -> bool {
  17105. if (offset < expected_body.size()) {
  17106. sink.write(expected_body.data() + offset,
  17107. expected_body.size() - offset);
  17108. }
  17109. sink.done();
  17110. return true;
  17111. });
  17112. });
  17113. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17114. auto se = detail::scope_exit([&] {
  17115. svr.stop();
  17116. listen_thread.join();
  17117. ASSERT_FALSE(svr.is_running());
  17118. });
  17119. svr.wait_until_ready();
  17120. SSLClient cli(HOST, PORT);
  17121. cli.enable_server_certificate_verification(false);
  17122. auto res = cli.Get("/no-content-length");
  17123. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17124. EXPECT_EQ(StatusCode::OK_200, res->status);
  17125. EXPECT_EQ(expected_body, res->body);
  17126. }
  17127. #endif // CPPHTTPLIB_SSL_ENABLED
  17128. //==============================================================================
  17129. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17130. // results for various scenarios.
  17131. //==============================================================================
  17132. TEST(ParityTest, GetVsOpenStream) {
  17133. Server svr;
  17134. const std::string path = "/parity";
  17135. const std::string content = "Parity test content: hello world";
  17136. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17137. res.set_content(content, "text/plain");
  17138. });
  17139. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17140. auto se = detail::scope_exit([&] {
  17141. svr.stop();
  17142. t.join();
  17143. ASSERT_FALSE(svr.is_running());
  17144. });
  17145. svr.wait_until_ready();
  17146. Client cli(HOST, PORT);
  17147. // Non-stream path
  17148. auto r1 = cli.Get(path);
  17149. ASSERT_TRUE(r1);
  17150. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17151. // Stream path
  17152. auto h = cli.open_stream("GET", path);
  17153. ASSERT_TRUE(h.is_valid());
  17154. EXPECT_EQ(r1->body, read_all(h));
  17155. }
  17156. // Helper to compress data with provided compressor type T
  17157. template <typename Compressor>
  17158. static std::string compress_payload_for_parity(const std::string &in) {
  17159. std::string out;
  17160. Compressor compressor;
  17161. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17162. [&](const char *data, size_t n) {
  17163. out.append(data, n);
  17164. return true;
  17165. });
  17166. EXPECT_TRUE(ok);
  17167. return out;
  17168. }
  17169. // Helper function for compression parity tests
  17170. template <typename Compressor>
  17171. static void test_compression_parity(const std::string &original,
  17172. const std::string &path,
  17173. const std::string &encoding) {
  17174. const std::string compressed =
  17175. compress_payload_for_parity<Compressor>(original);
  17176. Server svr;
  17177. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17178. res.set_content(compressed, "application/octet-stream");
  17179. res.set_header("Content-Encoding", encoding);
  17180. });
  17181. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17182. auto se = detail::scope_exit([&] {
  17183. svr.stop();
  17184. t.join();
  17185. ASSERT_FALSE(svr.is_running());
  17186. });
  17187. svr.wait_until_ready();
  17188. Client cli(HOST, PORT);
  17189. // Non-streaming
  17190. {
  17191. auto res = cli.Get(path);
  17192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17193. EXPECT_EQ(StatusCode::OK_200, res->status);
  17194. EXPECT_EQ(original, res->body);
  17195. }
  17196. // Streaming
  17197. {
  17198. auto h = cli.open_stream("GET", path);
  17199. ASSERT_TRUE(h.is_valid());
  17200. EXPECT_EQ(original, read_all(h));
  17201. }
  17202. }
  17203. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17204. TEST(ParityTest, Gzip) {
  17205. test_compression_parity<detail::gzip_compressor>(
  17206. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17207. }
  17208. #endif
  17209. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17210. TEST(ParityTest, Brotli) {
  17211. test_compression_parity<detail::brotli_compressor>(
  17212. "Hello, brotli parity test payload", "/parity-br", "br");
  17213. }
  17214. #endif
  17215. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17216. TEST(ParityTest, Zstd) {
  17217. test_compression_parity<detail::zstd_compressor>(
  17218. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17219. }
  17220. #endif
  17221. //==============================================================================
  17222. // New Stream API Tests
  17223. //==============================================================================
  17224. inline std::string read_body(httplib::stream::Result &result) {
  17225. std::string body;
  17226. while (result.next()) {
  17227. body.append(result.data(), result.size());
  17228. }
  17229. return body;
  17230. }
  17231. TEST(ClientConnectionTest, Basic) {
  17232. httplib::ClientConnection conn;
  17233. EXPECT_FALSE(conn.is_open());
  17234. conn.sock = 1;
  17235. EXPECT_TRUE(conn.is_open());
  17236. httplib::ClientConnection conn2(std::move(conn));
  17237. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17238. conn2.sock = INVALID_SOCKET;
  17239. }
  17240. // Unified test server for all stream::* tests
  17241. class StreamApiTest : public ::testing::Test {
  17242. protected:
  17243. void SetUp() override {
  17244. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17245. res.set_content("Hello World!", "text/plain");
  17246. });
  17247. svr_.Get("/echo-params",
  17248. [](const httplib::Request &req, httplib::Response &res) {
  17249. std::string r;
  17250. for (const auto &p : req.params) {
  17251. if (!r.empty()) r += "&";
  17252. r += p.first + "=" + p.second;
  17253. }
  17254. res.set_content(r, "text/plain");
  17255. });
  17256. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17257. res.set_content(req.body, req.get_header_value("Content-Type"));
  17258. });
  17259. svr_.Post("/echo-headers",
  17260. [](const httplib::Request &req, httplib::Response &res) {
  17261. std::string r;
  17262. for (const auto &h : req.headers)
  17263. r += h.first + ": " + h.second + "\n";
  17264. res.set_content(r, "text/plain");
  17265. });
  17266. svr_.Post("/echo-params",
  17267. [](const httplib::Request &req, httplib::Response &res) {
  17268. std::string r = "params:";
  17269. for (const auto &p : req.params)
  17270. r += p.first + "=" + p.second + ";";
  17271. res.set_content(r + " body:" + req.body, "text/plain");
  17272. });
  17273. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17274. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17275. });
  17276. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17277. res.set_content("PUT:" + req.body, "text/plain");
  17278. });
  17279. svr_.Patch("/echo",
  17280. [](const httplib::Request &req, httplib::Response &res) {
  17281. res.set_content("PATCH:" + req.body, "text/plain");
  17282. });
  17283. svr_.Delete(
  17284. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17285. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17286. "text/plain");
  17287. });
  17288. svr_.Get("/head-test",
  17289. [](const httplib::Request &, httplib::Response &res) {
  17290. res.set_content("body for HEAD", "text/plain");
  17291. });
  17292. svr_.Options("/options",
  17293. [](const httplib::Request &, httplib::Response &res) {
  17294. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17295. });
  17296. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17297. svr_.wait_until_ready();
  17298. }
  17299. void TearDown() override {
  17300. svr_.stop();
  17301. if (thread_.joinable()) thread_.join();
  17302. }
  17303. httplib::Server svr_;
  17304. std::thread thread_;
  17305. };
  17306. // stream::Get tests
  17307. TEST_F(StreamApiTest, GetBasic) {
  17308. httplib::Client cli(HOST, PORT);
  17309. auto result = httplib::stream::Get(cli, "/hello");
  17310. ASSERT_TRUE(result.is_valid());
  17311. EXPECT_EQ(200, result.status());
  17312. EXPECT_EQ("Hello World!", read_body(result));
  17313. }
  17314. TEST_F(StreamApiTest, GetWithParams) {
  17315. httplib::Client cli(HOST, PORT);
  17316. httplib::Params params{{"foo", "bar"}};
  17317. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17318. ASSERT_TRUE(result.is_valid());
  17319. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17320. }
  17321. TEST_F(StreamApiTest, GetConnectionError) {
  17322. httplib::Client cli(HOST, 9999);
  17323. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17324. }
  17325. TEST_F(StreamApiTest, Get404) {
  17326. httplib::Client cli(HOST, PORT);
  17327. auto result = httplib::stream::Get(cli, "/nonexistent");
  17328. EXPECT_TRUE(result.is_valid());
  17329. EXPECT_EQ(404, result.status());
  17330. }
  17331. // stream::Post tests
  17332. TEST_F(StreamApiTest, PostBasic) {
  17333. httplib::Client cli(HOST, PORT);
  17334. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17335. "application/json");
  17336. ASSERT_TRUE(result.is_valid());
  17337. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17338. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17339. }
  17340. TEST_F(StreamApiTest, PostWithHeaders) {
  17341. httplib::Client cli(HOST, PORT);
  17342. httplib::Headers headers{{"X-Custom", "value"}};
  17343. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17344. "text/plain");
  17345. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17346. }
  17347. TEST_F(StreamApiTest, PostWithParams) {
  17348. httplib::Client cli(HOST, PORT);
  17349. httplib::Params params{{"k", "v"}};
  17350. auto result =
  17351. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17352. auto body = read_body(result);
  17353. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17354. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17355. }
  17356. TEST_F(StreamApiTest, PostLarge) {
  17357. httplib::Client cli(HOST, PORT);
  17358. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17359. size_t total = 0;
  17360. while (result.next()) {
  17361. total += result.size();
  17362. }
  17363. EXPECT_EQ(100u * 1024u, total);
  17364. }
  17365. // stream::Put/Patch tests
  17366. TEST_F(StreamApiTest, PutAndPatch) {
  17367. httplib::Client cli(HOST, PORT);
  17368. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17369. EXPECT_EQ("PUT:test", read_body(put));
  17370. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17371. EXPECT_EQ("PATCH:test", read_body(patch));
  17372. }
  17373. // stream::Delete tests
  17374. TEST_F(StreamApiTest, Delete) {
  17375. httplib::Client cli(HOST, PORT);
  17376. auto del1 = httplib::stream::Delete(cli, "/resource");
  17377. EXPECT_EQ("Deleted", read_body(del1));
  17378. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17379. EXPECT_EQ("Deleted:data", read_body(del2));
  17380. }
  17381. // stream::Head/Options tests
  17382. TEST_F(StreamApiTest, HeadAndOptions) {
  17383. httplib::Client cli(HOST, PORT);
  17384. auto head = httplib::stream::Head(cli, "/head-test");
  17385. EXPECT_TRUE(head.is_valid());
  17386. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17387. auto opts = httplib::stream::Options(cli, "/options");
  17388. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17389. }
  17390. // SSL stream::* tests
  17391. #ifdef CPPHTTPLIB_SSL_ENABLED
  17392. class SSLStreamApiTest : public ::testing::Test {
  17393. protected:
  17394. void SetUp() override {
  17395. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17396. res.set_content("Hello SSL!", "text/plain");
  17397. });
  17398. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17399. res.set_content(req.body, "text/plain");
  17400. });
  17401. port_ = svr_.bind_to_any_port("127.0.0.1");
  17402. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17403. svr_.wait_until_ready();
  17404. }
  17405. void TearDown() override {
  17406. svr_.stop();
  17407. if (thread_.joinable()) thread_.join();
  17408. }
  17409. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17410. std::thread thread_;
  17411. int port_ = 0;
  17412. };
  17413. TEST_F(SSLStreamApiTest, GetAndPost) {
  17414. httplib::SSLClient cli("127.0.0.1", port_);
  17415. cli.enable_server_certificate_verification(false);
  17416. auto get = httplib::stream::Get(cli, "/hello");
  17417. EXPECT_EQ("Hello SSL!", read_body(get));
  17418. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17419. EXPECT_EQ("test", read_body(post));
  17420. }
  17421. #endif
  17422. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17423. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17424. // BodyReader
  17425. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17426. // Test that read timeout during streaming is detected
  17427. // Use a large content-length response where server delays mid-stream
  17428. Server svr;
  17429. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17430. // Send a large response with delay in the middle
  17431. res.set_content_provider(
  17432. 1000, // content_length
  17433. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17434. if (offset < 100) {
  17435. // Send first 100 bytes immediately
  17436. std::string data(100, 'A');
  17437. sink.write(data.c_str(), data.size());
  17438. return true;
  17439. }
  17440. // Then delay longer than client timeout
  17441. std::this_thread::sleep_for(std::chrono::seconds(3));
  17442. std::string data(900, 'B');
  17443. sink.write(data.c_str(), data.size());
  17444. return true;
  17445. });
  17446. });
  17447. auto port = 8091;
  17448. std::thread t([&]() { svr.listen("localhost", port); });
  17449. svr.wait_until_ready();
  17450. Client cli("localhost", port);
  17451. cli.set_read_timeout(1, 0); // 1 second timeout
  17452. auto handle = cli.open_stream("GET", "/slow-stream");
  17453. ASSERT_TRUE(handle.is_valid());
  17454. char buf[256];
  17455. ssize_t total = 0;
  17456. ssize_t n;
  17457. bool got_error = false;
  17458. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17459. total += n;
  17460. }
  17461. if (n < 0) {
  17462. got_error = true;
  17463. // Should be timeout or read error
  17464. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17465. handle.get_read_error() == Error::Read)
  17466. << "Actual error: " << to_string(handle.get_read_error());
  17467. }
  17468. // Either we got an error, or we got less data than expected
  17469. EXPECT_TRUE(got_error || total < 1000)
  17470. << "Expected timeout but got all " << total << " bytes";
  17471. svr.stop();
  17472. t.join();
  17473. }
  17474. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17475. // Test connection closed detection via BodyReader
  17476. Server svr;
  17477. std::atomic<bool> close_now{false};
  17478. svr.Get("/will-close", [&](const Request &, Response &res) {
  17479. res.set_content_provider(
  17480. 10000, // Large content_length that we won't fully send
  17481. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17482. if (offset < 100) {
  17483. std::string data(100, 'X');
  17484. sink.write(data.c_str(), data.size());
  17485. return true;
  17486. }
  17487. // Wait for signal then abort
  17488. while (!close_now) {
  17489. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17490. }
  17491. return false; // Abort - server will close connection
  17492. });
  17493. });
  17494. auto port = 8092;
  17495. std::thread t([&]() { svr.listen("localhost", port); });
  17496. svr.wait_until_ready();
  17497. Client cli("localhost", port);
  17498. auto handle = cli.open_stream("GET", "/will-close");
  17499. ASSERT_TRUE(handle.is_valid());
  17500. char buf[256];
  17501. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17502. EXPECT_GT(n, 0) << "First read should succeed";
  17503. // Signal server to close
  17504. close_now = true;
  17505. // Keep reading until error or EOF
  17506. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17507. // Keep reading
  17508. }
  17509. // Should get an error since content_length wasn't satisfied
  17510. if (n < 0) {
  17511. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17512. handle.get_read_error() == Error::Read)
  17513. << "Actual error: " << to_string(handle.get_read_error());
  17514. }
  17515. svr.stop();
  17516. t.join();
  17517. }
  17518. #ifdef CPPHTTPLIB_SSL_ENABLED
  17519. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17520. // Test that read timeout during SSL streaming is detected
  17521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17522. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17523. res.set_content_provider(
  17524. 1000, "text/plain",
  17525. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17526. if (offset < 100) {
  17527. std::string data(100, 'A');
  17528. sink.write(data.c_str(), data.size());
  17529. return true;
  17530. }
  17531. std::this_thread::sleep_for(std::chrono::seconds(3));
  17532. std::string data(900, 'B');
  17533. sink.write(data.c_str(), data.size());
  17534. return true;
  17535. });
  17536. });
  17537. auto port = 8093;
  17538. std::thread t([&]() { svr.listen("localhost", port); });
  17539. svr.wait_until_ready();
  17540. SSLClient cli("localhost", port);
  17541. cli.enable_server_certificate_verification(false);
  17542. cli.set_read_timeout(1, 0); // 1 second timeout
  17543. auto handle = cli.open_stream("GET", "/slow-stream");
  17544. ASSERT_TRUE(handle.is_valid());
  17545. char buf[256];
  17546. ssize_t total = 0;
  17547. ssize_t n;
  17548. bool got_error = false;
  17549. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17550. total += n;
  17551. }
  17552. if (n < 0) {
  17553. got_error = true;
  17554. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17555. handle.get_read_error() == Error::Read)
  17556. << "Actual error: " << to_string(handle.get_read_error());
  17557. }
  17558. EXPECT_TRUE(got_error || total < 1000)
  17559. << "Expected timeout but got all " << total << " bytes";
  17560. svr.stop();
  17561. t.join();
  17562. }
  17563. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17564. // Test SSL connection closed detection
  17565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17566. std::atomic<bool> close_now{false};
  17567. svr.Get("/will-close", [&](const Request &, Response &res) {
  17568. res.set_content_provider(
  17569. 10000, "text/plain",
  17570. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17571. if (offset < 100) {
  17572. std::string data(100, 'X');
  17573. sink.write(data.c_str(), data.size());
  17574. return true;
  17575. }
  17576. while (!close_now) {
  17577. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17578. }
  17579. return false;
  17580. });
  17581. });
  17582. auto port = 8094;
  17583. std::thread t([&]() { svr.listen("localhost", port); });
  17584. svr.wait_until_ready();
  17585. SSLClient cli("localhost", port);
  17586. cli.enable_server_certificate_verification(false);
  17587. auto handle = cli.open_stream("GET", "/will-close");
  17588. ASSERT_TRUE(handle.is_valid());
  17589. char buf[256];
  17590. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17591. EXPECT_GT(n, 0);
  17592. // Signal server to close
  17593. close_now = true;
  17594. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17595. // Keep reading
  17596. }
  17597. if (n < 0) {
  17598. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17599. handle.get_read_error() == Error::Read)
  17600. << "Actual error: " << to_string(handle.get_read_error());
  17601. }
  17602. svr.stop();
  17603. t.join();
  17604. }
  17605. #endif
  17606. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17607. using namespace httplib;
  17608. // Create a test file
  17609. const char *fname = "etag_testfile.txt";
  17610. const char *content = "etag-content";
  17611. {
  17612. std::ofstream ofs(fname);
  17613. ofs << content;
  17614. ASSERT_TRUE(ofs.good());
  17615. }
  17616. Server svr;
  17617. svr.set_mount_point("/static", ".");
  17618. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17619. svr.wait_until_ready();
  17620. Client cli(HOST, PORT);
  17621. // First request: should get 200 with ETag header
  17622. auto res1 = cli.Get("/static/etag_testfile.txt");
  17623. ASSERT_TRUE(res1);
  17624. ASSERT_EQ(200, res1->status);
  17625. ASSERT_TRUE(res1->has_header("ETag"));
  17626. std::string etag = res1->get_header_value("ETag");
  17627. EXPECT_FALSE(etag.empty());
  17628. // Verify ETag format: W/"hex-hex"
  17629. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17630. EXPECT_EQ('W', etag[0]);
  17631. EXPECT_EQ('/', etag[1]);
  17632. EXPECT_EQ('"', etag[2]);
  17633. EXPECT_EQ('"', etag.back());
  17634. // Exact match: expect 304 Not Modified
  17635. Headers h2 = {{"If-None-Match", etag}};
  17636. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17637. ASSERT_TRUE(res2);
  17638. EXPECT_EQ(304, res2->status);
  17639. // Wildcard match: expect 304 Not Modified
  17640. Headers h3 = {{"If-None-Match", "*"}};
  17641. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17642. ASSERT_TRUE(res3);
  17643. EXPECT_EQ(304, res3->status);
  17644. // Non-matching ETag: expect 200
  17645. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17646. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17647. ASSERT_TRUE(res4);
  17648. EXPECT_EQ(200, res4->status);
  17649. // Multiple ETags with one matching: expect 304
  17650. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17651. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17652. ASSERT_TRUE(res5);
  17653. EXPECT_EQ(304, res5->status);
  17654. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17655. // that equivalent to the single comma-separated list above, so the match on
  17656. // the second line must still be found.
  17657. Headers h6;
  17658. h6.emplace("If-None-Match", "W/\"other\"");
  17659. h6.emplace("If-None-Match", etag);
  17660. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17661. ASSERT_TRUE(res6);
  17662. EXPECT_EQ(304, res6->status);
  17663. svr.stop();
  17664. t.join();
  17665. std::remove(fname);
  17666. }
  17667. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17668. using namespace httplib;
  17669. Server svr;
  17670. svr.set_mount_point("/static", ".");
  17671. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17672. svr.wait_until_ready();
  17673. Client cli(HOST, PORT);
  17674. // Send If-None-Match: * to a non-existent file
  17675. Headers h = {{"If-None-Match", "*"}};
  17676. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17678. EXPECT_EQ(404, res->status);
  17679. svr.stop();
  17680. t.join();
  17681. }
  17682. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17683. using namespace httplib;
  17684. // Create a test file
  17685. const char *fname = "etag_boundary_testfile.txt";
  17686. const char *content = "boundary-test";
  17687. {
  17688. std::ofstream ofs(fname);
  17689. ofs << content;
  17690. ASSERT_TRUE(ofs.good());
  17691. }
  17692. Server svr;
  17693. svr.set_mount_point("/static", ".");
  17694. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17695. svr.wait_until_ready();
  17696. Client cli(HOST, PORT);
  17697. // Get the actual ETag
  17698. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17699. ASSERT_TRUE(res1);
  17700. ASSERT_EQ(200, res1->status);
  17701. ASSERT_TRUE(res1->has_header("ETag"));
  17702. std::string etag = res1->get_header_value("ETag");
  17703. // Test 1: Very long ETag value (longer than actual ETag)
  17704. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17705. Headers h1 = {{"If-None-Match", "W/"
  17706. "\"very-long-etag-value-that-is-much-longer-"
  17707. "than-the-actual-etag-value\""}};
  17708. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17709. ASSERT_TRUE(res2);
  17710. EXPECT_EQ(200, res2->status); // Should not match
  17711. // Test 2: Long string followed by wildcard
  17712. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17713. // string)
  17714. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17715. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17716. ASSERT_TRUE(res3);
  17717. EXPECT_EQ(304, res3->status); // Should match on "*"
  17718. // Test 3: Wildcard followed by long string
  17719. // Should match on "*" immediately and return 304
  17720. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17721. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17722. ASSERT_TRUE(res4);
  17723. EXPECT_EQ(304, res4->status); // Should match on "*"
  17724. // Test 4: Multiple long non-matching values
  17725. // Should NOT match and return 200 (test that all comparisons are safe)
  17726. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17727. "W/\"second-long-non-matching-value\", "
  17728. "W/\"third-long-non-matching-value\""}};
  17729. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17730. ASSERT_TRUE(res5);
  17731. EXPECT_EQ(200, res5->status); // Should not match
  17732. // Test 5: Single character that is not "*" (edge case)
  17733. Headers h5 = {{"If-None-Match", "X"}};
  17734. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17735. ASSERT_TRUE(res6);
  17736. EXPECT_EQ(200, res6->status); // Should not match
  17737. svr.stop();
  17738. t.join();
  17739. std::remove(fname);
  17740. }
  17741. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17742. using namespace httplib;
  17743. // Create a test file
  17744. const char *fname = "ims_testfile.txt";
  17745. const char *content = "if-modified-since-test";
  17746. {
  17747. std::ofstream ofs(fname);
  17748. ofs << content;
  17749. ASSERT_TRUE(ofs.good());
  17750. }
  17751. Server svr;
  17752. svr.set_mount_point("/static", ".");
  17753. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17754. svr.wait_until_ready();
  17755. Client cli(HOST, PORT);
  17756. // First request: should get 200 with Last-Modified header
  17757. auto res1 = cli.Get("/static/ims_testfile.txt");
  17758. ASSERT_TRUE(res1);
  17759. ASSERT_EQ(200, res1->status);
  17760. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17761. std::string last_modified = res1->get_header_value("Last-Modified");
  17762. EXPECT_FALSE(last_modified.empty());
  17763. // If-Modified-Since with same time: expect 304
  17764. Headers h2 = {{"If-Modified-Since", last_modified}};
  17765. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  17766. ASSERT_TRUE(res2);
  17767. EXPECT_EQ(304, res2->status);
  17768. // If-Modified-Since with future time: expect 304
  17769. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17770. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  17771. ASSERT_TRUE(res3);
  17772. EXPECT_EQ(304, res3->status);
  17773. // If-Modified-Since with past time: expect 200
  17774. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17775. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  17776. ASSERT_TRUE(res4);
  17777. EXPECT_EQ(200, res4->status);
  17778. // If-None-Match takes precedence over If-Modified-Since
  17779. // (send matching ETag with old If-Modified-Since -> should still be 304)
  17780. ASSERT_TRUE(res1->has_header("ETag"));
  17781. std::string etag = res1->get_header_value("ETag");
  17782. Headers h5 = {{"If-None-Match", etag},
  17783. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17784. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  17785. ASSERT_TRUE(res5);
  17786. EXPECT_EQ(304, res5->status);
  17787. svr.stop();
  17788. t.join();
  17789. std::remove(fname);
  17790. }
  17791. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  17792. using namespace httplib;
  17793. Server svr;
  17794. // Endpoint that returns compressible content
  17795. svr.Get("/compressible", [](const Request &, Response &res) {
  17796. // Return a large enough body to trigger compression
  17797. std::string body(1000, 'a');
  17798. res.set_content(body, "text/plain");
  17799. });
  17800. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17801. svr.wait_until_ready();
  17802. Client cli(HOST, PORT);
  17803. // Request with gzip support: should get Vary header when compressed
  17804. cli.set_compress(true);
  17805. auto res1 = cli.Get("/compressible");
  17806. ASSERT_TRUE(res1);
  17807. EXPECT_EQ(200, res1->status);
  17808. // If Content-Encoding is set, Vary should also be set
  17809. if (res1->has_header("Content-Encoding")) {
  17810. EXPECT_TRUE(res1->has_header("Vary"));
  17811. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  17812. }
  17813. // Request without Accept-Encoding header: should not have compression
  17814. Headers h_no_compress;
  17815. auto res2 = cli.Get("/compressible", h_no_compress);
  17816. ASSERT_TRUE(res2);
  17817. EXPECT_EQ(200, res2->status);
  17818. // Verify Vary header is present when compression is applied
  17819. // (the exact behavior depends on server configuration)
  17820. svr.stop();
  17821. t.join();
  17822. }
  17823. TEST(ETagTest, IfRangeWithETag) {
  17824. using namespace httplib;
  17825. // Create a test file with known content
  17826. const char *fname = "if_range_testfile.txt";
  17827. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  17828. {
  17829. std::ofstream ofs(fname);
  17830. ofs << content;
  17831. ASSERT_TRUE(ofs.good());
  17832. }
  17833. Server svr;
  17834. svr.set_mount_point("/static", ".");
  17835. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17836. svr.wait_until_ready();
  17837. Client cli(HOST, PORT);
  17838. // First request: get ETag
  17839. auto res1 = cli.Get("/static/if_range_testfile.txt");
  17840. ASSERT_TRUE(res1);
  17841. ASSERT_EQ(200, res1->status);
  17842. ASSERT_TRUE(res1->has_header("ETag"));
  17843. std::string etag = res1->get_header_value("ETag");
  17844. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  17845. // Since our server generates weak ETags (W/"..."), If-Range with our
  17846. // ETag should NOT result in partial content - it should return full content.
  17847. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  17848. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  17849. ASSERT_TRUE(res2);
  17850. // Weak ETag in If-Range -> full content (200), not partial (206)
  17851. EXPECT_EQ(200, res2->status);
  17852. EXPECT_EQ(content, res2->body);
  17853. EXPECT_FALSE(res2->has_header("Content-Range"));
  17854. // Range request with non-matching If-Range (ETag): should get 200 (full
  17855. // content)
  17856. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  17857. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  17858. ASSERT_TRUE(res3);
  17859. EXPECT_EQ(200, res3->status);
  17860. EXPECT_EQ(content, res3->body);
  17861. EXPECT_FALSE(res3->has_header("Content-Range"));
  17862. // Range request with strong ETag (hypothetical - our server doesn't generate
  17863. // strong ETags, but if client sends a strong ETag that doesn't match, it
  17864. // should return full content)
  17865. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  17866. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  17867. ASSERT_TRUE(res4);
  17868. EXPECT_EQ(200, res4->status);
  17869. EXPECT_EQ(content, res4->body);
  17870. EXPECT_FALSE(res4->has_header("Content-Range"));
  17871. svr.stop();
  17872. t.join();
  17873. std::remove(fname);
  17874. }
  17875. TEST(ETagTest, IfRangeWithDate) {
  17876. using namespace httplib;
  17877. // Create a test file
  17878. const char *fname = "if_range_date_testfile.txt";
  17879. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  17880. {
  17881. std::ofstream ofs(fname);
  17882. ofs << content;
  17883. ASSERT_TRUE(ofs.good());
  17884. }
  17885. Server svr;
  17886. svr.set_mount_point("/static", ".");
  17887. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17888. svr.wait_until_ready();
  17889. Client cli(HOST, PORT);
  17890. // First request: get Last-Modified
  17891. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  17892. ASSERT_TRUE(res1);
  17893. ASSERT_EQ(200, res1->status);
  17894. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17895. std::string last_modified = res1->get_header_value("Last-Modified");
  17896. // Range request with matching If-Range (date): should get 206
  17897. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  17898. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  17899. ASSERT_TRUE(res2);
  17900. EXPECT_EQ(206, res2->status);
  17901. EXPECT_EQ("FGHIJ", res2->body);
  17902. // Range request with old If-Range date: should get 200 (full content)
  17903. Headers h3 = {{"Range", "bytes=5-9"},
  17904. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17905. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  17906. ASSERT_TRUE(res3);
  17907. EXPECT_EQ(200, res3->status);
  17908. EXPECT_EQ(content, res3->body);
  17909. // Range request with future If-Range date: should get 206
  17910. Headers h4 = {{"Range", "bytes=0-4"},
  17911. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17912. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  17913. ASSERT_TRUE(res4);
  17914. EXPECT_EQ(206, res4->status);
  17915. EXPECT_EQ("ABCDE", res4->body);
  17916. svr.stop();
  17917. t.join();
  17918. std::remove(fname);
  17919. }
  17920. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  17921. using namespace httplib;
  17922. const char *fname = "etag_malformed.txt";
  17923. const char *content = "malformed-etag";
  17924. {
  17925. std::ofstream ofs(fname);
  17926. ofs << content;
  17927. ASSERT_TRUE(ofs.good());
  17928. }
  17929. Server svr;
  17930. svr.set_mount_point("/static", ".");
  17931. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17932. svr.wait_until_ready();
  17933. Client cli(HOST, PORT);
  17934. // baseline: should get 200 and an ETag
  17935. auto res1 = cli.Get("/static/etag_malformed.txt");
  17936. ASSERT_TRUE(res1);
  17937. ASSERT_EQ(200, res1->status);
  17938. ASSERT_TRUE(res1->has_header("ETag"));
  17939. // Malformed ETag value (missing quotes) should be treated as non-matching
  17940. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  17941. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  17942. ASSERT_TRUE(res_bad);
  17943. EXPECT_EQ(200, res_bad->status);
  17944. // Whitespace-only header value should be considered invalid / non-matching
  17945. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  17946. "Host: localhost\r\n"
  17947. "If-None-Match: \r\n"
  17948. "Connection: close\r\n"
  17949. "\r\n";
  17950. std::string out;
  17951. ASSERT_TRUE(send_request(5, raw_req, &out));
  17952. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17953. svr.stop();
  17954. t.join();
  17955. std::remove(fname);
  17956. }
  17957. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  17958. using namespace httplib;
  17959. const char *fname = "ims_invalid_format.txt";
  17960. const char *content = "ims-bad-format";
  17961. {
  17962. std::ofstream ofs(fname);
  17963. ofs << content;
  17964. ASSERT_TRUE(ofs.good());
  17965. }
  17966. Server svr;
  17967. svr.set_mount_point("/static", ".");
  17968. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17969. svr.wait_until_ready();
  17970. Client cli(HOST, PORT);
  17971. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  17972. ASSERT_TRUE(res1);
  17973. ASSERT_EQ(200, res1->status);
  17974. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17975. // If-Modified-Since with invalid format should not result in 304
  17976. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  17977. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  17978. ASSERT_TRUE(res_bad);
  17979. EXPECT_EQ(200, res_bad->status);
  17980. // If-Range with invalid date format should be treated as mismatch -> full
  17981. // content (200)
  17982. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  17983. {"If-Range", "invalid-date"}};
  17984. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  17985. ASSERT_TRUE(res_ifrange);
  17986. EXPECT_EQ(200, res_ifrange->status);
  17987. svr.stop();
  17988. t.join();
  17989. std::remove(fname);
  17990. }
  17991. TEST(ETagTest, IfRangeWithMalformedETag) {
  17992. using namespace httplib;
  17993. const char *fname = "ifrange_malformed.txt";
  17994. const std::string content = "0123456789";
  17995. {
  17996. std::ofstream ofs(fname);
  17997. ofs << content;
  17998. ASSERT_TRUE(ofs.good());
  17999. }
  18000. Server svr;
  18001. svr.set_mount_point("/static", ".");
  18002. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18003. svr.wait_until_ready();
  18004. Client cli(HOST, PORT);
  18005. // First request: get ETag
  18006. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18007. ASSERT_TRUE(res1);
  18008. ASSERT_EQ(200, res1->status);
  18009. ASSERT_TRUE(res1->has_header("ETag"));
  18010. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18011. // full content (200)
  18012. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18013. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18014. ASSERT_TRUE(res2);
  18015. EXPECT_EQ(200, res2->status);
  18016. EXPECT_EQ(content, res2->body);
  18017. svr.stop();
  18018. t.join();
  18019. std::remove(fname);
  18020. }
  18021. TEST(ETagTest, ExtremeLargeDateValues) {
  18022. using namespace httplib;
  18023. const char *fname = "ims_extreme_date.txt";
  18024. const char *content = "ims-extreme-date";
  18025. {
  18026. std::ofstream ofs(fname);
  18027. ofs << content;
  18028. ASSERT_TRUE(ofs.good());
  18029. }
  18030. Server svr;
  18031. svr.set_mount_point("/static", ".");
  18032. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18033. svr.wait_until_ready();
  18034. Client cli(HOST, PORT);
  18035. auto res1 = cli.Get(std::string("/static/") + fname);
  18036. ASSERT_TRUE(res1);
  18037. ASSERT_EQ(200, res1->status);
  18038. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18039. // Extremely large year that may overflow date parsing routines.
  18040. Headers h_large_date = {
  18041. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18042. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18043. ASSERT_TRUE(res_bad);
  18044. // Expect server to treat this as invalid/mismatch and return full content
  18045. EXPECT_EQ(200, res_bad->status);
  18046. // If-Range with extremely large date should be treated as mismatch -> full
  18047. // content (200)
  18048. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18049. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18050. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18051. ASSERT_TRUE(res_ifrange);
  18052. EXPECT_EQ(200, res_ifrange->status);
  18053. svr.stop();
  18054. t.join();
  18055. std::remove(fname);
  18056. }
  18057. TEST(ETagTest, NegativeFileModificationTime) {
  18058. using namespace httplib;
  18059. const char *fname = "ims_negative_mtime.txt";
  18060. const std::string content = "negative-mtime";
  18061. {
  18062. std::ofstream ofs(fname);
  18063. ofs << content;
  18064. ASSERT_TRUE(ofs.good());
  18065. }
  18066. // Try to set file mtime to a negative value. This may fail on some
  18067. // platforms/filesystems; if it fails, the test will still verify server
  18068. // behaves safely by performing a regular conditional request.
  18069. #if defined(__APPLE__) || defined(__linux__)
  18070. bool set_negative = false;
  18071. do {
  18072. struct timeval times[2];
  18073. // access time: now
  18074. times[0].tv_sec = time(nullptr);
  18075. times[0].tv_usec = 0;
  18076. // modification time: negative (e.g., -1)
  18077. times[1].tv_sec = -1;
  18078. times[1].tv_usec = 0;
  18079. if (utimes(fname, times) == 0) { set_negative = true; }
  18080. } while (0);
  18081. #else
  18082. bool set_negative = false;
  18083. #endif
  18084. Server svr;
  18085. svr.set_mount_point("/static", ".");
  18086. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18087. svr.wait_until_ready();
  18088. Client cli(HOST, PORT);
  18089. auto res1 = cli.Get(std::string("/static/") + fname);
  18090. ASSERT_TRUE(res1);
  18091. ASSERT_EQ(200, res1->status);
  18092. bool has_last_modified = res1->has_header("Last-Modified");
  18093. std::string last_modified;
  18094. if (has_last_modified) {
  18095. last_modified = res1->get_header_value("Last-Modified");
  18096. }
  18097. if (set_negative) {
  18098. // If we successfully set a negative mtime, ensure server returns a
  18099. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18100. // with an old date and ensure server handles it without crash.
  18101. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18102. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18103. ASSERT_TRUE(res2);
  18104. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18105. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18106. } else {
  18107. // Could not set negative mtime on this platform; fall back to verifying
  18108. // that normal invalid/malformed dates are treated safely (non-304).
  18109. Headers h_bad_date = {
  18110. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18111. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18112. ASSERT_TRUE(res_bad);
  18113. EXPECT_EQ(200, res_bad->status);
  18114. }
  18115. svr.stop();
  18116. t.join();
  18117. std::remove(fname);
  18118. }
  18119. //==============================================================================
  18120. // SSE Parsing Tests
  18121. //==============================================================================
  18122. class SSEParsingTest : public ::testing::Test {
  18123. protected:
  18124. // Test helper that mimics SSE parsing behavior
  18125. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18126. int &retry_ms) {
  18127. // Blank line signals end of event
  18128. if (line.empty() || line == "\r") { return true; }
  18129. // Lines starting with ':' are comments (ignored)
  18130. if (!line.empty() && line[0] == ':') { return false; }
  18131. // Find the colon separator
  18132. auto colon_pos = line.find(':');
  18133. if (colon_pos == std::string::npos) {
  18134. // Line with no colon is treated as field name with empty value
  18135. return false;
  18136. }
  18137. std::string field = line.substr(0, colon_pos);
  18138. std::string value;
  18139. // Value starts after colon, skip optional single space
  18140. if (colon_pos + 1 < line.size()) {
  18141. size_t value_start = colon_pos + 1;
  18142. if (line[value_start] == ' ') { value_start++; }
  18143. value = line.substr(value_start);
  18144. // Remove trailing \r if present
  18145. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18146. }
  18147. // Handle known fields
  18148. if (field == "event") {
  18149. msg.event = value;
  18150. } else if (field == "data") {
  18151. // Multiple data lines are concatenated with newlines
  18152. if (!msg.data.empty()) { msg.data += "\n"; }
  18153. msg.data += value;
  18154. } else if (field == "id") {
  18155. // Empty id is valid (clears the last event ID)
  18156. msg.id = value;
  18157. } else if (field == "retry") {
  18158. // Parse retry interval in milliseconds
  18159. {
  18160. int v = 0;
  18161. auto res =
  18162. detail::from_chars(value.data(), value.data() + value.size(), v);
  18163. if (res.ec == std::errc{}) { retry_ms = v; }
  18164. }
  18165. }
  18166. // Unknown fields are ignored per SSE spec
  18167. return false;
  18168. }
  18169. };
  18170. // Test: Single-line data
  18171. TEST_F(SSEParsingTest, SingleLineData) {
  18172. sse::SSEMessage msg;
  18173. int retry_ms = 3000;
  18174. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18175. EXPECT_EQ(msg.data, "hello");
  18176. EXPECT_EQ(msg.event, "message");
  18177. // Blank line ends event
  18178. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18179. }
  18180. // Test: Multi-line data
  18181. TEST_F(SSEParsingTest, MultiLineData) {
  18182. sse::SSEMessage msg;
  18183. int retry_ms = 3000;
  18184. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18185. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18186. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18187. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18188. }
  18189. // Test: Custom event types
  18190. TEST_F(SSEParsingTest, CustomEventType) {
  18191. sse::SSEMessage msg;
  18192. int retry_ms = 3000;
  18193. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18194. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18195. EXPECT_EQ(msg.event, "update");
  18196. EXPECT_EQ(msg.data, "payload");
  18197. }
  18198. // Test: Event ID handling
  18199. TEST_F(SSEParsingTest, EventIdHandling) {
  18200. sse::SSEMessage msg;
  18201. int retry_ms = 3000;
  18202. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18203. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18204. EXPECT_EQ(msg.id, "12345");
  18205. }
  18206. // Test: Empty event ID (clears last event ID)
  18207. TEST_F(SSEParsingTest, EmptyEventId) {
  18208. sse::SSEMessage msg;
  18209. msg.id = "previous";
  18210. int retry_ms = 3000;
  18211. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18212. EXPECT_EQ(msg.id, "");
  18213. }
  18214. // Test: Retry field parsing
  18215. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18216. sse::SSEMessage msg;
  18217. int retry_ms = 3000;
  18218. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18219. EXPECT_EQ(retry_ms, 5000);
  18220. }
  18221. // Test: Invalid retry value
  18222. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18223. sse::SSEMessage msg;
  18224. int retry_ms = 3000;
  18225. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18226. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18227. }
  18228. // Test: Comments (lines starting with :)
  18229. TEST_F(SSEParsingTest, CommentsIgnored) {
  18230. sse::SSEMessage msg;
  18231. int retry_ms = 3000;
  18232. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18233. EXPECT_EQ(msg.data, "");
  18234. EXPECT_EQ(msg.event, "message");
  18235. }
  18236. // Test: Colon in value
  18237. TEST_F(SSEParsingTest, ColonInValue) {
  18238. sse::SSEMessage msg;
  18239. int retry_ms = 3000;
  18240. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18241. EXPECT_EQ(msg.data, "hello:world:test");
  18242. }
  18243. // Test: Line with no colon (field name only)
  18244. TEST_F(SSEParsingTest, FieldNameOnly) {
  18245. sse::SSEMessage msg;
  18246. int retry_ms = 3000;
  18247. // According to SSE spec, this is treated as field name with empty value
  18248. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18249. // Since we don't recognize "data" without colon, data should be empty
  18250. EXPECT_EQ(msg.data, "");
  18251. }
  18252. // Test: Trailing \r handling
  18253. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18254. sse::SSEMessage msg;
  18255. int retry_ms = 3000;
  18256. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18257. EXPECT_EQ(msg.data, "hello");
  18258. }
  18259. // Test: Unknown fields ignored
  18260. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18261. sse::SSEMessage msg;
  18262. int retry_ms = 3000;
  18263. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18264. EXPECT_EQ(msg.data, "");
  18265. EXPECT_EQ(msg.event, "message");
  18266. }
  18267. // Test: Space after colon is optional
  18268. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18269. sse::SSEMessage msg1, msg2;
  18270. int retry_ms = 3000;
  18271. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18272. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18273. EXPECT_EQ(msg1.data, "hello");
  18274. EXPECT_EQ(msg2.data, "hello");
  18275. }
  18276. // Test: SSEMessage clear
  18277. TEST_F(SSEParsingTest, MessageClear) {
  18278. sse::SSEMessage msg;
  18279. msg.event = "custom";
  18280. msg.data = "some data";
  18281. msg.id = "123";
  18282. msg.clear();
  18283. EXPECT_EQ(msg.event, "message");
  18284. EXPECT_EQ(msg.data, "");
  18285. EXPECT_EQ(msg.id, "");
  18286. }
  18287. // Test: Complete event parsing
  18288. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18289. sse::SSEMessage msg;
  18290. int retry_ms = 3000;
  18291. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18292. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18293. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18294. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18295. // Blank line ends event
  18296. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18297. EXPECT_EQ(msg.event, "notification");
  18298. EXPECT_EQ(msg.id, "evt-42");
  18299. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18300. EXPECT_EQ(retry_ms, 1000);
  18301. }
  18302. //==============================================================================
  18303. // Integration Tests with Server
  18304. //==============================================================================
  18305. class SSEIntegrationTest : public ::testing::Test {
  18306. protected:
  18307. void SetUp() override {
  18308. stop_server_.store(false);
  18309. events_.clear();
  18310. server_ = httplib::detail::make_unique<Server>();
  18311. setup_server();
  18312. start_server();
  18313. }
  18314. void TearDown() override {
  18315. stop_server_.store(true);
  18316. event_cv_.notify_all();
  18317. server_->stop();
  18318. if (server_thread_.joinable()) { server_thread_.join(); }
  18319. }
  18320. void setup_server() {
  18321. // Simple SSE endpoint
  18322. server_->Get("/events", [this](const Request &req, Response &res) {
  18323. auto last_id = req.get_header_value("Last-Event-ID");
  18324. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18325. res.set_chunked_content_provider(
  18326. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18327. std::unique_lock<std::mutex> lock(event_mutex_);
  18328. if (event_cv_.wait_for(
  18329. lock, std::chrono::milliseconds(200), [this] {
  18330. return !events_.empty() || stop_server_.load();
  18331. })) {
  18332. if (stop_server_.load()) { return false; }
  18333. if (!events_.empty()) {
  18334. std::string event = events_.front();
  18335. events_.erase(events_.begin());
  18336. sink.write(event.data(), event.size());
  18337. return true;
  18338. }
  18339. }
  18340. return !stop_server_.load();
  18341. });
  18342. });
  18343. // Endpoint that returns error
  18344. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18345. res.status = 500;
  18346. res.set_content("Internal Server Error", "text/plain");
  18347. });
  18348. // Endpoint for custom event types
  18349. server_->Get("/custom-events", [](const Request &, Response &res) {
  18350. res.set_chunked_content_provider(
  18351. "text/event-stream", [](size_t offset, DataSink &sink) {
  18352. if (offset == 0) {
  18353. std::string event = "event: update\ndata: updated\n\n"
  18354. "event: delete\ndata: deleted\n\n";
  18355. sink.write(event.data(), event.size());
  18356. }
  18357. return false; // End stream after sending
  18358. });
  18359. });
  18360. }
  18361. void start_server() {
  18362. port_ = server_->bind_to_any_port(HOST);
  18363. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18364. // Wait for server to start
  18365. while (!server_->is_running()) {
  18366. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18367. }
  18368. }
  18369. int get_port() const { return port_; }
  18370. void send_event(const std::string &event) {
  18371. std::lock_guard<std::mutex> lock(event_mutex_);
  18372. events_.push_back(event);
  18373. event_cv_.notify_all();
  18374. }
  18375. std::unique_ptr<Server> server_;
  18376. std::thread server_thread_;
  18377. std::mutex event_mutex_;
  18378. std::condition_variable event_cv_;
  18379. std::vector<std::string> events_;
  18380. std::atomic<bool> stop_server_{false};
  18381. std::string last_received_event_id_;
  18382. int port_ = 0;
  18383. };
  18384. // Test: Successful connection and on_open callback
  18385. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18386. // Add a simple endpoint that sends one event and closes
  18387. server_->Get("/simple-event", [](const Request &, Response &res) {
  18388. res.set_chunked_content_provider(
  18389. "text/event-stream", [](size_t offset, DataSink &sink) {
  18390. if (offset == 0) {
  18391. std::string event = "data: hello\n\n";
  18392. sink.write(event.data(), event.size());
  18393. }
  18394. return false; // Close stream after sending
  18395. });
  18396. });
  18397. Client client("localhost", get_port());
  18398. sse::SSEClient sse(client, "/simple-event");
  18399. std::atomic<bool> open_called{false};
  18400. std::atomic<bool> message_received{false};
  18401. sse.on_open([&open_called]() { open_called.store(true); });
  18402. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18403. if (msg.data == "hello") { message_received.store(true); }
  18404. });
  18405. sse.set_reconnect_interval(100);
  18406. sse.set_max_reconnect_attempts(1);
  18407. // Start async
  18408. sse.start_async();
  18409. // Wait for message to be processed
  18410. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18411. sse.stop();
  18412. EXPECT_TRUE(open_called.load());
  18413. EXPECT_TRUE(message_received.load());
  18414. }
  18415. // Test: on_message callback
  18416. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18417. // Endpoint that sends multiple events then closes
  18418. server_->Get("/multi-event", [](const Request &, Response &res) {
  18419. res.set_chunked_content_provider(
  18420. "text/event-stream", [](size_t offset, DataSink &sink) {
  18421. if (offset == 0) {
  18422. std::string events = "data: message1\n\ndata: message2\n\n";
  18423. sink.write(events.data(), events.size());
  18424. }
  18425. return false;
  18426. });
  18427. });
  18428. Client client("localhost", get_port());
  18429. sse::SSEClient sse(client, "/multi-event");
  18430. std::vector<std::string> received_messages;
  18431. std::mutex messages_mutex;
  18432. sse.on_message([&](const sse::SSEMessage &msg) {
  18433. std::lock_guard<std::mutex> lock(messages_mutex);
  18434. received_messages.push_back(msg.data);
  18435. });
  18436. sse.set_reconnect_interval(100);
  18437. sse.set_max_reconnect_attempts(1);
  18438. sse.start_async();
  18439. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18440. sse.stop();
  18441. std::lock_guard<std::mutex> lock(messages_mutex);
  18442. EXPECT_GE(received_messages.size(), 2u);
  18443. if (received_messages.size() >= 2) {
  18444. EXPECT_EQ(received_messages[0], "message1");
  18445. EXPECT_EQ(received_messages[1], "message2");
  18446. }
  18447. }
  18448. // Test: on_event for specific types
  18449. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18450. Client client("localhost", get_port());
  18451. sse::SSEClient sse(client, "/custom-events");
  18452. std::atomic<bool> update_received{false};
  18453. std::atomic<bool> delete_received{false};
  18454. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18455. if (msg.data == "updated") { update_received.store(true); }
  18456. });
  18457. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18458. if (msg.data == "deleted") { delete_received.store(true); }
  18459. });
  18460. sse.set_max_reconnect_attempts(1);
  18461. sse.start_async();
  18462. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18463. sse.stop();
  18464. EXPECT_TRUE(update_received.load());
  18465. EXPECT_TRUE(delete_received.load());
  18466. }
  18467. // Test: on_error callback on connection failure
  18468. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18469. // Connect to a non-existent port
  18470. Client client("localhost", 59999);
  18471. sse::SSEClient sse(client, "/events");
  18472. std::atomic<bool> error_called{false};
  18473. Error received_error = Error::Success;
  18474. sse.on_error([&](Error err) {
  18475. error_called.store(true);
  18476. received_error = err;
  18477. });
  18478. sse.set_reconnect_interval(50);
  18479. sse.set_max_reconnect_attempts(1);
  18480. sse.start_async();
  18481. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18482. sse.stop();
  18483. EXPECT_TRUE(error_called.load());
  18484. EXPECT_NE(received_error, Error::Success);
  18485. }
  18486. // Test: Last-Event-ID header sent on reconnect
  18487. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18488. // Endpoint that sends event with ID
  18489. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18490. res.set_chunked_content_provider(
  18491. "text/event-stream", [](size_t offset, DataSink &sink) {
  18492. if (offset == 0) {
  18493. std::string event = "id: evt-123\ndata: test\n\n";
  18494. sink.write(event.data(), event.size());
  18495. }
  18496. return false;
  18497. });
  18498. });
  18499. Client client("localhost", get_port());
  18500. sse::SSEClient sse(client, "/event-with-id");
  18501. std::atomic<bool> id_received{false};
  18502. sse.on_message([&](const sse::SSEMessage &msg) {
  18503. if (!msg.id.empty()) { id_received.store(true); }
  18504. });
  18505. sse.set_reconnect_interval(100);
  18506. sse.set_max_reconnect_attempts(1);
  18507. sse.start_async();
  18508. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18509. sse.stop();
  18510. EXPECT_TRUE(id_received.load());
  18511. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18512. }
  18513. // Test: Manual stop
  18514. TEST_F(SSEIntegrationTest, ManualStop) {
  18515. // Endpoint that sends one event and stays open briefly
  18516. std::atomic<bool> handler_running{true};
  18517. server_->Get("/stay-open", [&handler_running](const Request &,
  18518. Response &res) {
  18519. res.set_chunked_content_provider(
  18520. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18521. if (offset == 0) {
  18522. std::string event = "data: connected\n\n";
  18523. sink.write(event.data(), event.size());
  18524. }
  18525. // Keep connection open while handler_running is true
  18526. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18527. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18528. }
  18529. return false;
  18530. });
  18531. });
  18532. Client client("localhost", get_port());
  18533. sse::SSEClient sse(client, "/stay-open");
  18534. std::atomic<bool> connected{false};
  18535. sse.on_open([&connected]() { connected.store(true); });
  18536. sse.set_reconnect_interval(100);
  18537. sse.set_max_reconnect_attempts(1);
  18538. sse.start_async();
  18539. // Wait for connection to establish
  18540. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18541. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18542. }
  18543. EXPECT_TRUE(connected.load());
  18544. EXPECT_TRUE(sse.is_connected());
  18545. // Signal handler to stop
  18546. handler_running.store(false);
  18547. // Stop SSE client
  18548. sse.stop();
  18549. EXPECT_FALSE(sse.is_connected());
  18550. }
  18551. // Test: SSEClient with custom headers
  18552. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18553. // Setup a server endpoint that checks for custom header
  18554. std::atomic<bool> header_received{false};
  18555. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18556. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18557. header_received.store(true);
  18558. }
  18559. res.set_chunked_content_provider("text/event-stream",
  18560. [](size_t, DataSink &) { return false; });
  18561. });
  18562. Client client("localhost", get_port());
  18563. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18564. sse::SSEClient sse(client, "/header-check", headers);
  18565. sse.set_max_reconnect_attempts(1);
  18566. sse.start_async();
  18567. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18568. sse.stop();
  18569. EXPECT_TRUE(header_received.load());
  18570. }
  18571. // Test: Reconnect interval configuration
  18572. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18573. Client client("localhost", get_port());
  18574. sse::SSEClient sse(client, "/events");
  18575. auto &result = sse.set_reconnect_interval(500);
  18576. // Builder pattern should return reference to self
  18577. EXPECT_EQ(&result, &sse);
  18578. }
  18579. // Test: Max reconnect attempts
  18580. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18581. // Connect to non-existent port to force reconnects
  18582. Client client("localhost", 59998);
  18583. sse::SSEClient sse(client, "/events");
  18584. std::atomic<int> error_count{0};
  18585. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18586. sse.set_reconnect_interval(50);
  18587. sse.set_max_reconnect_attempts(2);
  18588. auto start = std::chrono::steady_clock::now();
  18589. sse.start(); // Blocking call
  18590. auto end = std::chrono::steady_clock::now();
  18591. // Should have stopped after 2 failed attempts
  18592. EXPECT_GE(error_count.load(), 2);
  18593. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18594. auto duration =
  18595. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18596. #ifdef _WIN32
  18597. // Windows is much slower for socket connection failures
  18598. EXPECT_LT(duration.count(), 7000);
  18599. #else
  18600. EXPECT_LT(duration.count(), 1000);
  18601. #endif
  18602. }
  18603. // Test: Multi-line data in integration
  18604. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18605. // Endpoint with multi-line data
  18606. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18607. res.set_chunked_content_provider(
  18608. "text/event-stream", [](size_t offset, DataSink &sink) {
  18609. if (offset == 0) {
  18610. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18611. sink.write(event.data(), event.size());
  18612. }
  18613. return false;
  18614. });
  18615. });
  18616. Client client("localhost", get_port());
  18617. sse::SSEClient sse(client, "/multiline-data");
  18618. std::string received_data;
  18619. std::mutex data_mutex;
  18620. sse.on_message([&](const sse::SSEMessage &msg) {
  18621. std::lock_guard<std::mutex> lock(data_mutex);
  18622. received_data = msg.data;
  18623. });
  18624. sse.set_reconnect_interval(100);
  18625. sse.set_max_reconnect_attempts(1);
  18626. sse.start_async();
  18627. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18628. sse.stop();
  18629. std::lock_guard<std::mutex> lock(data_mutex);
  18630. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18631. }
  18632. // Test: Auto-reconnect after server disconnection
  18633. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18634. std::atomic<int> connection_count{0};
  18635. std::atomic<int> message_count{0};
  18636. // Endpoint that sends one event and closes, forcing reconnect
  18637. server_->Get("/reconnect-test",
  18638. [&connection_count](const Request &, Response &res) {
  18639. connection_count.fetch_add(1);
  18640. res.set_chunked_content_provider(
  18641. "text/event-stream", [](size_t offset, DataSink &sink) {
  18642. if (offset == 0) {
  18643. std::string event = "data: hello\n\n";
  18644. sink.write(event.data(), event.size());
  18645. }
  18646. return false; // Close connection after sending
  18647. });
  18648. });
  18649. Client client("localhost", get_port());
  18650. sse::SSEClient sse(client, "/reconnect-test");
  18651. sse.on_message([&message_count](const sse::SSEMessage &) {
  18652. message_count.fetch_add(1);
  18653. });
  18654. sse.set_reconnect_interval(100);
  18655. sse.set_max_reconnect_attempts(3);
  18656. sse.start_async();
  18657. // Wait long enough for multiple reconnects
  18658. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18659. sse.stop();
  18660. // Should have connected multiple times (initial + reconnects)
  18661. EXPECT_GE(connection_count.load(), 2);
  18662. // Should have received messages from multiple connections
  18663. EXPECT_GE(message_count.load(), 2);
  18664. }
  18665. // Test: Last-Event-ID sent on reconnect
  18666. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18667. std::atomic<int> connection_count{0};
  18668. std::vector<std::string> received_last_event_ids;
  18669. std::mutex id_mutex;
  18670. // Endpoint that checks Last-Event-ID header and sends event with ID
  18671. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18672. int conn = connection_count.fetch_add(1);
  18673. // Capture the Last-Event-ID header from each connection
  18674. {
  18675. std::lock_guard<std::mutex> lock(id_mutex);
  18676. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18677. }
  18678. res.set_chunked_content_provider(
  18679. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18680. if (offset == 0) {
  18681. std::string event =
  18682. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18683. sink.write(event.data(), event.size());
  18684. }
  18685. return false;
  18686. });
  18687. });
  18688. Client client("localhost", get_port());
  18689. sse::SSEClient sse(client, "/reconnect-with-id");
  18690. sse.set_reconnect_interval(100);
  18691. sse.set_max_reconnect_attempts(3);
  18692. sse.start_async();
  18693. // Wait for at least 2 connections
  18694. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18695. sse.stop();
  18696. // Verify behavior
  18697. std::lock_guard<std::mutex> lock(id_mutex);
  18698. EXPECT_GE(received_last_event_ids.size(), 2u);
  18699. // First connection should have no Last-Event-ID
  18700. if (!received_last_event_ids.empty()) {
  18701. EXPECT_EQ(received_last_event_ids[0], "");
  18702. }
  18703. // Second connection should have Last-Event-ID from first connection
  18704. if (received_last_event_ids.size() >= 2) {
  18705. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18706. }
  18707. }
  18708. // Test: set_headers updates headers used on reconnect
  18709. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18710. std::vector<std::string> received_tokens;
  18711. std::mutex token_mutex;
  18712. // Endpoint that captures Authorization header
  18713. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18714. {
  18715. std::lock_guard<std::mutex> lock(token_mutex);
  18716. received_tokens.push_back(req.get_header_value("Authorization"));
  18717. }
  18718. res.set_chunked_content_provider(
  18719. "text/event-stream", [](size_t offset, DataSink &sink) {
  18720. if (offset == 0) {
  18721. std::string event = "data: hello\n\n";
  18722. sink.write(event.data(), event.size());
  18723. }
  18724. return false; // Close connection to trigger reconnect
  18725. });
  18726. });
  18727. Client client("localhost", get_port());
  18728. Headers headers = {{"Authorization", "Bearer old-token"}};
  18729. sse::SSEClient sse(client, "/auth-check", headers);
  18730. // Update headers on each successful connection
  18731. sse.on_open(
  18732. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18733. sse.set_reconnect_interval(100);
  18734. sse.set_max_reconnect_attempts(3);
  18735. sse.start_async();
  18736. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18737. sse.stop();
  18738. std::lock_guard<std::mutex> lock(token_mutex);
  18739. ASSERT_GE(received_tokens.size(), 2u);
  18740. // First connection uses original header
  18741. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18742. // Second connection uses updated header from set_headers
  18743. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18744. }
  18745. // Test: 401 allows reconnection (so on_error can refresh headers)
  18746. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18747. std::atomic<int> connection_count{0};
  18748. // Endpoint: returns 401 on first attempt, 200 on second
  18749. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18750. int conn = connection_count.fetch_add(1);
  18751. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18752. res.status = StatusCode::Unauthorized_401;
  18753. res.set_content("Unauthorized", "text/plain");
  18754. return;
  18755. }
  18756. res.set_chunked_content_provider(
  18757. "text/event-stream", [](size_t offset, DataSink &sink) {
  18758. if (offset == 0) {
  18759. std::string event = "data: authenticated\n\n";
  18760. sink.write(event.data(), event.size());
  18761. }
  18762. return false;
  18763. });
  18764. });
  18765. Client client("localhost", get_port());
  18766. Headers headers = {{"Authorization", "Bearer expired"}};
  18767. sse::SSEClient sse(client, "/auth-retry", headers);
  18768. std::atomic<bool> message_received{false};
  18769. // Refresh token on error
  18770. sse.on_error(
  18771. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  18772. sse.on_message([&](const sse::SSEMessage &msg) {
  18773. if (msg.data == "authenticated") { message_received.store(true); }
  18774. });
  18775. sse.set_reconnect_interval(100);
  18776. sse.set_max_reconnect_attempts(3);
  18777. sse.start_async();
  18778. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18779. sse.stop();
  18780. // Should have reconnected after 401 and succeeded with new token
  18781. EXPECT_GE(connection_count.load(), 2);
  18782. EXPECT_TRUE(message_received.load());
  18783. }
  18784. TEST(Issue2318Test, EmptyHostString) {
  18785. {
  18786. httplib::Client cli_empty("", PORT);
  18787. auto res = cli_empty.Get("/");
  18788. ASSERT_FALSE(res);
  18789. EXPECT_EQ(httplib::Error::Connection, res.error());
  18790. }
  18791. {
  18792. httplib::Client cli(" ", PORT);
  18793. auto res = cli.Get("/");
  18794. ASSERT_FALSE(res);
  18795. EXPECT_EQ(httplib::Error::Connection, res.error());
  18796. }
  18797. }
  18798. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18799. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  18800. Server svr;
  18801. // Set a small payload limit (1KB)
  18802. svr.set_payload_max_length(1024);
  18803. svr.Post("/test", [&](const Request &req, Response &res) {
  18804. res.set_content("Body size: " + std::to_string(req.body.size()),
  18805. "text/plain");
  18806. });
  18807. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18808. auto se = detail::scope_exit([&] {
  18809. svr.stop();
  18810. listen_thread.join();
  18811. });
  18812. svr.wait_until_ready();
  18813. // Create data that compresses well but exceeds limit when decompressed
  18814. // 8KB of repeated null bytes compresses to a very small size
  18815. std::string original_data(8 * 1024, '\0');
  18816. // Compress the data using gzip
  18817. std::string compressed_data;
  18818. detail::gzip_compressor compressor;
  18819. compressor.compress(original_data.data(), original_data.size(), true,
  18820. [&](const char *data, size_t size) {
  18821. compressed_data.append(data, size);
  18822. return true;
  18823. });
  18824. // Verify compression worked (compressed should be much smaller)
  18825. ASSERT_LT(compressed_data.size(), original_data.size());
  18826. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  18827. // Send compressed data with Content-Encoding: gzip
  18828. Client cli(HOST, PORT);
  18829. Headers headers = {{"Content-Encoding", "gzip"}};
  18830. auto res =
  18831. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  18832. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  18833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18834. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  18835. }
  18836. #endif
  18837. // ============================================================================
  18838. // OpenSSL-Specific Tests
  18839. // ============================================================================
  18840. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18841. X509 *readCertificate(const std::string &strFileName) {
  18842. std::ifstream inStream(strFileName);
  18843. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  18844. std::istreambuf_iterator<char>());
  18845. if (strCertPEM.empty()) return (nullptr);
  18846. BIO *pbCert = BIO_new(BIO_s_mem());
  18847. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  18848. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  18849. BIO_free(pbCert);
  18850. return (pCert);
  18851. }
  18852. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  18853. std::ifstream inStream(strFileName);
  18854. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  18855. std::istreambuf_iterator<char>());
  18856. if (strPrivateKeyPEM.empty()) return (nullptr);
  18857. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  18858. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  18859. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  18860. BIO_free(pbPrivKey);
  18861. return (pPrivateKey);
  18862. }
  18863. TEST(BindServerTest, UpdateCerts) {
  18864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18865. int port = svr.bind_to_any_port("0.0.0.0");
  18866. ASSERT_TRUE(svr.is_valid());
  18867. ASSERT_TRUE(port > 0);
  18868. X509 *cert = readCertificate(SERVER_CERT_FILE);
  18869. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  18870. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  18871. ASSERT_TRUE(cert != nullptr);
  18872. ASSERT_TRUE(ca_cert != nullptr);
  18873. ASSERT_TRUE(key != nullptr);
  18874. X509_STORE *cert_store = X509_STORE_new();
  18875. X509_STORE_add_cert(cert_store, ca_cert);
  18876. // svr.update_certs(cert, key, cert_store); // deprecated
  18877. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  18878. CLIENT_CA_CERT_FILE);
  18879. ASSERT_TRUE(svr.is_valid());
  18880. svr.stop();
  18881. X509_STORE_free(cert_store);
  18882. X509_free(cert);
  18883. X509_free(ca_cert);
  18884. EVP_PKEY_free(key);
  18885. }
  18886. // Test that update_certs() updates client CA list correctly
  18887. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  18888. // Start with file-based constructor
  18889. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18890. ASSERT_TRUE(svr.is_valid());
  18891. // Initially no client CA list should be set
  18892. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18893. ASSERT_TRUE(ssl_ctx != nullptr);
  18894. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  18895. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  18896. EXPECT_EQ(0, count_before);
  18897. // Now update with client CA (PEM string)
  18898. std::string cert_pem, key_pem, ca_pem;
  18899. read_file(SERVER_CERT_FILE, cert_pem);
  18900. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  18901. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  18902. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  18903. ASSERT_TRUE(svr.is_valid());
  18904. // Now client CA list should be set
  18905. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  18906. ASSERT_TRUE(ca_list_after != nullptr);
  18907. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  18908. }
  18909. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  18910. // Test that the file-path SSLServer constructor properly sets the client CA
  18911. // list that is sent to clients during the TLS handshake (CertificateRequest)
  18912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18913. ASSERT_TRUE(svr.is_valid());
  18914. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18915. ASSERT_TRUE(ssl_ctx != nullptr);
  18916. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  18917. ASSERT_TRUE(ca_list != nullptr);
  18918. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  18919. }
  18920. #endif
  18921. // ============================================================================
  18922. // MbedTLS-Specific Tests
  18923. // ============================================================================
  18924. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  18925. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  18926. using namespace httplib::tls;
  18927. // Track if callback was invoked
  18928. bool callback_invoked = false;
  18929. // The callback receives void* ctx which is actually MbedTlsContext*
  18930. // We can access the mbedtls_ssl_config via the context
  18931. auto setup_callback = [&callback_invoked](void *ctx) {
  18932. callback_invoked = true;
  18933. // Cast to MbedTlsContext* to access the ssl config
  18934. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  18935. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  18936. // Use static variables to hold certificate data (simplified for test)
  18937. static mbedtls_x509_crt own_cert;
  18938. static mbedtls_pk_context own_key;
  18939. static mbedtls_x509_crt ca_chain;
  18940. static bool initialized = false;
  18941. if (!initialized) {
  18942. mbedtls_x509_crt_init(&own_cert);
  18943. mbedtls_pk_init(&own_key);
  18944. mbedtls_x509_crt_init(&ca_chain);
  18945. // Load server certificate
  18946. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  18947. return false;
  18948. }
  18949. // Load server private key.
  18950. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  18951. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  18952. #if MBEDTLS_VERSION_MAJOR == 3
  18953. ,
  18954. mbedtls_ctr_drbg_random, nullptr
  18955. #endif
  18956. ) != 0) {
  18957. return false;
  18958. }
  18959. // Load CA chain for client verification
  18960. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  18961. return false;
  18962. }
  18963. initialized = true;
  18964. }
  18965. // Configure the SSL config
  18966. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  18967. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  18968. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  18969. // Set minimum TLS version using mbedTLS native API
  18970. #if MBEDTLS_VERSION_MAJOR >= 3
  18971. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  18972. #else
  18973. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  18974. MBEDTLS_SSL_MINOR_VERSION_3);
  18975. #endif
  18976. return true;
  18977. };
  18978. SSLServer svr(setup_callback);
  18979. ASSERT_TRUE(svr.is_valid());
  18980. ASSERT_TRUE(callback_invoked);
  18981. svr.Get("/test", [&](const Request &req, Response &res) {
  18982. res.set_content("test", "text/plain");
  18983. auto cert = req.peer_cert();
  18984. ASSERT_TRUE(static_cast<bool>(cert));
  18985. auto common_name = cert.subject_cn();
  18986. EXPECT_EQ("Common Name", common_name);
  18987. });
  18988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18989. auto se = detail::scope_exit([&] {
  18990. svr.stop();
  18991. t.join();
  18992. ASSERT_FALSE(svr.is_running());
  18993. });
  18994. svr.wait_until_ready();
  18995. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18996. cli.enable_server_certificate_verification(false);
  18997. cli.set_connection_timeout(30);
  18998. auto res = cli.Get("/test");
  18999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19000. ASSERT_EQ(StatusCode::OK_200, res->status);
  19001. }
  19002. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19003. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19004. // keep-alive SSL session, which reads through that config in
  19005. // mbedtls_ssl_close_notify.
  19006. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19008. ASSERT_TRUE(svr.is_valid());
  19009. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19010. res.set_content("test", "text/plain");
  19011. });
  19012. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19013. auto se = detail::scope_exit([&] {
  19014. svr.stop();
  19015. t.join();
  19016. ASSERT_FALSE(svr.is_running());
  19017. });
  19018. svr.wait_until_ready();
  19019. {
  19020. SSLClient cli(HOST, PORT);
  19021. cli.enable_server_certificate_verification(false);
  19022. cli.set_keep_alive(true);
  19023. auto res = cli.Get("/test");
  19024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19025. ASSERT_EQ(StatusCode::OK_200, res->status);
  19026. // cli is destructed here with the keep-alive SSL session still open.
  19027. }
  19028. }
  19029. #endif
  19030. // WebSocket Tests
  19031. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19032. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19033. // defining the meaning of these bits has been negotiated.
  19034. auto make_frame = [](uint8_t first_byte) {
  19035. std::string frame;
  19036. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19037. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19038. frame += "Hello";
  19039. return frame;
  19040. };
  19041. // RSV1 set (0x40)
  19042. {
  19043. detail::BufferStream strm;
  19044. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19045. ws::Opcode opcode;
  19046. std::string payload;
  19047. bool fin;
  19048. EXPECT_EQ(
  19049. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19050. ws::impl::FrameRead::Fail);
  19051. }
  19052. // RSV2 set (0x20)
  19053. {
  19054. detail::BufferStream strm;
  19055. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19056. ws::Opcode opcode;
  19057. std::string payload;
  19058. bool fin;
  19059. EXPECT_EQ(
  19060. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19061. ws::impl::FrameRead::Fail);
  19062. }
  19063. // RSV3 set (0x10)
  19064. {
  19065. detail::BufferStream strm;
  19066. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19067. ws::Opcode opcode;
  19068. std::string payload;
  19069. bool fin;
  19070. EXPECT_EQ(
  19071. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19072. ws::impl::FrameRead::Fail);
  19073. }
  19074. // No RSV bits set - should succeed
  19075. {
  19076. detail::BufferStream strm;
  19077. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19078. ws::Opcode opcode;
  19079. std::string payload;
  19080. bool fin;
  19081. EXPECT_EQ(
  19082. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19083. ws::impl::FrameRead::Ok);
  19084. EXPECT_EQ(ws::Opcode::Text, opcode);
  19085. EXPECT_EQ("Hello", payload);
  19086. EXPECT_TRUE(fin);
  19087. }
  19088. }
  19089. TEST(WebSocketTest, ControlFrameValidation) {
  19090. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19091. // payload length <= 125.
  19092. // Ping with FIN=0 - must be rejected
  19093. {
  19094. detail::BufferStream strm;
  19095. std::string frame;
  19096. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19097. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19098. strm.write(frame.data(), frame.size());
  19099. ws::Opcode opcode;
  19100. std::string payload;
  19101. bool fin;
  19102. EXPECT_EQ(
  19103. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19104. ws::impl::FrameRead::Fail);
  19105. }
  19106. // Close with FIN=0 - must be rejected
  19107. {
  19108. detail::BufferStream strm;
  19109. std::string frame;
  19110. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19111. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19112. strm.write(frame.data(), frame.size());
  19113. ws::Opcode opcode;
  19114. std::string payload;
  19115. bool fin;
  19116. EXPECT_EQ(
  19117. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19118. ws::impl::FrameRead::Fail);
  19119. }
  19120. // Ping with payload_len=126 (extended length) - must be rejected
  19121. {
  19122. detail::BufferStream strm;
  19123. std::string frame;
  19124. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19125. frame += static_cast<char>(126); // payload_len=126 (>125)
  19126. frame += static_cast<char>(0x00); // extended length high byte
  19127. frame += static_cast<char>(126); // extended length low byte
  19128. frame += std::string(126, 'x');
  19129. strm.write(frame.data(), frame.size());
  19130. ws::Opcode opcode;
  19131. std::string payload;
  19132. bool fin;
  19133. EXPECT_EQ(
  19134. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19135. ws::impl::FrameRead::Fail);
  19136. }
  19137. // Ping with FIN=1 and payload_len=125 - should succeed
  19138. {
  19139. detail::BufferStream strm;
  19140. std::string frame;
  19141. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19142. frame += static_cast<char>(125); // payload_len=125
  19143. frame += std::string(125, 'x');
  19144. strm.write(frame.data(), frame.size());
  19145. ws::Opcode opcode;
  19146. std::string payload;
  19147. bool fin;
  19148. EXPECT_EQ(
  19149. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19150. ws::impl::FrameRead::Ok);
  19151. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19152. EXPECT_EQ(125u, payload.size());
  19153. EXPECT_TRUE(fin);
  19154. }
  19155. }
  19156. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19157. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19158. // length MUST be 0.
  19159. // MSB set - must be rejected
  19160. {
  19161. detail::BufferStream strm;
  19162. std::string frame;
  19163. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19164. frame += static_cast<char>(127); // 64-bit extended length
  19165. frame += static_cast<char>(0x80); // MSB set (invalid)
  19166. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19167. strm.write(frame.data(), frame.size());
  19168. ws::Opcode opcode;
  19169. std::string payload;
  19170. bool fin;
  19171. EXPECT_EQ(
  19172. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19173. ws::impl::FrameRead::Fail);
  19174. }
  19175. // MSB clear - should pass length parsing (will be rejected by max_len,
  19176. // but that's a different check; use a small length to verify)
  19177. {
  19178. detail::BufferStream strm;
  19179. std::string frame;
  19180. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19181. frame += static_cast<char>(127); // 64-bit extended length
  19182. frame += std::string(7, '\0'); // high bytes = 0
  19183. frame += static_cast<char>(0x03); // length = 3
  19184. frame += "abc";
  19185. strm.write(frame.data(), frame.size());
  19186. ws::Opcode opcode;
  19187. std::string payload;
  19188. bool fin;
  19189. EXPECT_EQ(
  19190. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19191. ws::impl::FrameRead::Ok);
  19192. EXPECT_EQ(ws::Opcode::Text, opcode);
  19193. EXPECT_EQ("abc", payload);
  19194. }
  19195. }
  19196. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19197. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19198. // Valid UTF-8
  19199. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19200. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19201. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19202. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19203. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19204. // Invalid UTF-8
  19205. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19206. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19207. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19208. EXPECT_FALSE(
  19209. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19210. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19211. }
  19212. TEST(WebSocketTest, ConnectAndDisconnect) {
  19213. Server svr;
  19214. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19215. std::string msg;
  19216. while (ws.read(msg)) {}
  19217. });
  19218. auto port = svr.bind_to_any_port(HOST);
  19219. std::thread t([&]() { svr.listen_after_bind(); });
  19220. svr.wait_until_ready();
  19221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19222. auto res = client.connect();
  19223. ASSERT_TRUE(res);
  19224. EXPECT_EQ(Error::Success, res.error());
  19225. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19226. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19227. EXPECT_TRUE(client.is_open());
  19228. client.close();
  19229. EXPECT_FALSE(client.is_open());
  19230. svr.stop();
  19231. t.join();
  19232. }
  19233. TEST(WebSocketTest, ValidURL) {
  19234. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19235. EXPECT_TRUE(ws1.is_valid());
  19236. ws::WebSocketClient ws2("ws://example.com/path");
  19237. EXPECT_TRUE(ws2.is_valid());
  19238. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19239. EXPECT_TRUE(ws3.is_valid());
  19240. #ifdef CPPHTTPLIB_SSL_ENABLED
  19241. ws::WebSocketClient wss1("wss://example.com/path");
  19242. EXPECT_TRUE(wss1.is_valid());
  19243. ws::WebSocketClient wss2("wss://example.com:443/path");
  19244. EXPECT_TRUE(wss2.is_valid());
  19245. #endif
  19246. }
  19247. TEST(WebSocketTest, InvalidURL) {
  19248. // No scheme
  19249. ws::WebSocketClient ws1("localhost:8080/path");
  19250. EXPECT_FALSE(ws1.is_valid());
  19251. // No path
  19252. ws::WebSocketClient ws2("ws://localhost:8080");
  19253. EXPECT_FALSE(ws2.is_valid());
  19254. // Empty string
  19255. ws::WebSocketClient ws3("");
  19256. EXPECT_FALSE(ws3.is_valid());
  19257. // Missing host
  19258. ws::WebSocketClient ws4("ws://:8080/path");
  19259. EXPECT_FALSE(ws4.is_valid());
  19260. // Port number overflow — should not crash
  19261. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19262. EXPECT_FALSE(ws5.is_valid());
  19263. // Port out of range
  19264. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19265. EXPECT_FALSE(ws6.is_valid());
  19266. }
  19267. TEST(WebSocketTest, UnsupportedScheme) {
  19268. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19269. ws::WebSocketClient ws1("http://localhost:8080/path");
  19270. EXPECT_FALSE(ws1.is_valid());
  19271. ws::WebSocketClient ws2("https://localhost:8080/path");
  19272. EXPECT_FALSE(ws2.is_valid());
  19273. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19274. EXPECT_FALSE(ws3.is_valid());
  19275. #else
  19276. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19277. std::invalid_argument);
  19278. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19279. std::invalid_argument);
  19280. #endif
  19281. }
  19282. TEST(WebSocketTest, ConnectWhenInvalid) {
  19283. ws::WebSocketClient ws("not a valid url");
  19284. EXPECT_FALSE(ws.is_valid());
  19285. auto res = ws.connect();
  19286. EXPECT_FALSE(res);
  19287. EXPECT_EQ(Error::Connection, res.error());
  19288. EXPECT_EQ(-1, res.status());
  19289. }
  19290. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19291. // Grab a port that is free, then close it again so nothing listens there
  19292. Server svr;
  19293. auto port = svr.bind_to_any_port(HOST);
  19294. svr.stop();
  19295. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19296. auto res = client.connect();
  19297. ASSERT_FALSE(res);
  19298. EXPECT_EQ(Error::Connection, res.error());
  19299. EXPECT_EQ(-1, res.status());
  19300. }
  19301. TEST(WebSocketTest, DefaultPort) {
  19302. ws::WebSocketClient ws1("ws://example.com/path");
  19303. EXPECT_TRUE(ws1.is_valid());
  19304. // ws:// defaults to port 80 (verified by successful parse)
  19305. #ifdef CPPHTTPLIB_SSL_ENABLED
  19306. ws::WebSocketClient ws2("wss://example.com/path");
  19307. EXPECT_TRUE(ws2.is_valid());
  19308. // wss:// defaults to port 443 (verified by successful parse)
  19309. #endif
  19310. }
  19311. TEST(WebSocketTest, IPv6LiteralAddress) {
  19312. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19313. EXPECT_TRUE(ws1.is_valid());
  19314. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19315. EXPECT_TRUE(ws2.is_valid());
  19316. }
  19317. TEST(WebSocketTest, ComplexPath) {
  19318. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19319. EXPECT_TRUE(ws1.is_valid());
  19320. ws::WebSocketClient ws2("ws://localhost:8080/");
  19321. EXPECT_TRUE(ws2.is_valid());
  19322. }
  19323. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19324. Server svr;
  19325. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19326. std::string msg;
  19327. while (ws.read(msg)) {}
  19328. });
  19329. auto port = svr.bind_to_any_port(HOST);
  19330. std::thread t([&]() { svr.listen_after_bind(); });
  19331. svr.wait_until_ready();
  19332. auto another_host = "example.com";
  19333. auto wrong_ip = "192.0.2.1";
  19334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19335. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19336. ASSERT_TRUE(client.connect());
  19337. EXPECT_TRUE(client.is_open());
  19338. client.close();
  19339. svr.stop();
  19340. t.join();
  19341. }
  19342. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19343. Server svr;
  19344. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19345. std::string msg;
  19346. while (ws.read(msg)) {}
  19347. });
  19348. auto port = svr.bind_to_any_port(HOST);
  19349. std::thread t([&]() { svr.listen_after_bind(); });
  19350. svr.wait_until_ready();
  19351. auto wrong_ip = "192.0.2.1";
  19352. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19353. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19354. client.set_connection_timeout(1);
  19355. client.set_read_timeout(1);
  19356. client.set_write_timeout(1);
  19357. EXPECT_FALSE(client.connect());
  19358. EXPECT_FALSE(client.is_open());
  19359. svr.stop();
  19360. t.join();
  19361. }
  19362. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19363. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19364. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19365. // (RFC 6761) is only a map key and the Host header value.
  19366. auto host = "target.invalid";
  19367. Server svr;
  19368. std::string received_host;
  19369. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19370. received_host = req.get_header_value("Host");
  19371. std::string msg;
  19372. while (ws.read(msg)) {}
  19373. });
  19374. auto port = svr.bind_to_any_port(HOST);
  19375. std::thread t([&]() { svr.listen_after_bind(); });
  19376. // ASSERT_* below returns from the test body, which would leave t joinable
  19377. // and make ~thread call std::terminate.
  19378. auto se = detail::scope_exit([&] {
  19379. svr.stop();
  19380. if (t.joinable()) { t.join(); }
  19381. });
  19382. svr.wait_until_ready();
  19383. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19384. std::to_string(port) + "/ws");
  19385. client.set_hostname_addr_map({{host, HOST}});
  19386. ASSERT_TRUE(client.connect());
  19387. EXPECT_TRUE(client.is_open());
  19388. client.close();
  19389. svr.stop();
  19390. t.join();
  19391. // The mapping only redirects the connection; the identity stays host_.
  19392. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19393. }
  19394. class WebSocketIntegrationTest : public ::testing::Test {
  19395. protected:
  19396. void SetUp() override {
  19397. server_ = httplib::detail::make_unique<Server>();
  19398. setup_server();
  19399. start_server();
  19400. }
  19401. void TearDown() override {
  19402. server_->stop();
  19403. if (server_thread_.joinable()) { server_thread_.join(); }
  19404. }
  19405. void setup_server() {
  19406. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19407. std::string msg;
  19408. ws::ReadResult ret;
  19409. while ((ret = ws.read(msg))) {
  19410. if (ret == ws::Binary) {
  19411. ws.send(msg.data(), msg.size());
  19412. } else {
  19413. ws.send(msg);
  19414. }
  19415. }
  19416. });
  19417. server_->WebSocket("/ws-echo-string",
  19418. [](const Request &, ws::WebSocket &ws) {
  19419. std::string msg;
  19420. while (ws.read(msg)) {
  19421. ws.send("echo: " + msg);
  19422. }
  19423. });
  19424. server_->WebSocket(
  19425. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19426. // Echo back request metadata
  19427. ws.send("path:" + req.path);
  19428. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19429. std::string msg;
  19430. while (ws.read(msg)) {}
  19431. });
  19432. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19433. std::string msg;
  19434. ws.read(msg); // wait for a message
  19435. ws.close();
  19436. });
  19437. server_->WebSocket("/ws-close-status",
  19438. [](const Request &, ws::WebSocket &ws) {
  19439. std::string msg;
  19440. ws.read(msg); // wait for a message
  19441. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19442. });
  19443. server_->WebSocket(
  19444. "/ws-subprotocol",
  19445. [](const Request &, ws::WebSocket &ws) {
  19446. std::string msg;
  19447. while (ws.read(msg)) {
  19448. ws.send(msg);
  19449. }
  19450. },
  19451. [](const std::vector<std::string> &protocols) -> std::string {
  19452. for (const auto &p : protocols) {
  19453. if (p == "graphql-ws") { return p; }
  19454. }
  19455. return "";
  19456. });
  19457. }
  19458. void start_server() {
  19459. port_ = server_->bind_to_any_port(HOST);
  19460. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19461. server_->wait_until_ready();
  19462. }
  19463. std::unique_ptr<Server> server_;
  19464. std::thread server_thread_;
  19465. int port_ = 0;
  19466. };
  19467. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19468. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19469. "/ws-echo");
  19470. ASSERT_TRUE(client.connect());
  19471. ASSERT_TRUE(client.is_open());
  19472. ASSERT_TRUE(client.send("Hello WebSocket"));
  19473. std::string msg;
  19474. EXPECT_EQ(ws::Text, client.read(msg));
  19475. EXPECT_EQ("Hello WebSocket", msg);
  19476. client.close();
  19477. }
  19478. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19479. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19480. "/ws-echo");
  19481. ASSERT_TRUE(client.connect());
  19482. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19483. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19484. std::string msg;
  19485. EXPECT_EQ(ws::Binary, client.read(msg));
  19486. EXPECT_EQ(binary_data, msg);
  19487. client.close();
  19488. }
  19489. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19491. "/ws-echo");
  19492. ASSERT_TRUE(client.connect());
  19493. for (int i = 0; i < 10; i++) {
  19494. auto text = "message " + std::to_string(i);
  19495. ASSERT_TRUE(client.send(text));
  19496. std::string msg;
  19497. ASSERT_TRUE(client.read(msg));
  19498. EXPECT_EQ(text, msg);
  19499. }
  19500. client.close();
  19501. }
  19502. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19504. "/ws-close");
  19505. ASSERT_TRUE(client.connect());
  19506. // Send a message to trigger the server to close
  19507. ASSERT_TRUE(client.send("trigger close"));
  19508. // The server will close, so read should return false
  19509. std::string msg;
  19510. EXPECT_FALSE(client.read(msg));
  19511. EXPECT_FALSE(client.is_open());
  19512. }
  19513. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19514. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19515. "/ws-echo");
  19516. ASSERT_TRUE(client.connect());
  19517. // 128KB message
  19518. std::string large_data(128 * 1024, 'X');
  19519. ASSERT_TRUE(client.send(large_data));
  19520. std::string msg;
  19521. ASSERT_TRUE(client.read(msg));
  19522. EXPECT_EQ(large_data, msg);
  19523. client.close();
  19524. }
  19525. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19526. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19527. "/ws-echo");
  19528. ASSERT_TRUE(client.connect());
  19529. const int num_threads = 4;
  19530. std::vector<std::thread> threads;
  19531. std::atomic<int> send_count{0};
  19532. for (int t = 0; t < num_threads; t++) {
  19533. threads.emplace_back([&client, &send_count, t]() {
  19534. for (int i = 0; i < 5; i++) {
  19535. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19536. if (client.send(text)) { send_count++; }
  19537. }
  19538. });
  19539. }
  19540. for (auto &th : threads) {
  19541. th.join();
  19542. }
  19543. int received = 0;
  19544. std::string msg;
  19545. while (received < send_count.load()) {
  19546. if (!client.read(msg)) { break; }
  19547. received++;
  19548. }
  19549. EXPECT_EQ(send_count.load(), received);
  19550. client.close();
  19551. }
  19552. TEST_F(WebSocketIntegrationTest, ReadString) {
  19553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19554. "/ws-echo-string");
  19555. ASSERT_TRUE(client.connect());
  19556. ASSERT_TRUE(client.send("hello"));
  19557. std::string msg;
  19558. ASSERT_TRUE(client.read(msg));
  19559. EXPECT_EQ("echo: hello", msg);
  19560. ASSERT_TRUE(client.send("world"));
  19561. ASSERT_TRUE(client.read(msg));
  19562. EXPECT_EQ("echo: world", msg);
  19563. client.close();
  19564. }
  19565. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19566. Headers headers = {{"X-Test-Header", "test-value"}};
  19567. ws::WebSocketClient client(
  19568. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19569. ASSERT_TRUE(client.connect());
  19570. std::string msg;
  19571. ASSERT_TRUE(client.read(msg));
  19572. EXPECT_EQ("path:/ws-request-info", msg);
  19573. ASSERT_TRUE(client.read(msg));
  19574. EXPECT_EQ("header:test-value", msg);
  19575. client.close();
  19576. }
  19577. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19579. "/ws-echo");
  19580. client.set_read_timeout(1, 0); // 1 second
  19581. ASSERT_TRUE(client.connect());
  19582. // Don't send anything — server echo handler waits for a message, so read()
  19583. // should time out. The connection survives it: nothing was consumed.
  19584. std::string msg;
  19585. EXPECT_EQ(client.read(msg), ws::Timeout);
  19586. EXPECT_TRUE(client.is_open());
  19587. // And it is still usable afterwards.
  19588. EXPECT_TRUE(client.send("after timeout"));
  19589. EXPECT_EQ(client.read(msg), ws::Text);
  19590. EXPECT_EQ(msg, "after timeout");
  19591. }
  19592. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19593. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19594. "/ws-echo");
  19595. client.set_read_timeout(1, 0);
  19596. ASSERT_TRUE(client.connect());
  19597. ASSERT_TRUE(client.send("first"));
  19598. std::string msg;
  19599. ASSERT_EQ(client.read(msg), ws::Text);
  19600. ASSERT_EQ(msg, "first");
  19601. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19602. // not be used with a read timeout: it would reprocess the previous message.
  19603. EXPECT_EQ(client.read(msg), ws::Timeout);
  19604. EXPECT_EQ(msg, "first");
  19605. }
  19606. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19607. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19608. "/ws-echo");
  19609. ASSERT_TRUE(client.connect());
  19610. // Setting it once the connection is open reaches the live stream, not just
  19611. // the seed for the next connect().
  19612. client.set_read_timeout(1, 0);
  19613. std::string msg;
  19614. EXPECT_EQ(client.read(msg), ws::Timeout);
  19615. EXPECT_TRUE(client.is_open());
  19616. }
  19617. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19618. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19619. "/ws-echo");
  19620. client.set_read_timeout(5, 0);
  19621. ASSERT_TRUE(client.connect());
  19622. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19623. // The server should reject it and close the connection.
  19624. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19625. client.send(oversized);
  19626. // The server's read() should have failed due to payload limit,
  19627. // so our read() should return false (connection closed).
  19628. std::string msg;
  19629. EXPECT_FALSE(client.read(msg));
  19630. }
  19631. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19632. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19633. "/ws-echo");
  19634. client.set_read_timeout(10, 0);
  19635. ASSERT_TRUE(client.connect());
  19636. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19637. // This should succeed.
  19638. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19639. ASSERT_TRUE(client.send(at_limit));
  19640. std::string msg;
  19641. ASSERT_TRUE(client.read(msg));
  19642. EXPECT_EQ(at_limit.size(), msg.size());
  19643. client.close();
  19644. }
  19645. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19646. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19647. "/nonexistent");
  19648. auto res = client.connect();
  19649. EXPECT_FALSE(res);
  19650. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19651. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19652. EXPECT_FALSE(client.is_open());
  19653. }
  19654. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19656. "/ws-echo");
  19657. ASSERT_TRUE(client.connect());
  19658. ASSERT_TRUE(client.send(""));
  19659. std::string msg;
  19660. EXPECT_EQ(ws::Text, client.read(msg));
  19661. EXPECT_EQ("", msg);
  19662. client.close();
  19663. }
  19664. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19665. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19666. "/ws-echo");
  19667. // First connection
  19668. ASSERT_TRUE(client.connect());
  19669. ASSERT_TRUE(client.send("first"));
  19670. std::string msg;
  19671. ASSERT_TRUE(client.read(msg));
  19672. EXPECT_EQ("first", msg);
  19673. client.close();
  19674. EXPECT_FALSE(client.is_open());
  19675. // Reconnect using the same client object
  19676. ASSERT_TRUE(client.connect());
  19677. ASSERT_TRUE(client.is_open());
  19678. ASSERT_TRUE(client.send("second"));
  19679. ASSERT_TRUE(client.read(msg));
  19680. EXPECT_EQ("second", msg);
  19681. client.close();
  19682. }
  19683. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19685. "/ws-close-status");
  19686. ASSERT_TRUE(client.connect());
  19687. // Trigger the server to close with GoingAway status
  19688. ASSERT_TRUE(client.send("trigger"));
  19689. // read() should return false after receiving the close frame
  19690. std::string msg;
  19691. EXPECT_FALSE(client.read(msg));
  19692. EXPECT_FALSE(client.is_open());
  19693. }
  19694. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19695. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19696. "/ws-echo");
  19697. ASSERT_TRUE(client.connect());
  19698. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19699. EXPECT_FALSE(client.is_open());
  19700. }
  19701. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19702. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19703. ws::WebSocketClient client(
  19704. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19705. ASSERT_TRUE(client.connect());
  19706. // Server should have selected graphql-ws
  19707. EXPECT_EQ("graphql-ws", client.subprotocol());
  19708. client.close();
  19709. }
  19710. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19711. Headers headers;
  19712. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19713. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19714. ws::WebSocketClient client(
  19715. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19716. ASSERT_TRUE(client.connect());
  19717. // The offer on the second field line counts too, so graphql-ws is selected
  19718. EXPECT_EQ("graphql-ws", client.subprotocol());
  19719. client.close();
  19720. }
  19721. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19722. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19723. ws::WebSocketClient client(
  19724. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19725. ASSERT_TRUE(client.connect());
  19726. // Server should not have selected any subprotocol
  19727. EXPECT_TRUE(client.subprotocol().empty());
  19728. client.close();
  19729. }
  19730. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19731. // Connect without requesting any subprotocol
  19732. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19733. "/ws-subprotocol");
  19734. ASSERT_TRUE(client.connect());
  19735. EXPECT_TRUE(client.subprotocol().empty());
  19736. client.close();
  19737. }
  19738. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19740. "/ws-echo");
  19741. client.set_tcp_nodelay(true);
  19742. client.set_connection_timeout(3, 0);
  19743. bool socket_options_called = false;
  19744. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19745. ASSERT_TRUE(client.connect());
  19746. ASSERT_TRUE(client.is_open());
  19747. EXPECT_TRUE(socket_options_called);
  19748. ASSERT_TRUE(client.send("hello"));
  19749. std::string msg;
  19750. auto result = client.read(msg);
  19751. EXPECT_EQ(result, ws::ReadResult::Text);
  19752. EXPECT_EQ(msg, "hello");
  19753. client.close();
  19754. }
  19755. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19756. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19757. "/ws-echo");
  19758. client.set_connection_timeout(std::chrono::seconds(3));
  19759. client.set_write_timeout(std::chrono::seconds(3));
  19760. // A sub-second remainder exercises the seconds/microseconds split.
  19761. client.set_read_timeout(std::chrono::milliseconds(1500));
  19762. ASSERT_TRUE(client.connect());
  19763. auto start = std::chrono::steady_clock::now();
  19764. std::string msg;
  19765. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  19766. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19767. std::chrono::steady_clock::now() - start)
  19768. .count();
  19769. // Above 1s so that dropping the microseconds half of the split fails here.
  19770. // Ignoring the setter altogether would not reach this line at all: a client
  19771. // waits forever by default.
  19772. EXPECT_GE(elapsed, 1400);
  19773. EXPECT_LT(elapsed, 30000);
  19774. }
  19775. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  19776. Server svr;
  19777. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  19778. if (!req.has_header("Authorization")) {
  19779. res.status = StatusCode::Unauthorized_401;
  19780. res.set_content("Unauthorized", "text/plain");
  19781. return Server::HandlerResponse::Handled;
  19782. }
  19783. return Server::HandlerResponse::Unhandled;
  19784. });
  19785. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19786. std::string msg;
  19787. while (ws.read(msg)) {
  19788. ws.send(msg);
  19789. }
  19790. });
  19791. auto port = svr.bind_to_any_port("localhost");
  19792. std::thread t([&]() { svr.listen_after_bind(); });
  19793. svr.wait_until_ready();
  19794. // Without Authorization header - should be rejected before upgrade
  19795. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  19796. EXPECT_FALSE(client1.connect());
  19797. // The rejection is framed like any other HTTP response
  19798. {
  19799. Client cli("localhost", port);
  19800. Headers headers = {{"Upgrade", "websocket"},
  19801. {"Connection", "Upgrade"},
  19802. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19803. {"Sec-WebSocket-Version", "13"}};
  19804. auto res = cli.Get("/ws", headers);
  19805. ASSERT_TRUE(res);
  19806. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19807. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  19808. EXPECT_EQ("Unauthorized", res->body);
  19809. }
  19810. // With Authorization header - should succeed
  19811. Headers headers = {{"Authorization", "Bearer token123"}};
  19812. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  19813. headers);
  19814. ASSERT_TRUE(client2.connect());
  19815. ASSERT_TRUE(client2.send("hello"));
  19816. std::string msg;
  19817. ASSERT_TRUE(client2.read(msg));
  19818. EXPECT_EQ("hello", msg);
  19819. client2.close();
  19820. svr.stop();
  19821. t.join();
  19822. }
  19823. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  19824. Server svr;
  19825. std::atomic<int> pre_request_calls{0};
  19826. std::atomic<bool> route_matched{false};
  19827. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  19828. pre_request_calls++;
  19829. if (req.matched_route == "/ws/:id") { route_matched = true; }
  19830. if (req.get_header_value("Authorization") != "Bearer token123") {
  19831. res.status = StatusCode::Unauthorized_401;
  19832. res.set_content("Unauthorized", "text/plain");
  19833. return Server::HandlerResponse::Handled;
  19834. }
  19835. return Server::HandlerResponse::Unhandled;
  19836. });
  19837. std::atomic<bool> handler_called{false};
  19838. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  19839. handler_called = true;
  19840. ws.send(req.matched_route + " " + req.path_params.at("id"));
  19841. });
  19842. auto port = svr.bind_to_any_port("localhost");
  19843. std::thread t([&]() { svr.listen_after_bind(); });
  19844. svr.wait_until_ready();
  19845. // Without Authorization header - should be rejected before upgrade
  19846. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  19847. "/ws/1");
  19848. EXPECT_FALSE(client1.connect());
  19849. EXPECT_FALSE(handler_called);
  19850. EXPECT_EQ(1, pre_request_calls);
  19851. EXPECT_TRUE(route_matched);
  19852. // The rejection is an ordinary HTTP response, not a protocol switch
  19853. {
  19854. Client cli("localhost", port);
  19855. Headers headers = {{"Upgrade", "websocket"},
  19856. {"Connection", "Upgrade"},
  19857. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19858. {"Sec-WebSocket-Version", "13"}};
  19859. auto res = cli.Get("/ws/1", headers);
  19860. ASSERT_TRUE(res);
  19861. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19862. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  19863. EXPECT_EQ("Unauthorized", res->body);
  19864. }
  19865. EXPECT_FALSE(handler_called);
  19866. // With Authorization header - should succeed
  19867. Headers headers = {{"Authorization", "Bearer token123"}};
  19868. ws::WebSocketClient client2(
  19869. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  19870. ASSERT_TRUE(client2.connect());
  19871. std::string msg;
  19872. ASSERT_TRUE(client2.read(msg));
  19873. EXPECT_EQ("/ws/:id 2", msg);
  19874. EXPECT_TRUE(handler_called);
  19875. client2.close();
  19876. svr.stop();
  19877. t.join();
  19878. }
  19879. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  19880. Server svr;
  19881. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19882. // A read timeout is how a handler gets control back. Without it, a handler
  19883. // parked in read() can never write on the connection it is reading.
  19884. ws.set_read_timeout(std::chrono::milliseconds(100));
  19885. std::string msg;
  19886. while (ws.is_open()) {
  19887. auto r = ws.read(msg);
  19888. if (r == httplib::ws::Timeout) {
  19889. ws.send("tick");
  19890. continue;
  19891. }
  19892. if (r == httplib::ws::Fail) { break; }
  19893. ws.send(msg);
  19894. }
  19895. });
  19896. auto port = svr.bind_to_any_port("localhost");
  19897. std::thread t([&]() { svr.listen_after_bind(); });
  19898. svr.wait_until_ready();
  19899. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19900. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  19901. ASSERT_TRUE(client.connect());
  19902. // The client sends nothing, so anything it receives came out of the
  19903. // handler's timeout path.
  19904. std::string msg;
  19905. ASSERT_EQ(client.read(msg), ws::Text);
  19906. EXPECT_EQ("tick", msg);
  19907. client.close();
  19908. svr.stop();
  19909. t.join();
  19910. }
  19911. // Stream::read may return fewer bytes than asked for. This is that contract at
  19912. // its worst -- one byte per call -- which is what a frame header straddling a
  19913. // read buffer's boundary looks like to the frame parser.
  19914. class WsByteAtATimeStream : public Stream {
  19915. public:
  19916. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  19917. bool is_readable() const override { return true; }
  19918. bool wait_readable() const override { return true; }
  19919. bool wait_writable() const override { return true; }
  19920. ssize_t read(char *ptr, size_t size) override {
  19921. if (size == 0 || pos_ >= data_.size()) { return 0; }
  19922. *ptr = data_[pos_++];
  19923. return 1;
  19924. }
  19925. ssize_t write(const char *, size_t size) override {
  19926. return static_cast<ssize_t>(size);
  19927. }
  19928. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19929. ip = "127.0.0.1";
  19930. port = 0;
  19931. }
  19932. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19933. ip = "127.0.0.1";
  19934. port = 0;
  19935. }
  19936. socket_t socket() const override { return INVALID_SOCKET; }
  19937. time_t duration() const override { return 0; }
  19938. private:
  19939. std::string data_;
  19940. size_t pos_ = 0;
  19941. };
  19942. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  19943. // A 200-byte payload uses the 16-bit extended length, so the header, the
  19944. // length and the mask key are all multi-byte fields here. Each used to be
  19945. // read with a single read() call, which fails as soon as one is split.
  19946. std::string body(200, 'x');
  19947. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  19948. std::string frame;
  19949. frame += static_cast<char>(0x81); // FIN + Text
  19950. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  19951. frame += static_cast<char>(body.size() >> 8);
  19952. frame += static_cast<char>(body.size() & 0xff);
  19953. for (size_t i = 0; i < 4; i++) {
  19954. frame += static_cast<char>(mask[i]);
  19955. }
  19956. for (size_t i = 0; i < body.size(); i++) {
  19957. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  19958. }
  19959. WsByteAtATimeStream strm(frame);
  19960. ws::Opcode opcode;
  19961. std::string payload;
  19962. bool fin = false;
  19963. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  19964. /*expect_masked=*/true, 1024),
  19965. ws::impl::FrameRead::Ok);
  19966. EXPECT_TRUE(fin);
  19967. EXPECT_EQ(opcode, ws::Opcode::Text);
  19968. EXPECT_EQ(payload, body);
  19969. }
  19970. TEST(WebSocketTest, QueryStringInHandshake) {
  19971. Server svr;
  19972. std::mutex mtx;
  19973. std::string received_target;
  19974. std::string received_token;
  19975. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19976. {
  19977. std::lock_guard<std::mutex> lock(mtx);
  19978. received_target = req.target;
  19979. if (req.has_param("token")) {
  19980. received_token = req.get_param_value("token");
  19981. }
  19982. }
  19983. std::string msg;
  19984. while (ws.read(msg)) {
  19985. ws.send(msg);
  19986. }
  19987. });
  19988. auto port = svr.bind_to_any_port("localhost");
  19989. std::thread t([&]() { svr.listen_after_bind(); });
  19990. svr.wait_until_ready();
  19991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  19992. "/ws?token=ABC&session=123");
  19993. ASSERT_TRUE(client.connect());
  19994. // Round-trip ensures the handler has run and captured the request.
  19995. ASSERT_TRUE(client.send("hello"));
  19996. std::string msg;
  19997. ASSERT_TRUE(client.read(msg));
  19998. EXPECT_EQ("hello", msg);
  19999. client.close();
  20000. {
  20001. std::lock_guard<std::mutex> lock(mtx);
  20002. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20003. EXPECT_EQ("ABC", received_token);
  20004. }
  20005. svr.stop();
  20006. t.join();
  20007. }
  20008. // Run a handshake against a throwaway server and hand the request the server
  20009. // received back to the caller, so tests can assert on the headers the client
  20010. // actually put on the wire.
  20011. static void capture_websocket_handshake_request(
  20012. const Headers &client_headers,
  20013. std::function<void(const Request &, int port)> verify) {
  20014. Server svr;
  20015. std::mutex mtx;
  20016. Request received;
  20017. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20018. {
  20019. std::lock_guard<std::mutex> lock(mtx);
  20020. received = req;
  20021. }
  20022. std::string msg;
  20023. while (ws.read(msg)) {
  20024. ws.send(msg);
  20025. }
  20026. });
  20027. auto port = svr.bind_to_any_port("localhost");
  20028. std::thread t([&]() { svr.listen_after_bind(); });
  20029. auto se = detail::scope_exit([&] {
  20030. svr.stop();
  20031. t.join();
  20032. });
  20033. svr.wait_until_ready();
  20034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20035. client_headers);
  20036. ASSERT_TRUE(client.connect());
  20037. ASSERT_TRUE(client.send("hello"));
  20038. std::string msg;
  20039. ASSERT_TRUE(client.read(msg));
  20040. client.close();
  20041. {
  20042. std::lock_guard<std::mutex> lock(mtx);
  20043. verify(received, port);
  20044. }
  20045. }
  20046. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20047. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20048. // Non-default port must be present in the Host header. Default ports
  20049. // (80/443) are omitted; that logic is covered by
  20050. // MakeHostAndPortStringTest.
  20051. EXPECT_EQ("localhost:" + std::to_string(port),
  20052. req.get_header_value("Host"));
  20053. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20054. req.get_header_value("User-Agent"));
  20055. EXPECT_FALSE(req.has_header("Accept"));
  20056. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20057. EXPECT_FALSE(req.has_header("Content-Length"));
  20058. });
  20059. }
  20060. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20061. capture_websocket_handshake_request(
  20062. {{"Host", "example.com"},
  20063. {"User-Agent", "custom-agent"},
  20064. {"X-Custom", "value"}},
  20065. [](const Request &req, int) {
  20066. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20067. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20068. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20069. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20070. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20071. });
  20072. }
  20073. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20074. capture_websocket_handshake_request(
  20075. {{"Upgrade", "bogus"},
  20076. {"Connection", "close"},
  20077. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20078. {"Sec-WebSocket-Version", "8"}},
  20079. [](const Request &req, int) {
  20080. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20081. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20082. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20083. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20084. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20085. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20086. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20087. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20088. req.get_header_value("Sec-WebSocket-Key"));
  20089. });
  20090. }
  20091. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20092. // A header the client refuses to send must abort the handshake before any
  20093. // part of it reaches the wire; a lone request line would otherwise sit in
  20094. // the peer's buffer as a truncated request.
  20095. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20096. ASSERT_NE(INVALID_SOCKET, srv);
  20097. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20098. sockaddr_in addr{};
  20099. addr.sin_family = AF_INET;
  20100. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20101. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20102. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20103. ASSERT_EQ(0, ::listen(srv, 1));
  20104. sockaddr_in bound{};
  20105. socklen_t bound_len = sizeof(bound);
  20106. ASSERT_EQ(
  20107. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20108. auto port = ntohs(bound.sin_port);
  20109. ssize_t received = -1;
  20110. std::thread t([&] {
  20111. // Bound every blocking call so a regression fails the test with a bad
  20112. // value instead of hanging the suite.
  20113. fd_set rfds;
  20114. FD_ZERO(&rfds);
  20115. FD_SET(srv, &rfds);
  20116. timeval tv{5, 0};
  20117. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20118. 0) {
  20119. return;
  20120. }
  20121. sockaddr_in cli_addr{};
  20122. socklen_t cli_len = sizeof(cli_addr);
  20123. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20124. if (cli == INVALID_SOCKET) { return; }
  20125. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20126. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20127. char buf[4096];
  20128. received = ::recv(cli, buf, sizeof(buf), 0);
  20129. });
  20130. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20131. // connect() has already shut the socket down by the time it returns false,
  20132. // so the peer sees EOF without waiting for the client to be destroyed.
  20133. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20134. {{"X-Bad", "a\r\nInjected: 1"}});
  20135. EXPECT_FALSE(client.connect());
  20136. t.join();
  20137. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20138. EXPECT_EQ(0, received);
  20139. }
  20140. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20141. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20142. // contains "upgrade" as a substring is a different token and must not
  20143. // start a WebSocket handshake.
  20144. auto make_request = [](const std::vector<std::string> &connection_values) {
  20145. Request req;
  20146. req.method = "GET";
  20147. req.headers.emplace("Upgrade", "websocket");
  20148. for (const auto &value : connection_values) {
  20149. req.headers.emplace("Connection", value);
  20150. }
  20151. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20152. req.headers.emplace("Sec-WebSocket-Version", "13");
  20153. return req;
  20154. };
  20155. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20156. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20157. EXPECT_TRUE(
  20158. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20159. EXPECT_TRUE(
  20160. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20161. EXPECT_TRUE(
  20162. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20163. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20164. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20165. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20166. EXPECT_FALSE(
  20167. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20168. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20169. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20170. }
  20171. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20172. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20173. // asks recipients to match each protocol-name case-insensitively, and RFC
  20174. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20175. // client naming websocket alongside another protocol, or on a second field
  20176. // line, is offering websocket; a value that merely contains "websocket" as a
  20177. // substring is a different protocol name and is not.
  20178. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20179. Request req;
  20180. req.method = "GET";
  20181. for (const auto &value : upgrade_values) {
  20182. req.headers.emplace("Upgrade", value);
  20183. }
  20184. req.headers.emplace("Connection", "Upgrade");
  20185. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20186. req.headers.emplace("Sec-WebSocket-Version", "13");
  20187. return req;
  20188. };
  20189. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20190. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20191. EXPECT_TRUE(
  20192. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20193. EXPECT_TRUE(
  20194. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20195. EXPECT_TRUE(
  20196. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20197. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20198. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20199. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20200. EXPECT_FALSE(
  20201. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20202. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20203. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20204. }
  20205. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20206. Server svr;
  20207. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20208. auto port = svr.bind_to_any_port("localhost");
  20209. std::thread t([&]() { svr.listen_after_bind(); });
  20210. auto se = detail::scope_exit([&] {
  20211. svr.stop();
  20212. t.join();
  20213. });
  20214. svr.wait_until_ready();
  20215. Headers headers = {{"Upgrade", "websocket"},
  20216. {"Connection", "notupgrade"},
  20217. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20218. {"Sec-WebSocket-Version", "13"}};
  20219. Client cli("localhost", port);
  20220. auto res = cli.Get("/ws", headers);
  20221. // The route exists only as a WebSocket route, so a request that fails the
  20222. // handshake check falls through to ordinary routing.
  20223. ASSERT_TRUE(res);
  20224. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20225. }
  20226. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20227. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20228. // Connection value is the only thing left for the client to reject.
  20229. Server svr;
  20230. svr.Get("/ws", [](const Request &req, Response &res) {
  20231. res.status = StatusCode::SwitchingProtocol_101;
  20232. res.set_header("Upgrade", "websocket");
  20233. res.set_header("Connection", "notupgrade");
  20234. res.set_header("Sec-WebSocket-Accept",
  20235. detail::websocket_accept_key(
  20236. req.get_header_value("Sec-WebSocket-Key")));
  20237. });
  20238. auto port = svr.bind_to_any_port("localhost");
  20239. std::thread t([&]() { svr.listen_after_bind(); });
  20240. auto se = detail::scope_exit([&] {
  20241. svr.stop();
  20242. t.join();
  20243. });
  20244. svr.wait_until_ready();
  20245. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20246. auto res = client.connect();
  20247. EXPECT_FALSE(res);
  20248. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20249. EXPECT_FALSE(client.is_open());
  20250. }
  20251. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20252. // The socket path doubles as the URL host, so it must not contain '/'.
  20253. const char *shard = getenv("GTEST_SHARD_INDEX");
  20254. const std::string sock_path =
  20255. shard ? std::string("httplib-ws-") + shard + ".sock"
  20256. : std::string("httplib-ws.sock");
  20257. std::remove(sock_path.c_str());
  20258. Server svr;
  20259. std::mutex mtx;
  20260. std::string received_host;
  20261. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20262. {
  20263. std::lock_guard<std::mutex> lock(mtx);
  20264. received_host = req.get_header_value("Host");
  20265. }
  20266. std::string msg;
  20267. while (ws.read(msg)) {
  20268. ws.send(msg);
  20269. }
  20270. });
  20271. svr.set_address_family(AF_UNIX);
  20272. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20273. auto se = detail::scope_exit([&] {
  20274. svr.stop();
  20275. t.join();
  20276. std::remove(sock_path.c_str());
  20277. });
  20278. svr.wait_until_ready();
  20279. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20280. client.set_address_family(AF_UNIX);
  20281. ASSERT_TRUE(client.connect());
  20282. ASSERT_TRUE(client.send("hello"));
  20283. std::string msg;
  20284. ASSERT_TRUE(client.read(msg));
  20285. client.close();
  20286. {
  20287. std::lock_guard<std::mutex> lock(mtx);
  20288. // There is no host:port for a Unix socket, so the same "localhost"
  20289. // placeholder the HTTP client uses is expected.
  20290. EXPECT_EQ("localhost", received_host);
  20291. }
  20292. }
  20293. // Two threads must never parse WebSocket frames from the same stream.
  20294. // close() used to read the peer's Close reply with its own frame read, so it
  20295. // raced a reader thread that was in the middle of a payload: the payload loop
  20296. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20297. // so bytes taken by close() were replaced with bytes from further along the
  20298. // stream. The message kept its length and silently changed content.
  20299. //
  20300. // The raw peer below sends a frame header plus part of the payload, waits for
  20301. // the handler to call close(), and only then sends the rest. Whichever thread
  20302. // would win the race for those bytes, the message must arrive intact, because
  20303. // close() must not touch the stream while read() owns it.
  20304. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20305. #ifndef _WIN32
  20306. signal(SIGPIPE, SIG_IGN);
  20307. #endif
  20308. const size_t payload_len = 120; // fits the 7-bit length field
  20309. const size_t prefix_len = 8;
  20310. const int attempts = 8;
  20311. std::string expected(payload_len, '\0');
  20312. for (size_t i = 0; i < payload_len; i++) {
  20313. expected[i] = static_cast<char>('a' + i % 26);
  20314. }
  20315. std::atomic<bool> peer_stalled{false};
  20316. std::atomic<bool> handler_done{false};
  20317. std::mutex received_mutex;
  20318. std::vector<std::string> received;
  20319. // Bound every wait, so a regression fails the test instead of hanging the
  20320. // suite.
  20321. auto wait_for = [](const std::atomic<bool> &flag) {
  20322. for (int i = 0; i < 500 && !flag; i++) {
  20323. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20324. }
  20325. };
  20326. Server svr;
  20327. svr.set_websocket_ping_interval(0);
  20328. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20329. std::thread reader([&]() {
  20330. std::string msg;
  20331. while (ws.read(msg)) {
  20332. std::lock_guard<std::mutex> guard(received_mutex);
  20333. received.push_back(msg);
  20334. }
  20335. });
  20336. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20337. // inside read_websocket_frame() when close() runs.
  20338. wait_for(peer_stalled);
  20339. ws.close();
  20340. reader.join();
  20341. handler_done = true;
  20342. });
  20343. auto port = svr.bind_to_any_port("127.0.0.1");
  20344. std::thread t([&]() { svr.listen_after_bind(); });
  20345. auto se = detail::scope_exit([&] {
  20346. svr.stop();
  20347. t.join();
  20348. });
  20349. svr.wait_until_ready();
  20350. auto send_bytes = [](socket_t s, const std::string &data) {
  20351. #ifdef _WIN32
  20352. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20353. #else
  20354. auto n = ::send(s, data.data(), data.size(), 0);
  20355. #endif
  20356. return n == static_cast<decltype(n)>(data.size());
  20357. };
  20358. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20359. // Every length used here fits the 7-bit length field.
  20360. auto masked_header = [](uint8_t first_byte, size_t len) {
  20361. std::string h;
  20362. h += static_cast<char>(first_byte);
  20363. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20364. h.append(4, '\0'); // mask key
  20365. return h;
  20366. };
  20367. for (int attempt = 0; attempt < attempts; attempt++) {
  20368. peer_stalled = false;
  20369. handler_done = false;
  20370. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20371. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20372. auto se_sock = detail::scope_exit([&] {
  20373. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20374. });
  20375. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20376. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20377. sockaddr_in addr{};
  20378. addr.sin_family = AF_INET;
  20379. addr.sin_port = htons(static_cast<uint16_t>(port));
  20380. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20381. ASSERT_EQ(
  20382. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20383. << "attempt " << attempt;
  20384. ASSERT_TRUE(send_bytes(sock,
  20385. "GET /ws HTTP/1.1\r\n"
  20386. "Host: 127.0.0.1\r\n"
  20387. "Upgrade: websocket\r\n"
  20388. "Connection: Upgrade\r\n"
  20389. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20390. "Sec-WebSocket-Version: 13\r\n"
  20391. "\r\n"))
  20392. << "attempt " << attempt;
  20393. std::string response;
  20394. while (response.find("\r\n\r\n") == std::string::npos) {
  20395. char buf[512];
  20396. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20397. if (n <= 0) { break; }
  20398. response.append(buf, static_cast<size_t>(n));
  20399. }
  20400. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20401. << "attempt " << attempt;
  20402. // Send the header of a Binary message but only the first prefix_len bytes
  20403. // of its payload, leaving the reader thread stalled inside the payload.
  20404. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20405. expected.substr(0, prefix_len)))
  20406. << "attempt " << attempt;
  20407. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20408. peer_stalled = true;
  20409. // Let close() send its Close frame and park in its own read before the
  20410. // rest of the payload arrives, so both threads are waiting for it.
  20411. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20412. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20413. close_frame += static_cast<char>(0x03); // status 1000
  20414. close_frame += static_cast<char>(0xE8);
  20415. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20416. << "attempt " << attempt;
  20417. // Closing the peer releases the reader thread even on the buggy path,
  20418. // where it waits for bytes another thread already consumed.
  20419. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20420. detail::close_socket(sock);
  20421. sock = INVALID_SOCKET;
  20422. wait_for(handler_done);
  20423. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20424. }
  20425. std::lock_guard<std::mutex> guard(received_mutex);
  20426. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20427. << "a message in flight when close() ran was dropped";
  20428. for (size_t i = 0; i < received.size(); i++) {
  20429. EXPECT_EQ(expected, received[i]) << "message " << i;
  20430. }
  20431. }
  20432. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20433. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20434. protected:
  20435. void SetUp() override {
  20436. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20437. SERVER_PRIVATE_KEY_FILE);
  20438. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20439. std::string msg;
  20440. ws::ReadResult ret;
  20441. while ((ret = ws.read(msg))) {
  20442. if (ret == ws::Binary) {
  20443. ws.send(msg.data(), msg.size());
  20444. } else {
  20445. ws.send(msg);
  20446. }
  20447. }
  20448. });
  20449. port_ = server_->bind_to_any_port(HOST);
  20450. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20451. server_->wait_until_ready();
  20452. }
  20453. void TearDown() override {
  20454. server_->stop();
  20455. if (server_thread_.joinable()) { server_thread_.join(); }
  20456. }
  20457. std::unique_ptr<SSLServer> server_;
  20458. std::thread server_thread_;
  20459. int port_ = 0;
  20460. };
  20461. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20462. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20463. "/ws-echo");
  20464. client.enable_server_certificate_verification(false);
  20465. ASSERT_TRUE(client.connect());
  20466. ASSERT_TRUE(client.is_open());
  20467. ASSERT_TRUE(client.send("Hello WSS"));
  20468. std::string msg;
  20469. EXPECT_EQ(ws::Text, client.read(msg));
  20470. EXPECT_EQ("Hello WSS", msg);
  20471. client.close();
  20472. }
  20473. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20474. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20475. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20476. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20477. // client (without calling close() first) is the only path that runs
  20478. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20479. // bug exactly.
  20480. //
  20481. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20482. // when linked against an instrumented libssl; run under Valgrind to catch it
  20483. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20484. // suite (the freed session otherwise stalls on the close handshake) — this test
  20485. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20486. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20487. {
  20488. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20489. "/ws-echo");
  20490. client.enable_server_certificate_verification(false);
  20491. client.set_read_timeout(2, 0);
  20492. client.set_write_timeout(2, 0);
  20493. ASSERT_TRUE(client.connect());
  20494. ASSERT_TRUE(client.is_open());
  20495. ASSERT_TRUE(client.send("still open"));
  20496. // Intentionally do NOT call client.close(): leaving scope runs
  20497. // shutdown_and_close() with the WebSocket still open, which must send the
  20498. // close frame while the TLS session is still alive.
  20499. }
  20500. }
  20501. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20502. // shutdown_and_close() at the start of connect(), reproducing the same
  20503. // use-after-free within the test body rather than at scope exit. The second
  20504. // connect must succeed and echo, proving the close handshake ran over a live
  20505. // session. See the note above about memory-tool requirements.
  20506. TEST_F(WebSocketSSLIntegrationTest,
  20507. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20508. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20509. "/ws-echo");
  20510. client.enable_server_certificate_verification(false);
  20511. client.set_read_timeout(2, 0);
  20512. client.set_write_timeout(2, 0);
  20513. ASSERT_TRUE(client.connect());
  20514. ASSERT_TRUE(client.is_open());
  20515. ASSERT_TRUE(client.send("still open"));
  20516. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20517. // the still-open connection, which must not touch a freed TLS session.
  20518. ASSERT_TRUE(client.connect());
  20519. ASSERT_TRUE(client.is_open());
  20520. ASSERT_TRUE(client.send("after reconnect"));
  20521. std::string msg;
  20522. EXPECT_EQ(ws::Text, client.read(msg));
  20523. EXPECT_EQ("after reconnect", msg);
  20524. client.close();
  20525. }
  20526. #endif
  20527. #ifdef CPPHTTPLIB_SSL_ENABLED
  20528. class WebSocketSSLCATest : public ::testing::Test {
  20529. protected:
  20530. void SetUp() override {
  20531. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20532. SERVER_PRIVATE_KEY_FILE);
  20533. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20534. std::string msg;
  20535. while (ws.read(msg)) {
  20536. ws.send(msg);
  20537. }
  20538. });
  20539. port_ = server_->bind_to_any_port("127.0.0.1");
  20540. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20541. server_->wait_until_ready();
  20542. }
  20543. void TearDown() override {
  20544. server_->stop();
  20545. if (server_thread_.joinable()) { server_thread_.join(); }
  20546. }
  20547. std::string url() const {
  20548. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20549. }
  20550. std::unique_ptr<SSLServer> server_;
  20551. std::thread server_thread_;
  20552. int port_ = 0;
  20553. };
  20554. // A custom CA loaded as PEM verifies the server with full certificate
  20555. // verification enabled
  20556. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20557. ws::WebSocketClient client(url());
  20558. std::string cert;
  20559. read_file(SERVER_CERT2_FILE, cert);
  20560. client.load_ca_cert_store(cert.c_str(), cert.size());
  20561. ASSERT_TRUE(client.connect());
  20562. ASSERT_TRUE(client.send("hello"));
  20563. std::string msg;
  20564. EXPECT_EQ(ws::Text, client.read(msg));
  20565. EXPECT_EQ("hello", msg);
  20566. client.close();
  20567. }
  20568. // A custom CA that does not cover the server must fail verification (the
  20569. // custom CA is exclusive; system certs are not loaded alongside it)
  20570. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20571. ws::WebSocketClient client(url());
  20572. std::string cert;
  20573. read_file(CLIENT_CA_CERT_FILE, cert);
  20574. client.load_ca_cert_store(cert.c_str(), cert.size());
  20575. auto res = client.connect();
  20576. ASSERT_FALSE(res);
  20577. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20578. EXPECT_EQ(-1, res.status());
  20579. EXPECT_NE(0u, res.ssl_backend_error());
  20580. }
  20581. // The same CA as a file path rather than PEM in memory
  20582. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20583. ws::WebSocketClient client(url());
  20584. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20585. ASSERT_TRUE(client.connect());
  20586. ASSERT_TRUE(client.send("hello"));
  20587. std::string msg;
  20588. EXPECT_EQ(ws::Text, client.read(msg));
  20589. EXPECT_EQ("hello", msg);
  20590. client.close();
  20591. }
  20592. // ...and a CA file that does not cover the server still fails, so it is the
  20593. // path above that decides the outcome
  20594. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20595. ws::WebSocketClient client(url());
  20596. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20597. ASSERT_FALSE(client.connect());
  20598. }
  20599. // Regression test: reconnecting with a native custom CA store used to reuse
  20600. // a store handle the previous TLS context had already freed (use-after-free
  20601. // under the OpenSSL backend). The context now lives as long as the client.
  20602. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20603. ws::WebSocketClient client(url());
  20604. std::string cert;
  20605. read_file(SERVER_CERT2_FILE, cert);
  20606. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20607. ASSERT_TRUE(client.connect());
  20608. client.close();
  20609. ASSERT_TRUE(client.connect());
  20610. ASSERT_TRUE(client.send("again"));
  20611. std::string msg;
  20612. EXPECT_EQ(ws::Text, client.read(msg));
  20613. EXPECT_EQ("again", msg);
  20614. client.close();
  20615. }
  20616. // Regression test: a certificate with a trusted chain but no identity match
  20617. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20618. // verification entirely for IP hosts, so this connection succeeded there.
  20619. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20620. // chain verification while the identity check must still fail.
  20621. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20623. ASSERT_TRUE(svr.is_valid());
  20624. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20625. std::string msg;
  20626. while (ws.read(msg)) {
  20627. ws.send(msg);
  20628. }
  20629. });
  20630. auto port = svr.bind_to_any_port("127.0.0.1");
  20631. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20632. auto se = detail::scope_exit([&] {
  20633. svr.stop();
  20634. t.join();
  20635. });
  20636. svr.wait_until_ready();
  20637. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20638. "/echo");
  20639. std::string cert;
  20640. read_file(SERVER_CERT_FILE, cert);
  20641. client.load_ca_cert_store(cert.c_str(), cert.size());
  20642. ASSERT_FALSE(client.connect());
  20643. }
  20644. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20645. // SNI, so nothing binds the host name to the TLS session. These bind the
  20646. // server to "localhost" instead, the only shape that exercises the SNI and
  20647. // hostname-verification path with certificate verification left enabled.
  20648. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20649. protected:
  20650. void Start(const char *cert_file) {
  20651. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20652. SERVER_PRIVATE_KEY_FILE);
  20653. ASSERT_TRUE(server_->is_valid());
  20654. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20655. std::string msg;
  20656. while (ws.read(msg)) {
  20657. ws.send(msg);
  20658. }
  20659. });
  20660. port_ = server_->bind_to_any_port("localhost");
  20661. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20662. server_->wait_until_ready();
  20663. }
  20664. void TearDown() override {
  20665. if (server_) { server_->stop(); }
  20666. if (server_thread_.joinable()) { server_thread_.join(); }
  20667. }
  20668. std::string url() const {
  20669. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20670. }
  20671. std::unique_ptr<SSLServer> server_;
  20672. std::thread server_thread_;
  20673. int port_ = 0;
  20674. };
  20675. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20676. // out and the connection is usable
  20677. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20678. Start(SERVER_CERT2_FILE);
  20679. ws::WebSocketClient client(url());
  20680. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20681. ASSERT_TRUE(client.connect());
  20682. ASSERT_TRUE(client.send("hello"));
  20683. std::string msg;
  20684. EXPECT_EQ(ws::Text, client.read(msg));
  20685. EXPECT_EQ("hello", msg);
  20686. client.close();
  20687. }
  20688. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20689. // while the identity check must still reject "localhost"
  20690. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20691. Start(SERVER_CERT_FILE);
  20692. ws::WebSocketClient client(url());
  20693. client.set_ca_cert_path(SERVER_CERT_FILE);
  20694. auto res = client.connect();
  20695. ASSERT_FALSE(res);
  20696. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20697. EXPECT_EQ(-1, res.status());
  20698. }
  20699. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20700. // disabled: the chain is still checked, only the identity check is skipped
  20701. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20702. Start(SERVER_CERT_FILE);
  20703. ws::WebSocketClient client(url());
  20704. client.set_ca_cert_path(SERVER_CERT_FILE);
  20705. client.enable_server_hostname_verification(false);
  20706. ASSERT_TRUE(client.connect());
  20707. ASSERT_TRUE(client.send("hello"));
  20708. std::string msg;
  20709. EXPECT_EQ(ws::Text, client.read(msg));
  20710. EXPECT_EQ("hello", msg);
  20711. client.close();
  20712. }
  20713. // A CA that did not sign the server certificate fails the chain, even though
  20714. // the name would match
  20715. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20716. Start(SERVER_CERT2_FILE);
  20717. ws::WebSocketClient client(url());
  20718. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20719. ASSERT_FALSE(client.connect());
  20720. }
  20721. // With verification disabled, neither the chain nor the name is checked
  20722. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  20723. Start(SERVER_CERT_FILE);
  20724. ws::WebSocketClient client(url());
  20725. client.enable_server_certificate_verification(false);
  20726. ASSERT_TRUE(client.connect());
  20727. ASSERT_TRUE(client.send("hello"));
  20728. std::string msg;
  20729. EXPECT_EQ(ws::Text, client.read(msg));
  20730. EXPECT_EQ("hello", msg);
  20731. client.close();
  20732. }
  20733. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20734. protected:
  20735. void SetUp() override {
  20736. server_ = httplib::detail::make_unique<SSLServer>(
  20737. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20738. ASSERT_TRUE(server_->is_valid());
  20739. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20740. std::string msg;
  20741. while (ws.read(msg)) {
  20742. ws.send(msg);
  20743. }
  20744. });
  20745. port_ = server_->bind_to_any_port("localhost");
  20746. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20747. server_->wait_until_ready();
  20748. }
  20749. void TearDown() override {
  20750. server_->stop();
  20751. if (server_thread_.joinable()) { server_thread_.join(); }
  20752. }
  20753. std::string url() const {
  20754. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  20755. }
  20756. void ConnectWithClientCert(const std::string &client_cert_file,
  20757. const std::string &client_private_key_file,
  20758. const char *private_key_password) {
  20759. std::string cert_pem, key_pem;
  20760. read_file(client_cert_file, cert_pem);
  20761. read_file(client_private_key_file, key_pem);
  20762. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20763. key_pem.c_str(), key_pem.size(),
  20764. private_key_password};
  20765. ws::WebSocketClient client(url(), pem);
  20766. ASSERT_TRUE(client.is_valid());
  20767. client.enable_server_certificate_verification(false);
  20768. ASSERT_TRUE(client.connect());
  20769. ASSERT_TRUE(client.send("hello"));
  20770. std::string msg;
  20771. EXPECT_EQ(ws::Text, client.read(msg));
  20772. EXPECT_EQ("hello", msg);
  20773. client.close();
  20774. }
  20775. std::unique_ptr<SSLServer> server_;
  20776. std::thread server_thread_;
  20777. int port_ = 0;
  20778. };
  20779. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  20780. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  20781. }
  20782. // Control for the tests above: the fixture's server really does require a
  20783. // client certificate, so it is the PEM the constructor installed that decides
  20784. // the outcome.
  20785. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  20786. ws::WebSocketClient client(url());
  20787. ASSERT_TRUE(client.is_valid());
  20788. client.enable_server_certificate_verification(false);
  20789. EXPECT_FALSE(client.connect());
  20790. }
  20791. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  20792. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  20793. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  20794. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  20795. }
  20796. #endif
  20797. #if !defined(_WIN32)
  20798. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  20799. auto secret_dir = std::string("./symlink_test_secret");
  20800. auto served_dir = std::string("./symlink_test_served");
  20801. auto secret_file = secret_dir + "/secret.txt";
  20802. auto symlink_path = served_dir + "/escape";
  20803. // Setup: create directories and files
  20804. mkdir(secret_dir.c_str(), 0755);
  20805. mkdir(served_dir.c_str(), 0755);
  20806. {
  20807. std::ofstream ofs(secret_file);
  20808. ofs << "SECRET_DATA";
  20809. }
  20810. // Create symlink using absolute path so it resolves correctly
  20811. #ifdef PATH_MAX
  20812. char abs_secret[PATH_MAX];
  20813. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  20814. #else
  20815. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  20816. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  20817. ASSERT_NE(nullptr, abs_secret);
  20818. #endif
  20819. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  20820. auto se = detail::scope_exit([&] {
  20821. unlink(symlink_path.c_str());
  20822. unlink(secret_file.c_str());
  20823. rmdir(served_dir.c_str());
  20824. rmdir(secret_dir.c_str());
  20825. });
  20826. Server svr;
  20827. svr.set_mount_point("/", served_dir);
  20828. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  20829. auto se2 = detail::scope_exit([&] {
  20830. svr.stop();
  20831. listen_thread.join();
  20832. });
  20833. svr.wait_until_ready();
  20834. Client cli("localhost", PORT);
  20835. // Symlink pointing outside base dir should be blocked
  20836. auto res = cli.Get("/escape/secret.txt");
  20837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20838. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  20839. }
  20840. #endif
  20841. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  20842. // A GET request with Content-Length to a static file handler must have its
  20843. // body drained before the keep-alive connection is reused. Otherwise the
  20844. // unread body bytes are interpreted as the next HTTP request.
  20845. //
  20846. // The body is sent AFTER receiving the first response (as in the original
  20847. // PoC) so that the stream_line_reader cannot buffer it together with the
  20848. // headers of the first request.
  20849. Server svr;
  20850. svr.set_mount_point("/", "./www");
  20851. std::atomic<int> smuggled_count(0);
  20852. svr.Get("/smuggled", [&](const Request &, Response &res) {
  20853. smuggled_count++;
  20854. res.set_content("oops", "text/plain");
  20855. });
  20856. auto port = svr.bind_to_any_port("localhost");
  20857. thread t = thread([&] { svr.listen_after_bind(); });
  20858. auto se = detail::scope_exit([&] {
  20859. svr.stop();
  20860. t.join();
  20861. });
  20862. svr.wait_until_ready();
  20863. auto error = Error::Success;
  20864. auto sock = detail::create_client_socket(
  20865. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  20866. /*connection_timeout_sec=*/2, 0,
  20867. /*read_timeout_sec=*/2, 0,
  20868. /*write_timeout_sec=*/2, 0, std::string(), error);
  20869. ASSERT_NE(INVALID_SOCKET, sock);
  20870. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20871. // The "smuggled" request will be sent as the body of the outer GET
  20872. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  20873. "Host: localhost\r\n"
  20874. "Connection: close\r\n"
  20875. "\r\n";
  20876. // Step 1: Send only the outer request headers (no body yet)
  20877. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  20878. "Host: localhost\r\n"
  20879. "Content-Length: " +
  20880. std::to_string(smuggled.size()) +
  20881. "\r\n"
  20882. "\r\n";
  20883. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  20884. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  20885. // Step 2: Read the first response (server serves file without reading body)
  20886. std::string first_response;
  20887. char buf[4096];
  20888. for (;;) {
  20889. auto n = recv(sock, buf, sizeof(buf), 0);
  20890. if (n <= 0) break;
  20891. first_response.append(buf, static_cast<size_t>(n));
  20892. // Stop once we have a complete response (headers + body)
  20893. auto hdr_end = first_response.find("\r\n\r\n");
  20894. if (hdr_end != std::string::npos) {
  20895. // Check for Content-Length to know when the body is complete
  20896. auto cl_pos = first_response.find("Content-Length:");
  20897. if (cl_pos != std::string::npos) {
  20898. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  20899. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  20900. auto cl = std::stoul(
  20901. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  20902. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  20903. } else {
  20904. break; // No Content-Length, assume headers-only response
  20905. }
  20906. }
  20907. }
  20908. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  20909. // Step 3: Now send the body, which looks like a new HTTP request.
  20910. // On a vulnerable server the keep-alive loop reads this as a second request.
  20911. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  20912. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  20913. // Step 4: Try to read a second response (should NOT exist after fix)
  20914. std::string second_response;
  20915. for (;;) {
  20916. auto n = recv(sock, buf, sizeof(buf), 0);
  20917. if (n <= 0) break;
  20918. second_response.append(buf, static_cast<size_t>(n));
  20919. }
  20920. // The smuggled request must NOT have been processed
  20921. EXPECT_EQ(0, smuggled_count.load());
  20922. }
  20923. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20924. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  20925. // must be rejected with 400 Bad Request.
  20926. Server svr;
  20927. svr.Post("/test", [&](const Request &, Response &res) {
  20928. res.set_content("ok", "text/plain");
  20929. });
  20930. thread t = thread([&] { svr.listen(HOST, PORT); });
  20931. auto se = detail::scope_exit([&] {
  20932. svr.stop();
  20933. t.join();
  20934. ASSERT_FALSE(svr.is_running());
  20935. });
  20936. svr.wait_until_ready();
  20937. // Exact "chunked"
  20938. {
  20939. auto req = "POST /test HTTP/1.1\r\n"
  20940. "Host: localhost\r\n"
  20941. "Content-Length: 5\r\n"
  20942. "Transfer-Encoding: chunked\r\n"
  20943. "Connection: close\r\n"
  20944. "\r\n"
  20945. "hello";
  20946. std::string response;
  20947. ASSERT_TRUE(send_request(1, req, &response));
  20948. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20949. response.substr(0, response.find("\r\n")));
  20950. }
  20951. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  20952. {
  20953. auto req = "POST /test HTTP/1.1\r\n"
  20954. "Host: localhost\r\n"
  20955. "Content-Length: 5\r\n"
  20956. "Transfer-Encoding: gzip, chunked\r\n"
  20957. "Connection: close\r\n"
  20958. "\r\n"
  20959. "hello";
  20960. std::string response;
  20961. ASSERT_TRUE(send_request(1, req, &response));
  20962. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20963. response.substr(0, response.find("\r\n")));
  20964. }
  20965. }
  20966. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  20967. Server svr;
  20968. svr.Post("/test", [&](const Request &, Response &res) {
  20969. res.set_content("ok", "text/plain");
  20970. });
  20971. thread t = thread([&] { svr.listen(HOST, PORT); });
  20972. auto se = detail::scope_exit([&] {
  20973. svr.stop();
  20974. t.join();
  20975. ASSERT_FALSE(svr.is_running());
  20976. });
  20977. svr.wait_until_ready();
  20978. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  20979. // length cannot be determined, so the server must answer 400 and close
  20980. // rather than treat the request as bodyless and leave the body in the
  20981. // socket for the next request to pick up.
  20982. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  20983. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  20984. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  20985. std::string response;
  20986. ASSERT_TRUE(send_request(1, req, &response));
  20987. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20988. response.substr(0, response.find("\r\n")))
  20989. << transfer_encoding;
  20990. }
  20991. // RFC 9110 5.3: the codings may also be split across several
  20992. // Transfer-Encoding lines, which combine in the order they were received.
  20993. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  20994. // just like the single-line "chunked, gzip" above.
  20995. {
  20996. auto req = "POST /test HTTP/1.1\r\n"
  20997. "Host: localhost\r\n"
  20998. "Transfer-Encoding: chunked\r\n"
  20999. "Transfer-Encoding: gzip\r\n"
  21000. "\r\n"
  21001. "0\r\n\r\n";
  21002. std::string response;
  21003. ASSERT_TRUE(send_request(1, req, &response));
  21004. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21005. response.substr(0, response.find("\r\n")));
  21006. }
  21007. // A sequence ending in chunked stays valid.
  21008. auto req = "POST /test HTTP/1.1\r\n"
  21009. "Host: localhost\r\n"
  21010. "Transfer-Encoding: gzip, chunked\r\n"
  21011. "Connection: close\r\n"
  21012. "\r\n"
  21013. "0\r\n\r\n";
  21014. std::string response;
  21015. ASSERT_TRUE(send_request(1, req, &response));
  21016. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21017. // ...including when it is spread over several lines.
  21018. auto split_req = "POST /test HTTP/1.1\r\n"
  21019. "Host: localhost\r\n"
  21020. "Transfer-Encoding: gzip\r\n"
  21021. "Transfer-Encoding: chunked\r\n"
  21022. "Connection: close\r\n"
  21023. "\r\n"
  21024. "0\r\n\r\n";
  21025. std::string split_response;
  21026. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21027. EXPECT_EQ("HTTP/1.1 200 OK",
  21028. split_response.substr(0, split_response.find("\r\n")));
  21029. }
  21030. // Regression for issue #2450: a DELETE without Content-Length on a
  21031. // keep-alive connection must not let the post-response drain consume the
  21032. // next request's bytes.
  21033. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21034. Server svr;
  21035. std::atomic<int> delete_count(0);
  21036. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21037. delete_count++;
  21038. res.status = StatusCode::NoContent_204;
  21039. });
  21040. auto port = svr.bind_to_any_port(HOST);
  21041. thread t = thread([&] { svr.listen_after_bind(); });
  21042. auto se = detail::scope_exit([&] {
  21043. svr.stop();
  21044. t.join();
  21045. });
  21046. svr.wait_until_ready();
  21047. auto error = Error::Success;
  21048. auto sock = detail::create_client_socket(
  21049. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21050. /*connection_timeout_sec=*/2, 0,
  21051. /*read_timeout_sec=*/2, 0,
  21052. /*write_timeout_sec=*/2, 0, std::string(), error);
  21053. ASSERT_NE(INVALID_SOCKET, sock);
  21054. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21055. auto send_request_and_read_response = [&](const std::string &req,
  21056. std::string &out) -> bool {
  21057. auto sent = send(sock, req.data(), req.size(), 0);
  21058. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21059. char buf[4096];
  21060. for (;;) {
  21061. auto n = recv(sock, buf, sizeof(buf), 0);
  21062. if (n <= 0) { return !out.empty(); }
  21063. out.append(buf, static_cast<size_t>(n));
  21064. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21065. }
  21066. };
  21067. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21068. "Host: localhost\r\n"
  21069. "\r\n";
  21070. std::string resp1;
  21071. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21072. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21073. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21074. "Host: localhost\r\n"
  21075. "Connection: close\r\n"
  21076. "\r\n";
  21077. std::string resp2;
  21078. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21079. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21080. EXPECT_EQ(2, delete_count.load());
  21081. }
  21082. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21083. Server svr;
  21084. svr.Post("/ingest", [&](const Request &, Response &res,
  21085. const ContentReader &content_reader) {
  21086. auto consumed = content_reader([](const char *, size_t) { return false; });
  21087. EXPECT_FALSE(consumed);
  21088. res.status = StatusCode::Conflict_409;
  21089. res.set_header("Connection", "close");
  21090. });
  21091. auto port = svr.bind_to_any_port(HOST);
  21092. thread t = thread([&] { svr.listen_after_bind(); });
  21093. auto se = detail::scope_exit([&] {
  21094. svr.stop();
  21095. t.join();
  21096. });
  21097. svr.wait_until_ready();
  21098. auto error = Error::Success;
  21099. auto sock = detail::create_client_socket(
  21100. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21101. /*connection_timeout_sec=*/2, 0,
  21102. /*read_timeout_sec=*/1, 0,
  21103. /*write_timeout_sec=*/2, 0, std::string(), error);
  21104. ASSERT_NE(INVALID_SOCKET, sock);
  21105. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21106. std::string request = "POST /ingest HTTP/1.1\r\n"
  21107. "Host: localhost\r\n"
  21108. "Transfer-Encoding: chunked\r\n"
  21109. "\r\n"
  21110. "4\r\n"
  21111. "data\r\n";
  21112. auto sent = send(sock, request.data(), request.size(), 0);
  21113. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21114. std::string response;
  21115. ssize_t received = 0;
  21116. do {
  21117. char buf[4096];
  21118. received = recv(sock, buf, sizeof(buf), 0);
  21119. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21120. } while (received > 0);
  21121. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21122. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21123. EXPECT_EQ(0, received);
  21124. }
  21125. namespace no_proxy_test {
  21126. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21127. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21128. // calling listen().
  21129. class ScopedServer {
  21130. public:
  21131. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21132. ~ScopedServer() {
  21133. svr_.stop();
  21134. if (th_.joinable()) { th_.join(); }
  21135. }
  21136. Server &svr() { return svr_; }
  21137. int port() const { return port_; }
  21138. void listen() {
  21139. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21140. svr_.wait_until_ready();
  21141. }
  21142. private:
  21143. Server svr_;
  21144. std::thread th_;
  21145. int port_ = 0;
  21146. };
  21147. class ProxyAndTargetServers {
  21148. public:
  21149. ProxyAndTargetServers() {
  21150. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21151. proxy_hits_++;
  21152. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21153. res.set_content("via-proxy", "text/plain");
  21154. });
  21155. target_.Get(".*", [this](const Request &req, Response &res) {
  21156. target_hits_++;
  21157. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21158. res.set_content("direct", "text/plain");
  21159. });
  21160. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21161. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21162. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21163. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21164. proxy_mock_.wait_until_ready();
  21165. target_.wait_until_ready();
  21166. }
  21167. ~ProxyAndTargetServers() {
  21168. proxy_mock_.stop();
  21169. target_.stop();
  21170. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21171. if (target_thread_.joinable()) { target_thread_.join(); }
  21172. }
  21173. Server &proxy_mock() { return proxy_mock_; }
  21174. Server &target() { return target_; }
  21175. int proxy_port() const { return proxy_port_; }
  21176. int target_port() const { return target_port_; }
  21177. int proxy_hits() const { return proxy_hits_.load(); }
  21178. int target_hits() const { return target_hits_.load(); }
  21179. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21180. void reset_counters() {
  21181. proxy_hits_ = 0;
  21182. target_hits_ = 0;
  21183. last_had_proxy_authz_ = false;
  21184. }
  21185. private:
  21186. Server proxy_mock_;
  21187. Server target_;
  21188. std::thread proxy_thread_;
  21189. std::thread target_thread_;
  21190. int proxy_port_ = 0;
  21191. int target_port_ = 0;
  21192. std::atomic<int> proxy_hits_{0};
  21193. std::atomic<int> target_hits_{0};
  21194. std::atomic<bool> last_had_proxy_authz_{false};
  21195. };
  21196. inline std::unique_ptr<Client> make_client(const std::string &host,
  21197. ProxyAndTargetServers &s) {
  21198. auto cli = detail::make_unique<Client>(host, s.target_port());
  21199. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21200. cli->set_proxy("127.0.0.1", s.proxy_port());
  21201. return cli;
  21202. }
  21203. } // namespace no_proxy_test
  21204. using no_proxy_test::make_client;
  21205. using no_proxy_test::ProxyAndTargetServers;
  21206. TEST(NoProxyTest, ExactHostnameBypasses) {
  21207. ProxyAndTargetServers s;
  21208. auto cli = make_client("example.com", s);
  21209. cli->set_no_proxy({"example.com"});
  21210. auto res = cli->Get("/");
  21211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21212. EXPECT_EQ(0, s.proxy_hits());
  21213. EXPECT_EQ(1, s.target_hits());
  21214. }
  21215. TEST(NoProxyTest, SubdomainBypasses) {
  21216. ProxyAndTargetServers s;
  21217. auto cli = make_client("foo.example.com", s);
  21218. cli->set_no_proxy({"example.com"});
  21219. auto res = cli->Get("/");
  21220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21221. EXPECT_EQ(0, s.proxy_hits());
  21222. EXPECT_EQ(1, s.target_hits());
  21223. }
  21224. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21225. // Regression guard: "evilexample.com" must not be considered a subdomain
  21226. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21227. // check would let traffic bypass the proxy and leak credentials direct
  21228. // to the attacker host.
  21229. ProxyAndTargetServers s;
  21230. auto cli = make_client("evilexample.com", s);
  21231. cli->set_no_proxy({"example.com"});
  21232. auto res = cli->Get("/");
  21233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21234. EXPECT_GE(s.proxy_hits(), 1);
  21235. EXPECT_EQ(0, s.target_hits());
  21236. }
  21237. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21238. ProxyAndTargetServers s;
  21239. auto cli = make_client("example.com.evil.com", s);
  21240. cli->set_no_proxy({"example.com"});
  21241. auto res = cli->Get("/");
  21242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21243. EXPECT_GE(s.proxy_hits(), 1);
  21244. EXPECT_EQ(0, s.target_hits());
  21245. }
  21246. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21247. ProxyAndTargetServers s;
  21248. auto cli = make_client("example.com", s);
  21249. cli->set_no_proxy({".example.com"});
  21250. auto res = cli->Get("/");
  21251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21252. EXPECT_EQ(0, s.proxy_hits());
  21253. EXPECT_EQ(1, s.target_hits());
  21254. }
  21255. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21256. ProxyAndTargetServers s;
  21257. auto cli = make_client("Example.COM", s);
  21258. cli->set_no_proxy({"EXAMPLE.com"});
  21259. auto res = cli->Get("/");
  21260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21261. EXPECT_EQ(0, s.proxy_hits());
  21262. EXPECT_EQ(1, s.target_hits());
  21263. }
  21264. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21265. ProxyAndTargetServers s;
  21266. auto cli = make_client("example.com.", s);
  21267. cli->set_no_proxy({"example.com"});
  21268. auto res = cli->Get("/");
  21269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21270. EXPECT_EQ(0, s.proxy_hits());
  21271. EXPECT_EQ(1, s.target_hits());
  21272. }
  21273. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21274. // Trailing dots must be normalized on BOTH sides — host and entry.
  21275. // An implementation that only strips the host-side trailing dot would
  21276. // fail to match host "example.com" against entry "example.com." because
  21277. // a literal substring search would compare 11 chars against 12.
  21278. ProxyAndTargetServers s;
  21279. auto cli = make_client("example.com", s);
  21280. cli->set_no_proxy({"example.com."});
  21281. auto res = cli->Get("/");
  21282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21283. EXPECT_EQ(0, s.proxy_hits());
  21284. EXPECT_EQ(1, s.target_hits());
  21285. }
  21286. TEST(NoProxyTest, WildcardBypassesEverything) {
  21287. ProxyAndTargetServers s;
  21288. auto cli = make_client("anything.invalid.test", s);
  21289. cli->set_no_proxy({"*"});
  21290. auto res = cli->Get("/");
  21291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21292. EXPECT_EQ(0, s.proxy_hits());
  21293. EXPECT_EQ(1, s.target_hits());
  21294. }
  21295. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21296. ProxyAndTargetServers s;
  21297. Client cli("127.0.0.1", s.target_port());
  21298. cli.set_proxy("127.0.0.1", s.proxy_port());
  21299. cli.set_no_proxy({"127.0.0.1"});
  21300. auto res = cli.Get("/");
  21301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21302. EXPECT_EQ(0, s.proxy_hits());
  21303. EXPECT_EQ(1, s.target_hits());
  21304. }
  21305. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21306. ProxyAndTargetServers s;
  21307. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21308. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21309. cli.set_proxy("127.0.0.1", s.proxy_port());
  21310. cli.set_no_proxy({"::1"});
  21311. auto res = cli.Get("/");
  21312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21313. EXPECT_EQ(0, s.proxy_hits());
  21314. EXPECT_EQ(1, s.target_hits());
  21315. }
  21316. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21317. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21318. // must still be recognized as IPv6 for CIDR matching. Implementations
  21319. // that detect IPv6 only when the host begins with '[' would parse the
  21320. // host as a hostname and miss the match.
  21321. ProxyAndTargetServers s;
  21322. Client cli("fe80::1", s.target_port());
  21323. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21324. cli.set_proxy("127.0.0.1", s.proxy_port());
  21325. cli.set_no_proxy({"fe80::/10"});
  21326. auto res = cli.Get("/");
  21327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21328. EXPECT_EQ(0, s.proxy_hits());
  21329. EXPECT_EQ(1, s.target_hits());
  21330. }
  21331. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21332. ProxyAndTargetServers s;
  21333. Client cli("::1", s.target_port());
  21334. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21335. cli.set_proxy("127.0.0.1", s.proxy_port());
  21336. cli.set_no_proxy({"[::1]"});
  21337. auto res = cli.Get("/");
  21338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21339. EXPECT_EQ(0, s.proxy_hits());
  21340. EXPECT_EQ(1, s.target_hits());
  21341. }
  21342. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21343. ProxyAndTargetServers s;
  21344. Client cli("fe80::1", s.target_port());
  21345. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21346. cli.set_proxy("127.0.0.1", s.proxy_port());
  21347. cli.set_no_proxy({"[fe80::]/10"});
  21348. auto res = cli.Get("/");
  21349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21350. EXPECT_EQ(0, s.proxy_hits());
  21351. EXPECT_EQ(1, s.target_hits());
  21352. }
  21353. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21354. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21355. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21356. // tricks via address-family conversion.
  21357. ProxyAndTargetServers s;
  21358. Client cli("::ffff:127.0.0.1", s.target_port());
  21359. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21360. cli.set_proxy("127.0.0.1", s.proxy_port());
  21361. cli.set_no_proxy({"127.0.0.1"});
  21362. auto res = cli.Get("/");
  21363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21364. EXPECT_GE(s.proxy_hits(), 1);
  21365. EXPECT_EQ(0, s.target_hits());
  21366. }
  21367. TEST(NoProxyTest, IPv4CidrMatch) {
  21368. ProxyAndTargetServers s;
  21369. Client cli("127.0.0.1", s.target_port());
  21370. cli.set_proxy("127.0.0.1", s.proxy_port());
  21371. cli.set_no_proxy({"127.0.0.0/8"});
  21372. auto res = cli.Get("/");
  21373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21374. EXPECT_EQ(0, s.proxy_hits());
  21375. EXPECT_EQ(1, s.target_hits());
  21376. }
  21377. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21378. ProxyAndTargetServers s;
  21379. Client cli("127.0.0.1", s.target_port());
  21380. cli.set_proxy("127.0.0.1", s.proxy_port());
  21381. cli.set_no_proxy({"10.0.0.0/8"});
  21382. auto res = cli.Get("/");
  21383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21384. EXPECT_GE(s.proxy_hits(), 1);
  21385. EXPECT_EQ(0, s.target_hits());
  21386. }
  21387. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21388. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21389. // IPv4 target matches.
  21390. ProxyAndTargetServers s;
  21391. Client cli("127.0.0.1", s.target_port());
  21392. cli.set_proxy("127.0.0.1", s.proxy_port());
  21393. cli.set_no_proxy({"0.0.0.0/0"});
  21394. auto res = cli.Get("/");
  21395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21396. EXPECT_EQ(0, s.proxy_hits());
  21397. EXPECT_EQ(1, s.target_hits());
  21398. }
  21399. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21400. ProxyAndTargetServers s;
  21401. Client cli("127.0.0.1", s.target_port());
  21402. cli.set_proxy("127.0.0.1", s.proxy_port());
  21403. cli.set_no_proxy({"127.0.0.1"});
  21404. auto res = cli.Get("/");
  21405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21406. EXPECT_EQ(0, s.proxy_hits());
  21407. EXPECT_EQ(1, s.target_hits());
  21408. }
  21409. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21410. ProxyAndTargetServers s;
  21411. Client cli("127.0.0.1", s.target_port());
  21412. cli.set_proxy("127.0.0.1", s.proxy_port());
  21413. cli.set_no_proxy({"127.0.0.0/33"});
  21414. auto res = cli.Get("/");
  21415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21416. EXPECT_GE(s.proxy_hits(), 1);
  21417. EXPECT_EQ(0, s.target_hits());
  21418. }
  21419. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21420. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21421. ProxyAndTargetServers s;
  21422. Client cli("127.0.0.1", s.target_port());
  21423. cli.set_proxy("127.0.0.1", s.proxy_port());
  21424. cli.set_no_proxy({"127.0.0.1/"});
  21425. auto res = cli.Get("/");
  21426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21427. EXPECT_GE(s.proxy_hits(), 1);
  21428. EXPECT_EQ(0, s.target_hits());
  21429. }
  21430. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21431. ProxyAndTargetServers s;
  21432. auto cli = make_client("internal.corp", s);
  21433. cli->set_proxy_basic_auth("u", "p");
  21434. cli->set_no_proxy({"internal.corp"});
  21435. auto res = cli->Get("/");
  21436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21437. EXPECT_EQ(1, s.target_hits());
  21438. EXPECT_EQ(0, s.proxy_hits());
  21439. EXPECT_FALSE(s.last_had_proxy_authz())
  21440. << "Proxy-Authorization must not be sent direct to the target";
  21441. }
  21442. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21443. ProxyAndTargetServers s;
  21444. auto cli = make_client("public.example", s);
  21445. cli->set_proxy_basic_auth("u", "p");
  21446. cli->set_no_proxy({"internal.corp"}); // does not match
  21447. auto res = cli->Get("/");
  21448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21449. EXPECT_GE(s.proxy_hits(), 1);
  21450. EXPECT_TRUE(s.last_had_proxy_authz());
  21451. }
  21452. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21453. ProxyAndTargetServers s;
  21454. auto cli = make_client("anything.test", s);
  21455. auto res = cli->Get("/");
  21456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21457. EXPECT_GE(s.proxy_hits(), 1);
  21458. EXPECT_EQ(0, s.target_hits());
  21459. }
  21460. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21461. ProxyAndTargetServers s;
  21462. auto cli = make_client("example.com", s);
  21463. cli->set_no_proxy({"example.com:8080"});
  21464. auto res = cli->Get("/");
  21465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21466. EXPECT_GE(s.proxy_hits(), 1);
  21467. EXPECT_EQ(0, s.target_hits());
  21468. }
  21469. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21470. ProxyAndTargetServers s;
  21471. auto cli = make_client("anything.test", s);
  21472. cli->set_no_proxy({"", " ", "\t"});
  21473. auto res = cli->Get("/");
  21474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21475. EXPECT_GE(s.proxy_hits(), 1);
  21476. EXPECT_EQ(0, s.target_hits());
  21477. }
  21478. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21479. // An entry with leading/trailing whitespace must still match — env-style
  21480. // values are commonly pasted with stray spaces and an implementation
  21481. // that feeds the raw token directly to inet_pton would fail to match
  21482. // valid CIDRs because of the spaces.
  21483. ProxyAndTargetServers s;
  21484. Client cli("127.0.0.1", s.target_port());
  21485. cli.set_proxy("127.0.0.1", s.proxy_port());
  21486. cli.set_no_proxy({" 127.0.0.0/8 "});
  21487. auto res = cli.Get("/");
  21488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21489. EXPECT_EQ(0, s.proxy_hits());
  21490. EXPECT_EQ(1, s.target_hits());
  21491. }
  21492. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21493. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21494. // go direct and must NOT carry Proxy-Authorization.
  21495. std::atomic<int> proxy_hits{0};
  21496. std::atomic<int> target_hits{0};
  21497. std::atomic<bool> target_saw_authz{false};
  21498. no_proxy_test::ScopedServer proxy_mock, target;
  21499. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21500. proxy_hits++;
  21501. res.status = 302;
  21502. res.set_header("Location", "http://127.0.0.1:" +
  21503. std::to_string(target.port()) + "/landed");
  21504. });
  21505. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21506. target_hits++;
  21507. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21508. res.set_content("direct", "text/plain");
  21509. });
  21510. proxy_mock.listen();
  21511. target.listen();
  21512. Client cli("public.example", target.port());
  21513. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21514. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21515. cli.set_proxy_basic_auth("u", "p");
  21516. cli.set_no_proxy({"127.0.0.1"});
  21517. cli.set_follow_location(true);
  21518. auto res = cli.Get("/redir");
  21519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21520. EXPECT_GE(proxy_hits.load(), 1);
  21521. EXPECT_GE(target_hits.load(), 1);
  21522. EXPECT_FALSE(target_saw_authz.load());
  21523. }
  21524. #ifdef CPPHTTPLIB_SSL_ENABLED
  21525. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21526. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21527. // proxy creds would be sent to the (possibly hostile) origin.
  21528. std::atomic<int> target_hits{0};
  21529. std::atomic<bool> target_saw_proxy_authz{false};
  21530. no_proxy_test::ScopedServer target;
  21531. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21532. target_hits++;
  21533. if (req.has_header("Proxy-Authorization")) {
  21534. target_saw_proxy_authz = true;
  21535. }
  21536. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21537. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21538. "nonce=\"abc\", algorithm=MD5");
  21539. });
  21540. target.listen();
  21541. // The proxy address is set to the target's port: the bypass MUST kick in;
  21542. // if it doesn't, the test still routes "via proxy" to the same server and
  21543. // the Proxy-Authorization assertion below catches the leak.
  21544. Client cli("evil.example", target.port());
  21545. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21546. cli.set_proxy("127.0.0.1", target.port());
  21547. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21548. cli.set_no_proxy({"evil.example"});
  21549. auto res = cli.Get("/x");
  21550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21551. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21552. EXPECT_EQ(1, target_hits.load());
  21553. EXPECT_FALSE(target_saw_proxy_authz.load());
  21554. }
  21555. #endif
  21556. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21557. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21558. std::atomic<int> proxy_hits{0};
  21559. std::atomic<int> bypass_hits{0};
  21560. std::atomic<bool> proxy_saw_c_url{false};
  21561. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21562. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21563. proxy_hits++;
  21564. if (req.path.find("/start") != std::string::npos) {
  21565. res.status = 302;
  21566. res.set_header("Location", "http://127.0.0.1:" +
  21567. std::to_string(bypass_server.port()) +
  21568. "/middle");
  21569. return;
  21570. }
  21571. if (req.path.find("/end") != std::string::npos) {
  21572. proxy_saw_c_url = true;
  21573. res.set_content("c-via-proxy", "text/plain");
  21574. return;
  21575. }
  21576. res.set_content("unexpected", "text/plain");
  21577. });
  21578. // public.example's "advertised" port is arbitrary (the request never lands
  21579. // there — it goes through the proxy), but use a dynamic value to stay
  21580. // friendly with sharded parallel runs.
  21581. int public_port = bypass_server.port();
  21582. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21583. bypass_hits++;
  21584. res.status = 302;
  21585. res.set_header("Location", "http://public.example:" +
  21586. std::to_string(public_port) + "/end");
  21587. });
  21588. proxy_mock.listen();
  21589. bypass_server.listen();
  21590. Client cli("public.example", public_port);
  21591. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21592. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21593. cli.set_no_proxy({"127.0.0.1"});
  21594. cli.set_follow_location(true);
  21595. auto res = cli.Get("/start");
  21596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21597. EXPECT_EQ(StatusCode::OK_200, res->status);
  21598. EXPECT_EQ("c-via-proxy", res->body);
  21599. EXPECT_GE(proxy_hits.load(), 2);
  21600. EXPECT_GE(bypass_hits.load(), 1);
  21601. EXPECT_TRUE(proxy_saw_c_url.load());
  21602. }
  21603. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21604. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21605. // request reconnects to the correct endpoint.
  21606. std::atomic<int> proxy_hits{0};
  21607. std::atomic<int> target_hits{0};
  21608. no_proxy_test::ScopedServer proxy_mock, target;
  21609. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21610. proxy_hits++;
  21611. res.set_content("via-proxy", "text/plain");
  21612. });
  21613. target.svr().Get(".*", [&](const Request &, Response &res) {
  21614. target_hits++;
  21615. res.set_content("direct", "text/plain");
  21616. });
  21617. proxy_mock.listen();
  21618. target.listen();
  21619. Client cli("public.example", target.port());
  21620. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21621. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21622. cli.set_keep_alive(true);
  21623. auto res1 = cli.Get("/a");
  21624. ASSERT_TRUE(res1);
  21625. EXPECT_EQ("via-proxy", res1->body);
  21626. EXPECT_EQ(1, proxy_hits.load());
  21627. EXPECT_EQ(0, target_hits.load());
  21628. cli.set_no_proxy({"public.example"});
  21629. auto res2 = cli.Get("/b");
  21630. ASSERT_TRUE(res2);
  21631. EXPECT_EQ("direct", res2->body);
  21632. EXPECT_EQ(1, proxy_hits.load());
  21633. EXPECT_EQ(1, target_hits.load());
  21634. }
  21635. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21636. namespace proxy_tunnel_test {
  21637. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21638. class ScopedSSLServer {
  21639. public:
  21640. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21641. port_ = svr_.bind_to_any_port("127.0.0.1");
  21642. }
  21643. ~ScopedSSLServer() {
  21644. svr_.stop();
  21645. if (th_.joinable()) { th_.join(); }
  21646. }
  21647. SSLServer &svr() { return svr_; }
  21648. int port() const { return port_; }
  21649. void listen() {
  21650. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21651. svr_.wait_until_ready();
  21652. }
  21653. private:
  21654. SSLServer svr_;
  21655. std::thread th_;
  21656. int port_ = 0;
  21657. };
  21658. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21659. class ScopedConnectProxy {
  21660. public:
  21661. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21662. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21663. if (listen_fd_ < 0) { return; }
  21664. int yes = 1;
  21665. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21666. sockaddr_in a{};
  21667. a.sin_family = AF_INET;
  21668. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21669. a.sin_port = 0;
  21670. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21671. return;
  21672. }
  21673. socklen_t alen = sizeof(a);
  21674. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21675. 0) {
  21676. return;
  21677. }
  21678. port_ = ntohs(a.sin_port);
  21679. if (::listen(listen_fd_, 1) != 0) { return; }
  21680. th_ = std::thread([this] { run(); });
  21681. }
  21682. ~ScopedConnectProxy() {
  21683. stop_ = true;
  21684. if (listen_fd_ >= 0) {
  21685. ::shutdown(listen_fd_, SHUT_RDWR);
  21686. ::close(listen_fd_);
  21687. }
  21688. if (th_.joinable()) { th_.join(); }
  21689. }
  21690. int port() const { return port_; }
  21691. int connect_hits() const { return connect_hits_.load(); }
  21692. // Head of the last CONNECT request, as the proxy saw it on the wire.
  21693. std::string connect_request() const {
  21694. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21695. return connect_request_;
  21696. }
  21697. private:
  21698. void run() {
  21699. while (!stop_.load()) {
  21700. fd_set rfds;
  21701. FD_ZERO(&rfds);
  21702. FD_SET(listen_fd_, &rfds);
  21703. timeval tv{0, 100 * 1000};
  21704. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21705. if (sel <= 0) { continue; }
  21706. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21707. if (client_fd < 0) { continue; }
  21708. std::string req;
  21709. char buf[2048];
  21710. while (req.find("\r\n\r\n") == std::string::npos) {
  21711. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21712. if (n <= 0) { break; }
  21713. req.append(buf, static_cast<size_t>(n));
  21714. }
  21715. if (req.compare(0, 7, "CONNECT") != 0) {
  21716. ::close(client_fd);
  21717. continue;
  21718. }
  21719. connect_hits_++;
  21720. {
  21721. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21722. connect_request_ = req;
  21723. }
  21724. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  21725. ::send(client_fd, ok, std::strlen(ok), 0);
  21726. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  21727. sockaddr_in o{};
  21728. o.sin_family = AF_INET;
  21729. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21730. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  21731. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  21732. 0) {
  21733. ::close(client_fd);
  21734. ::close(origin_fd);
  21735. continue;
  21736. }
  21737. auto forward = [](int from, int to) {
  21738. char b[8192];
  21739. for (;;) {
  21740. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21741. if (n <= 0) { break; }
  21742. ssize_t off = 0;
  21743. while (off < n) {
  21744. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21745. if (s <= 0) {
  21746. off = n;
  21747. break;
  21748. }
  21749. off += s;
  21750. }
  21751. }
  21752. ::shutdown(to, SHUT_WR);
  21753. };
  21754. std::thread t1([&] { forward(client_fd, origin_fd); });
  21755. std::thread t2([&] { forward(origin_fd, client_fd); });
  21756. t1.join();
  21757. t2.join();
  21758. ::close(client_fd);
  21759. ::close(origin_fd);
  21760. }
  21761. }
  21762. int forward_port_ = -1;
  21763. int listen_fd_ = -1;
  21764. int port_ = 0;
  21765. std::thread th_;
  21766. std::atomic<bool> stop_{false};
  21767. std::atomic<int> connect_hits_{0};
  21768. mutable std::mutex connect_request_mutex_;
  21769. std::string connect_request_;
  21770. };
  21771. // Sends one request through the CONNECT proxy to the TLS origin with a
  21772. // credential configured for each hop, and checks that each credential reaches
  21773. // only the hop it was configured for: the proxy's on the CONNECT request, the
  21774. // origin's (every header in origin_headers) on the tunnelled request.
  21775. void CredentialsStayWithTheirHop(
  21776. const std::function<void(SSLClient &)> &set_credentials,
  21777. const std::string &scheme,
  21778. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  21779. std::atomic<int> origin_hits{0};
  21780. std::atomic<bool> origin_saw_proxy_authz{false};
  21781. std::atomic<bool> origin_saw_headers{false};
  21782. ScopedSSLServer origin;
  21783. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21784. origin_hits++;
  21785. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  21786. origin_saw_headers =
  21787. std::all_of(origin_headers.begin(), origin_headers.end(),
  21788. [&](const std::string &h) { return req.has_header(h); });
  21789. res.set_content("ok", "text/plain");
  21790. });
  21791. origin.listen();
  21792. ScopedConnectProxy proxy(origin.port());
  21793. ASSERT_NE(0, proxy.port());
  21794. // Pinned to 127.0.0.1 for the same reason as the test below.
  21795. SSLClient cli("127.0.0.1", origin.port());
  21796. cli.enable_server_certificate_verification(false);
  21797. cli.set_proxy("127.0.0.1", proxy.port());
  21798. set_credentials(cli);
  21799. auto res = cli.Get("/x");
  21800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21801. EXPECT_EQ(StatusCode::OK_200, res->status);
  21802. EXPECT_EQ(1, origin_hits.load());
  21803. EXPECT_EQ(1, proxy.connect_hits());
  21804. EXPECT_TRUE(origin_saw_headers.load());
  21805. EXPECT_FALSE(origin_saw_proxy_authz.load())
  21806. << "Proxy-Authorization must not be sent inside the tunnel";
  21807. auto connect_req = proxy.connect_request();
  21808. EXPECT_NE(std::string::npos,
  21809. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  21810. for (const auto &h : origin_headers) {
  21811. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  21812. << h << " must not be sent to the proxy on CONNECT";
  21813. }
  21814. }
  21815. } // namespace proxy_tunnel_test
  21816. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  21817. proxy_tunnel_test::CredentialsStayWithTheirHop(
  21818. [](SSLClient &cli) {
  21819. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  21820. cli.set_basic_auth("origin-user", "origin-pass");
  21821. },
  21822. "Basic");
  21823. }
  21824. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  21825. proxy_tunnel_test::CredentialsStayWithTheirHop(
  21826. [](SSLClient &cli) {
  21827. cli.set_proxy_bearer_token_auth("proxy-token");
  21828. cli.set_bearer_token_auth("origin-token");
  21829. },
  21830. "Bearer");
  21831. }
  21832. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  21833. proxy_tunnel_test::CredentialsStayWithTheirHop(
  21834. [](SSLClient &cli) {
  21835. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  21836. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  21837. {"Cookie", "sid=origin-session"},
  21838. {"X-Api-Key", "origin-key"}});
  21839. },
  21840. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  21841. }
  21842. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  21843. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  21844. // retry; otherwise proxy creds would be sent to the origin.
  21845. std::atomic<int> origin_hits{0};
  21846. std::atomic<bool> origin_saw_proxy_authz{false};
  21847. proxy_tunnel_test::ScopedSSLServer origin;
  21848. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21849. origin_hits++;
  21850. if (req.has_header("Proxy-Authorization")) {
  21851. origin_saw_proxy_authz = true;
  21852. }
  21853. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21854. res.set_header("Proxy-Authenticate",
  21855. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  21856. "algorithm=MD5");
  21857. });
  21858. origin.listen();
  21859. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  21860. ASSERT_NE(0, proxy.port());
  21861. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  21862. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  21863. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  21864. // and answer with its own status, making this test flaky.
  21865. SSLClient cli("127.0.0.1", origin.port());
  21866. cli.enable_server_certificate_verification(false);
  21867. cli.set_proxy("127.0.0.1", proxy.port());
  21868. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21869. auto res = cli.Get("/x");
  21870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21871. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21872. EXPECT_EQ(1, origin_hits.load());
  21873. EXPECT_FALSE(origin_saw_proxy_authz.load());
  21874. EXPECT_EQ(1, proxy.connect_hits());
  21875. }
  21876. #endif