test.cc 704 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  258. ASSERT_EQ(0, listen(s, 1));
  259. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  260. ASSERT_EQ(0, close(s));
  261. }};
  262. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  263. std::thread cli{[&] {
  264. const int s = socket(AF_INET, SOCK_STREAM, 0);
  265. ASSERT_LE(0, s);
  266. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. cli.join();
  270. svr.join();
  271. ASSERT_NE(disconnected_svr_sock, -1);
  272. const auto asSocketStream = [&](socket_t fd,
  273. std::function<bool(Stream &)> func) {
  274. return detail::process_client_socket(
  275. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  276. };
  277. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  278. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  279. // wait_writable() returns true because select_write() only checks if the
  280. // send buffer has space. Peer disconnection is detected later by send().
  281. EXPECT_TRUE(ss.wait_writable());
  282. return true;
  283. });
  284. ASSERT_EQ(0, close(disconnected_svr_sock));
  285. }
  286. #endif // #ifndef _WIN32
  287. TEST(SetSocketOptTest, TcpNoDelay) {
  288. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  289. ASSERT_NE(sock, INVALID_SOCKET);
  290. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  291. int val = 0;
  292. socklen_t len = sizeof(val);
  293. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  294. reinterpret_cast<char *>(&val), &len));
  295. EXPECT_NE(val, 0);
  296. detail::close_socket(sock);
  297. }
  298. TEST(ClientTest, MoveConstructible) {
  299. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  300. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  301. }
  302. TEST(ClientTest, MoveAssignable) {
  303. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  304. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  305. }
  306. #ifdef _WIN32
  307. TEST(StartupTest, WSAStartup) {
  308. WSADATA wsaData;
  309. int ret = WSAStartup(0x0002, &wsaData);
  310. ASSERT_EQ(0, ret);
  311. }
  312. #endif
  313. TEST(DecodePathTest, PercentCharacter) {
  314. EXPECT_EQ(
  315. decode_path_component(
  316. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  317. U8("descrip=Gastos áéíóúñÑ 6"));
  318. }
  319. TEST(DecodePathTest, PercentCharacterNUL) {
  320. string expected;
  321. expected.push_back('x');
  322. expected.push_back('\0');
  323. expected.push_back('x');
  324. EXPECT_EQ(decode_path_component("x%00x"), expected);
  325. }
  326. TEST(DecodePathTest, UnicodeEncoding) {
  327. // %u0041 = 'A' (1-byte UTF-8)
  328. EXPECT_EQ("A", decode_path_component("%u0041"));
  329. // %u00E9 = 'é' (2-byte UTF-8)
  330. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  331. // %u3042 = 'あ' (3-byte UTF-8)
  332. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  333. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  334. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  335. // %uD800 = surrogate (invalid, silently dropped)
  336. EXPECT_EQ("", decode_path_component("%uD800"));
  337. }
  338. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  339. // A sign or whitespace inside the two-character escape window must not be
  340. // accepted as a valid percent-encoding; the sequence is passed through
  341. // literally, matching decode_uri_component / decode_path_component.
  342. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  343. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  344. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  345. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  346. // Well-formed escapes still decode.
  347. EXPECT_EQ("-", decode_query_component("%2D", false));
  348. EXPECT_EQ("A", decode_query_component("%41", false));
  349. }
  350. TEST(SanitizeFilenameTest, VariousPatterns) {
  351. // Path traversal
  352. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  353. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  354. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  355. // Normal and edge cases
  356. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  357. EXPECT_EQ("filename.txt",
  358. httplib::sanitize_filename("/path/to/filename.txt"));
  359. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  360. EXPECT_EQ("", httplib::sanitize_filename(".."));
  361. EXPECT_EQ("", httplib::sanitize_filename(""));
  362. // Null bytes stripped
  363. EXPECT_EQ("safe.txt",
  364. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  365. // Whitespace-only rejected
  366. EXPECT_EQ("", httplib::sanitize_filename(" "));
  367. }
  368. // Forward declaration (see the base64_encode note below): split builds move the
  369. // definition into httplib.cc, so re-declaring it here lets the test link.
  370. namespace httplib {
  371. namespace detail {
  372. bool is_chunked_transfer_encoding(const Headers &headers);
  373. } // namespace detail
  374. } // namespace httplib
  375. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  376. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  377. auto make = [](std::initializer_list<const char *> lines) {
  378. Headers h;
  379. for (auto te : lines) {
  380. if (te) { h.emplace("Transfer-Encoding", te); }
  381. }
  382. return h;
  383. };
  384. // Sole coding, matched case-insensitively.
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  386. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  388. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  390. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  392. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  395. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  396. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  397. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  398. // were received, into one list. Headers preserves that order, so the answer
  399. // is decided by the last coding of the last line and the order the lines
  400. // arrived in is significant.
  401. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  403. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  404. // The split can fall anywhere in the list.
  405. EXPECT_TRUE(
  406. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  407. EXPECT_FALSE(
  408. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  409. // A trailing line naming no coding leaves the list ending in nothing, so it
  410. // must not inherit the chunked from the line before it.
  411. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  412. }
  413. // Forward declaration: in split builds split.py strips `inline` and moves the
  414. // definition into httplib.cc, so detail::base64_encode is not visible from the
  415. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  416. // in both header-only and split builds.
  417. namespace httplib {
  418. namespace detail {
  419. std::string base64_encode(const std::string &in);
  420. } // namespace detail
  421. } // namespace httplib
  422. TEST(Base64EncodeTest, KnownAnswers) {
  423. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  424. // where the accumulator's top bit is already set before the next shift.
  425. EXPECT_EQ("", detail::base64_encode(""));
  426. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  427. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  428. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  429. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  430. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  431. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  432. // High bytes keep the top bit set across several rounds.
  433. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  434. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  435. }
  436. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  437. string unescapedCharacters = "-_.!~*'()";
  438. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  439. }
  440. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  441. string reservedCharacters = ";,/?:@&=+$";
  442. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  443. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  444. }
  445. TEST(ClientQueryOrder, PreserveOrder) {
  446. // This test reproduces Issue #2259: client may reorder query parameters
  447. // when sending a GET request. The expected behavior is that the client
  448. // preserves the original query string order when the caller supplied it
  449. // as part of the path.
  450. Server svr;
  451. svr.Get("/", [&](const Request &req, Response &res) {
  452. // Echo back the raw target so the test can assert ordering
  453. res.set_content(req.target, "text/plain");
  454. });
  455. std::thread t{[&] { svr.listen(HOST, PORT); }};
  456. auto se = detail::scope_exit([&] {
  457. svr.stop();
  458. t.join();
  459. ASSERT_FALSE(svr.is_running());
  460. });
  461. svr.wait_until_ready();
  462. Client cli(HOST, PORT);
  463. ASSERT_TRUE(cli.is_valid());
  464. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  465. auto res = cli.Get(original);
  466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  467. // Expect the echoed target to exactly match the original path (order
  468. // preserved)
  469. EXPECT_EQ(res->body, original);
  470. }
  471. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  472. string chineseCharacters = U8("中国語");
  473. string russianCharacters = U8("дом");
  474. string brazilianCharacters = U8("óculos");
  475. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  476. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  477. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  478. "%D0%B4%D0%BE%D0%BC");
  479. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  480. }
  481. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  482. string unescapedCharacters = "-_.!~*'()";
  483. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  484. }
  485. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  486. string reservedCharacters = ";,/?:@&=+$";
  487. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  488. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  489. }
  490. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  491. string chineseCharacters = U8("中国語");
  492. string russianCharacters = U8("дом");
  493. string brazilianCharacters = U8("óculos");
  494. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  495. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  496. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  497. "%D0%B4%D0%BE%D0%BC");
  498. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  499. }
  500. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  501. // Issue #2082 use case: encoding path component with ampersand
  502. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  503. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  504. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  505. }
  506. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  507. string unescapedCharacters = "-_.!~*'()";
  508. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  509. }
  510. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  511. string reservedCharacters = ";,/?:@&=+$#";
  512. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  513. }
  514. TEST(EncodeUriTest, TestUTF8Characters) {
  515. string chineseCharacters = U8("中国語");
  516. string russianCharacters = U8("дом");
  517. string brazilianCharacters = U8("óculos");
  518. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  519. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  520. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  521. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  522. }
  523. TEST(EncodeUriTest, TestCompleteUri) {
  524. string uri =
  525. "https://example.com/path/to/resource?query=value&param=test#fragment";
  526. EXPECT_EQ(
  527. httplib::encode_uri(uri),
  528. "https://example.com/path/to/resource?query=value&param=test#fragment");
  529. }
  530. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  531. string uri =
  532. "https://example.com/path with spaces/file name.html?q=hello world";
  533. EXPECT_EQ(httplib::encode_uri(uri),
  534. "https://example.com/path%20with%20spaces/"
  535. "file%20name.html?q=hello%20world");
  536. }
  537. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  538. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  539. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  540. }
  541. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  546. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  547. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  548. string encodedBrazilian = "%C3%B3culos";
  549. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  550. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  551. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  552. }
  553. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  554. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  556. "Piri Tommy Villiers - on & on");
  557. }
  558. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  559. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  560. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  561. }
  562. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  563. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  564. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  565. }
  566. TEST(DecodeUriTest, TestUTF8Characters) {
  567. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  568. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  569. string encodedBrazilian = "%C3%B3culos";
  570. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  571. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  572. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  573. }
  574. TEST(DecodeUriTest, TestCompleteUri) {
  575. string encodedUri = "https://example.com/path%20with%20spaces/"
  576. "file%20name.html?q=hello%20world";
  577. EXPECT_EQ(
  578. httplib::decode_uri(encodedUri),
  579. "https://example.com/path with spaces/file name.html?q=hello world");
  580. }
  581. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  582. string original =
  583. "https://example.com/path with spaces/file name.html?q=hello world";
  584. string encoded = httplib::encode_uri(original);
  585. string decoded = httplib::decode_uri(encoded);
  586. EXPECT_EQ(decoded, original);
  587. }
  588. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  589. string original = "Piri Tommy Villiers - on & on";
  590. string encoded = httplib::encode_uri_component(original);
  591. string decoded = httplib::decode_uri_component(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(TrimTests, TrimStringTests) {
  595. EXPECT_EQ("abc", detail::trim_copy("abc"));
  596. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  597. EXPECT_TRUE(detail::trim_copy("").empty());
  598. }
  599. TEST(AsciiTest, LocaleIndependentClassification) {
  600. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  601. // which consult the global C locale: std::isalnum(0xC5) can return true
  602. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  603. // helpers must classify every byte by the ASCII grammar alone.
  604. for (int i = 0; i < 256; i++) {
  605. auto c = static_cast<char>(i);
  606. auto is_digit = i >= '0' && i <= '9';
  607. auto is_upper = i >= 'A' && i <= 'Z';
  608. auto is_lower = i >= 'a' && i <= 'z';
  609. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  610. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  611. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  612. << "byte " << i;
  613. }
  614. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  615. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  616. // Non-ASCII bytes must be percent-encoded, never passed through as
  617. // alphanumeric.
  618. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  619. }
  620. TEST(FromCharsTest, Double) {
  621. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  622. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  623. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  624. auto parse = [](const std::string &s, double &v) {
  625. return detail::from_chars(s.data(), s.data() + s.size(), v);
  626. };
  627. double v = -1.0;
  628. // Representative quality values.
  629. EXPECT_EQ(parse("0", v).ec, std::errc{});
  630. EXPECT_DOUBLE_EQ(v, 0.0);
  631. EXPECT_EQ(parse("1", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 1.0);
  633. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 0.8);
  635. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  636. EXPECT_DOUBLE_EQ(v, 0.001);
  637. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  638. EXPECT_DOUBLE_EQ(v, 1.0);
  639. // A missing integer or fractional part is tolerated.
  640. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  641. EXPECT_DOUBLE_EQ(v, 0.5);
  642. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  643. EXPECT_DOUBLE_EQ(v, 5.0);
  644. // Values outside [0, 1] still parse; the caller range-checks them.
  645. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  646. EXPECT_DOUBLE_EQ(v, 123.456);
  647. // Stops at the first byte that is not part of the number and reports where.
  648. std::string trailing = "0.9, text/html";
  649. auto r = parse(trailing, v);
  650. EXPECT_EQ(r.ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.9);
  652. EXPECT_EQ(*r.ptr, ',');
  653. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  654. // outright, and an 'e'/'E' simply ends the number.
  655. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  657. std::string exp_input = "1.5e3";
  658. r = parse(exp_input, v);
  659. EXPECT_EQ(r.ec, std::errc{});
  660. EXPECT_DOUBLE_EQ(v, 1.5);
  661. EXPECT_EQ(*r.ptr, 'e');
  662. // Invalid inputs.
  663. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  664. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  665. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  666. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  667. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  668. // Pathological but well-formed inputs must stay bounded (no overflow, no
  669. // out-of-bounds table access) and stay within [0, 1] for the caller.
  670. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  671. std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.0);
  673. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  674. std::errc{});
  675. EXPECT_GE(v, 0.0);
  676. EXPECT_LE(v, 1.0);
  677. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  678. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  679. }
  680. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  681. // Simple case without quality values
  682. std::vector<std::string> result1;
  683. EXPECT_TRUE(detail::parse_accept_header(
  684. "text/html,application/json,text/plain", result1));
  685. EXPECT_EQ(result1.size(), 3U);
  686. EXPECT_EQ(result1[0], "text/html");
  687. EXPECT_EQ(result1[1], "application/json");
  688. EXPECT_EQ(result1[2], "text/plain");
  689. // With quality values
  690. std::vector<std::string> result2;
  691. EXPECT_TRUE(detail::parse_accept_header(
  692. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  693. EXPECT_EQ(result2.size(), 3U);
  694. EXPECT_EQ(result2[0], "application/json"); // highest q value
  695. EXPECT_EQ(result2[1], "text/html");
  696. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  697. }
  698. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  699. // Mixed with and without quality values
  700. std::vector<std::string> result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  703. EXPECT_EQ(result.size(), 3U);
  704. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  705. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  706. EXPECT_EQ(result[2], "application/json"); // q=0.5
  707. }
  708. TEST(ParseAcceptHeaderTest, EdgeCases) {
  709. // Empty header
  710. std::vector<std::string> empty_result;
  711. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  712. EXPECT_TRUE(empty_result.empty());
  713. // Single type
  714. std::vector<std::string> single_result;
  715. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  716. EXPECT_EQ(single_result.size(), 1U);
  717. EXPECT_EQ(single_result[0], "application/json");
  718. // Wildcard types
  719. std::vector<std::string> wildcard_result;
  720. EXPECT_TRUE(detail::parse_accept_header(
  721. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  722. EXPECT_EQ(wildcard_result.size(), 3U);
  723. EXPECT_EQ(wildcard_result[0], "application/json");
  724. EXPECT_EQ(wildcard_result[1], "text/*");
  725. EXPECT_EQ(wildcard_result[2], "*/*");
  726. }
  727. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  728. // Common browser Accept header
  729. std::vector<std::string> browser_result;
  730. EXPECT_TRUE(
  731. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  732. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  733. browser_result));
  734. EXPECT_EQ(browser_result.size(), 6U);
  735. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  736. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  737. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  738. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  739. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  740. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  741. // API client header
  742. std::vector<std::string> api_result;
  743. EXPECT_TRUE(detail::parse_accept_header(
  744. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  745. api_result));
  746. EXPECT_EQ(api_result.size(), 3U);
  747. EXPECT_EQ(api_result[0], "application/json");
  748. EXPECT_EQ(api_result[1], "application/xml");
  749. EXPECT_EQ(api_result[2], "text/plain");
  750. }
  751. TEST(ParseAcceptHeaderTest, SpecialCases) {
  752. // Quality value with 3 decimal places
  753. std::vector<std::string> decimal_result;
  754. EXPECT_TRUE(detail::parse_accept_header(
  755. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  756. EXPECT_EQ(decimal_result.size(), 2U);
  757. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  758. EXPECT_EQ(decimal_result[1], "text/html");
  759. // Zero quality (should still be included but with lowest priority)
  760. std::vector<std::string> zero_q_result;
  761. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  762. zero_q_result));
  763. EXPECT_EQ(zero_q_result.size(), 2U);
  764. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  765. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  766. // No spaces around commas
  767. std::vector<std::string> no_space_result;
  768. EXPECT_TRUE(detail::parse_accept_header(
  769. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  770. no_space_result));
  771. EXPECT_EQ(no_space_result.size(), 3U);
  772. EXPECT_EQ(no_space_result[0], "text/html");
  773. EXPECT_EQ(no_space_result[1], "application/json");
  774. EXPECT_EQ(no_space_result[2], "text/plain");
  775. }
  776. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  777. // Quality values always use '.' as the decimal separator, so parsing must
  778. // not depend on the process locale. An embedding application may have
  779. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  780. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  781. std::string saved = cur ? cur : "C";
  782. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  783. "fr_FR.UTF-8"};
  784. bool switched = false;
  785. for (const auto loc : comma_locales) {
  786. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  787. std::localeconv()->decimal_point[0] == ',') {
  788. switched = true;
  789. break;
  790. }
  791. }
  792. if (!switched) {
  793. std::setlocale(LC_NUMERIC, saved.c_str());
  794. GTEST_SKIP() << "no comma-decimal locale available on this host";
  795. }
  796. // The higher-weighted type appears later in the list, so a correct parse
  797. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  798. // sensitive parse reads both weights as 0 and leaves the original order.
  799. std::vector<std::string> result;
  800. EXPECT_TRUE(detail::parse_accept_header(
  801. "application/json;q=0.1,text/html;q=0.9", result));
  802. ASSERT_EQ(result.size(), 2U);
  803. EXPECT_EQ(result[0], "text/html");
  804. EXPECT_EQ(result[1], "application/json");
  805. std::setlocale(LC_NUMERIC, saved.c_str());
  806. }
  807. TEST(ParseAcceptHeaderTest, InvalidCases) {
  808. std::vector<std::string> result;
  809. // Invalid quality value (> 1.0)
  810. EXPECT_FALSE(
  811. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  812. // Invalid quality value (< 0.0)
  813. EXPECT_FALSE(
  814. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  815. // Invalid quality value (not a number)
  816. EXPECT_FALSE(detail::parse_accept_header(
  817. "text/html;q=invalid,application/json", result));
  818. // Empty quality value
  819. EXPECT_FALSE(
  820. detail::parse_accept_header("text/html;q=,application/json", result));
  821. // Invalid media type format (no slash and not wildcard)
  822. EXPECT_FALSE(
  823. detail::parse_accept_header("invalidtype,application/json", result));
  824. // Empty media type
  825. result.clear();
  826. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  827. // Only commas
  828. result.clear();
  829. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  830. // Valid cases should still work
  831. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  832. EXPECT_EQ(result.size(), 1U);
  833. EXPECT_EQ(result[0], "*/*");
  834. EXPECT_TRUE(detail::parse_accept_header("*", result));
  835. EXPECT_EQ(result.size(), 1U);
  836. EXPECT_EQ(result[0], "*");
  837. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  838. EXPECT_EQ(result.size(), 1U);
  839. EXPECT_EQ(result[0], "text/*");
  840. }
  841. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  842. Server svr;
  843. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  844. EXPECT_EQ(req.accept_content_types.size(), 3U);
  845. EXPECT_EQ(req.accept_content_types[0], "application/json");
  846. EXPECT_EQ(req.accept_content_types[1], "text/html");
  847. EXPECT_EQ(req.accept_content_types[2], "*/*");
  848. res.set_content("ok", "text/plain");
  849. });
  850. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  851. EXPECT_TRUE(false);
  852. res.set_content("bad request", "text/plain");
  853. });
  854. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  855. auto se = detail::scope_exit([&] {
  856. svr.stop();
  857. listen_thread.join();
  858. ASSERT_FALSE(svr.is_running());
  859. });
  860. svr.wait_until_ready();
  861. Client cli("localhost", PORT);
  862. {
  863. auto res = cli.Get(
  864. "/accept_ok",
  865. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  867. EXPECT_EQ(StatusCode::OK_200, res->status);
  868. }
  869. {
  870. auto res = cli.Get("/accept_bad_request",
  871. Headers{{"Accept", "text/html;q=abc,application/json"}});
  872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  873. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  874. }
  875. }
  876. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  877. Server svr;
  878. svr.Get("/", [](const Request & /*req*/, Response &res) {
  879. res.set_content("ok", "text/plain");
  880. });
  881. std::atomic<int> start_count{0};
  882. std::atomic<bool> running_when_called{false};
  883. svr.set_start_handler([&]() {
  884. running_when_called = svr.is_running();
  885. start_count++;
  886. });
  887. auto port = svr.bind_to_any_port(HOST);
  888. std::thread t([&]() { svr.listen_after_bind(); });
  889. auto se = detail::scope_exit([&] {
  890. svr.stop();
  891. t.join();
  892. ASSERT_FALSE(svr.is_running());
  893. });
  894. svr.wait_until_ready();
  895. // A successful request proves the accept loop is running, which the start
  896. // handler precedes; so by now the handler must have run exactly once.
  897. Client cli(HOST, port);
  898. cli.set_connection_timeout(std::chrono::seconds(5));
  899. auto res = cli.Get("/");
  900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  901. EXPECT_EQ(StatusCode::OK_200, res->status);
  902. EXPECT_EQ(1, start_count.load());
  903. EXPECT_TRUE(running_when_called.load());
  904. }
  905. TEST(DivideTest, DivideStringTests) {
  906. auto divide = [](const std::string &str, char d) {
  907. std::string lhs;
  908. std::string rhs;
  909. detail::divide(str, d,
  910. [&](const char *lhs_data, std::size_t lhs_size,
  911. const char *rhs_data, std::size_t rhs_size) {
  912. lhs.assign(lhs_data, lhs_size);
  913. rhs.assign(rhs_data, rhs_size);
  914. });
  915. return std::make_pair(std::move(lhs), std::move(rhs));
  916. };
  917. {
  918. const auto res = divide("", '=');
  919. EXPECT_EQ(res.first, "");
  920. EXPECT_EQ(res.second, "");
  921. }
  922. {
  923. const auto res = divide("=", '=');
  924. EXPECT_EQ(res.first, "");
  925. EXPECT_EQ(res.second, "");
  926. }
  927. {
  928. const auto res = divide(" ", '=');
  929. EXPECT_EQ(res.first, " ");
  930. EXPECT_EQ(res.second, "");
  931. }
  932. {
  933. const auto res = divide("a", '=');
  934. EXPECT_EQ(res.first, "a");
  935. EXPECT_EQ(res.second, "");
  936. }
  937. {
  938. const auto res = divide("a=", '=');
  939. EXPECT_EQ(res.first, "a");
  940. EXPECT_EQ(res.second, "");
  941. }
  942. {
  943. const auto res = divide("=b", '=');
  944. EXPECT_EQ(res.first, "");
  945. EXPECT_EQ(res.second, "b");
  946. }
  947. {
  948. const auto res = divide("a=b", '=');
  949. EXPECT_EQ(res.first, "a");
  950. EXPECT_EQ(res.second, "b");
  951. }
  952. {
  953. const auto res = divide("a=b=", '=');
  954. EXPECT_EQ(res.first, "a");
  955. EXPECT_EQ(res.second, "b=");
  956. }
  957. {
  958. const auto res = divide("a=b=c", '=');
  959. EXPECT_EQ(res.first, "a");
  960. EXPECT_EQ(res.second, "b=c");
  961. }
  962. }
  963. TEST(SplitTest, ParseQueryString) {
  964. string s = "key1=val1&key2=val2&key3=val3";
  965. Params dic;
  966. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  967. [&](const char *b, const char *e) {
  968. string key, val;
  969. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  970. if (key.empty()) {
  971. key.assign(b2, e2);
  972. } else {
  973. val.assign(b2, e2);
  974. }
  975. });
  976. dic.emplace(key, val);
  977. });
  978. EXPECT_EQ("val1", dic.find("key1")->second);
  979. EXPECT_EQ("val2", dic.find("key2")->second);
  980. EXPECT_EQ("val3", dic.find("key3")->second);
  981. }
  982. TEST(SplitTest, ParseInvalidQueryTests) {
  983. {
  984. string s = " ";
  985. Params dict;
  986. detail::parse_query_text(s, dict);
  987. EXPECT_TRUE(dict.empty());
  988. }
  989. {
  990. string s = " = =";
  991. Params dict;
  992. detail::parse_query_text(s, dict);
  993. EXPECT_TRUE(dict.empty());
  994. }
  995. }
  996. TEST(ParseQueryTest, ParseQueryString) {
  997. {
  998. std::string s = "key1=val1&key2=val2&key3=val3";
  999. Params dic;
  1000. detail::parse_query_text(s, dic);
  1001. EXPECT_EQ("val1", dic.find("key1")->second);
  1002. EXPECT_EQ("val2", dic.find("key2")->second);
  1003. EXPECT_EQ("val3", dic.find("key3")->second);
  1004. }
  1005. {
  1006. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1007. Params dic;
  1008. detail::parse_query_text(s, dic);
  1009. EXPECT_EQ("", dic.find("key1")->second);
  1010. EXPECT_EQ("val1", dic.find("key2")->second);
  1011. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1012. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1013. }
  1014. }
  1015. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1016. Params dic;
  1017. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1018. dic.emplace("key1", "val1");
  1019. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1020. dic.emplace("key2", "val2");
  1021. dic.emplace("key3", "val3");
  1022. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1023. }
  1024. // Joins every entry of a Headers or Params into "key=value " so a whole
  1025. // traversal can be compared in one assertion. Both are instantiations of the
  1026. // same insertion-ordered container, so one helper serves both.
  1027. template <typename Map> static std::string entries_to_string(const Map &m) {
  1028. std::string s;
  1029. for (const auto &entry : m) {
  1030. s += entry.first + "=" + entry.second + " ";
  1031. }
  1032. return s;
  1033. }
  1034. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1035. // Params used to be a std::multimap, which sorted by name and handed the
  1036. // caller's query back alphabetised. A client signing its query string could
  1037. // not reproduce the order it asked for.
  1038. Params dic;
  1039. dic.emplace("zulu", "1");
  1040. dic.emplace("alpha", "2");
  1041. dic.emplace("mike", "3");
  1042. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1043. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1044. }
  1045. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1046. Params dic;
  1047. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1048. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1049. }
  1050. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1051. Request req;
  1052. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1053. req.params);
  1054. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1055. EXPECT_EQ("first", req.get_param_value("tag"));
  1056. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1057. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1058. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1059. EXPECT_EQ("", req.get_param_value("tag", 3));
  1060. }
  1061. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1062. // Params shares its container with Headers, which matches field names
  1063. // case-insensitively. Parameter names must not pick that up.
  1064. Params dic;
  1065. dic.emplace("Key", "upper");
  1066. dic.emplace("key", "lower");
  1067. EXPECT_EQ(2U, dic.size());
  1068. EXPECT_EQ(1U, dic.count("Key"));
  1069. EXPECT_EQ(1U, dic.count("key"));
  1070. EXPECT_EQ("upper", dic.find("Key")->second);
  1071. EXPECT_EQ("lower", dic.find("key")->second);
  1072. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1073. }
  1074. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1075. Server svr;
  1076. std::string order;
  1077. svr.Get("/order", [&](const Request &req, Response &res) {
  1078. order = entries_to_string(req.params);
  1079. res.set_content("ok", "text/plain");
  1080. });
  1081. thread t = thread([&] { svr.listen(HOST, PORT); });
  1082. auto se = detail::scope_exit([&] {
  1083. svr.stop();
  1084. t.join();
  1085. ASSERT_FALSE(svr.is_running());
  1086. });
  1087. svr.wait_until_ready();
  1088. Client cli(HOST, PORT);
  1089. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1090. ASSERT_TRUE(res);
  1091. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1092. }
  1093. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1094. Server svr;
  1095. std::string field_order, file_order;
  1096. svr.Post("/order", [&](const Request &req, Response &res) {
  1097. for (const auto &field : req.form.fields) {
  1098. field_order += field.first + "=" + field.second.content + " ";
  1099. }
  1100. for (const auto &file : req.form.files) {
  1101. file_order += file.first + "=" + file.second.filename + " ";
  1102. }
  1103. res.set_content("ok", "text/plain");
  1104. });
  1105. thread t = thread([&] { svr.listen(HOST, PORT); });
  1106. auto se = detail::scope_exit([&] {
  1107. svr.stop();
  1108. t.join();
  1109. ASSERT_FALSE(svr.is_running());
  1110. });
  1111. svr.wait_until_ready();
  1112. UploadFormDataItems items = {
  1113. {"zulu", "1", "", ""},
  1114. {"alpha", "2", "", ""},
  1115. {"mike", "3", "", ""},
  1116. {"zebra", "z", "z.txt", "text/plain"},
  1117. {"apple", "a", "a.txt", "text/plain"},
  1118. };
  1119. Client cli(HOST, PORT);
  1120. auto res = cli.Post("/order", items);
  1121. ASSERT_TRUE(res);
  1122. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1123. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1124. }
  1125. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1126. Server svr;
  1127. std::vector<std::string> values;
  1128. std::string first, second, out_of_range, order;
  1129. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1130. values = req.form.get_fields("tag");
  1131. first = req.form.get_field("tag", 0);
  1132. second = req.form.get_field("tag", 1);
  1133. out_of_range = req.form.get_field("tag", 2);
  1134. for (const auto &field : req.form.fields) {
  1135. order += field.first + "=" + field.second.content + " ";
  1136. }
  1137. res.set_content("ok", "text/plain");
  1138. });
  1139. thread t = thread([&] { svr.listen(HOST, PORT); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. t.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1147. // not adjacent in the container.
  1148. UploadFormDataItems items = {
  1149. {"tag", "first", "", ""},
  1150. {"other", "x", "", ""},
  1151. {"tag", "second", "", ""},
  1152. };
  1153. Client cli(HOST, PORT);
  1154. auto res = cli.Post("/repeated", items);
  1155. ASSERT_TRUE(res);
  1156. ASSERT_EQ(2U, values.size());
  1157. EXPECT_EQ("first", values[0]);
  1158. EXPECT_EQ("second", values[1]);
  1159. EXPECT_EQ("first", first);
  1160. EXPECT_EQ("second", second);
  1161. // std::multimap already kept entries sharing a name in insertion order, so
  1162. // everything above passes without this change too. The whole traversal is
  1163. // what tells the two apart: sorting by name would hoist "other" to the front
  1164. // and the two "tag" parts would end up adjacent.
  1165. EXPECT_EQ("tag=first other=x tag=second ", order);
  1166. // Advancing past the last entry of a name used to run off the container;
  1167. // the container's saturating increment makes it return the default instead.
  1168. EXPECT_EQ("", out_of_range);
  1169. }
  1170. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1171. // Server::read_content() keeps a FormFields::iterator alive across the
  1172. // content callbacks that fill the part it points at. The container is
  1173. // vector-backed, so a later emplace can reallocate and invalidate an older
  1174. // iterator; 64 parts grow the vector through seven reallocations, which
  1175. // checks that every part's content still lands in its own entry.
  1176. const size_t part_count = 64;
  1177. // One formula for both the parts sent and the values expected back, so the
  1178. // two cannot drift apart.
  1179. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1180. auto content_of = [](size_t i) {
  1181. return std::string(64, static_cast<char>('a' + (i % 26)));
  1182. };
  1183. Server svr;
  1184. std::vector<std::pair<std::string, std::string>> received;
  1185. svr.Post("/many", [&](const Request &req, Response &res) {
  1186. for (const auto &field : req.form.fields) {
  1187. received.emplace_back(field.first, field.second.content);
  1188. }
  1189. res.set_content("ok", "text/plain");
  1190. });
  1191. thread t = thread([&] { svr.listen(HOST, PORT); });
  1192. auto se = detail::scope_exit([&] {
  1193. svr.stop();
  1194. t.join();
  1195. ASSERT_FALSE(svr.is_running());
  1196. });
  1197. svr.wait_until_ready();
  1198. UploadFormDataItems items;
  1199. for (size_t i = 0; i < part_count; i++) {
  1200. items.push_back({name_of(i), content_of(i), "", ""});
  1201. }
  1202. Client cli(HOST, PORT);
  1203. auto res = cli.Post("/many", items);
  1204. ASSERT_TRUE(res);
  1205. ASSERT_EQ(part_count, received.size());
  1206. for (size_t i = 0; i < part_count; i++) {
  1207. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1208. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1209. }
  1210. }
  1211. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1212. string content_type = "multipart/form-data; boundary=something";
  1213. string boundary;
  1214. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1215. EXPECT_TRUE(ret);
  1216. EXPECT_EQ(boundary, "something");
  1217. }
  1218. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1219. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1220. string boundary;
  1221. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1222. EXPECT_TRUE(ret);
  1223. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1224. }
  1225. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1226. string content_type =
  1227. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1228. string boundary;
  1229. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1230. EXPECT_TRUE(ret);
  1231. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1232. }
  1233. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1234. string content_type =
  1235. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1236. string boundary;
  1237. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1238. EXPECT_TRUE(ret);
  1239. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1240. }
  1241. TEST(GetHeaderValueTest, DefaultValue) {
  1242. Headers headers = {{"Dummy", "Dummy"}};
  1243. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1244. EXPECT_STREQ("text/plain", val);
  1245. }
  1246. TEST(GetHeaderValueTest, DefaultValueInt) {
  1247. Headers headers = {{"Dummy", "Dummy"}};
  1248. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1249. EXPECT_EQ(100ull, val);
  1250. }
  1251. TEST(GetHeaderValueTest, RegularValue) {
  1252. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1253. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1254. EXPECT_STREQ("text/html", val);
  1255. }
  1256. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1257. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1258. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1259. EXPECT_STREQ("text/html", val);
  1260. }
  1261. TEST(GetHeaderValueTest, SetContent) {
  1262. Response res;
  1263. res.set_content("html", "text/html");
  1264. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1265. res.set_content("text", "text/plain");
  1266. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1267. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1268. }
  1269. TEST(GetHeaderValueTest, RegularValueInt) {
  1270. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1271. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1272. EXPECT_EQ(100ull, val);
  1273. }
  1274. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1275. Headers headers = {{"Content-Length", "x"}};
  1276. auto is_invalid_value = false;
  1277. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1278. is_invalid_value);
  1279. EXPECT_EQ(0ull, val);
  1280. EXPECT_TRUE(is_invalid_value);
  1281. }
  1282. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1283. // An all-digit value that overflows size_t must be reported as invalid, not
  1284. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1285. // a large length to a small one on 32-bit builds, leaving the framing length
  1286. // wrong while is_invalid_value stayed false.
  1287. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1288. auto is_invalid_value = false;
  1289. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1290. is_invalid_value);
  1291. EXPECT_TRUE(is_invalid_value);
  1292. // A well-formed length is unaffected.
  1293. Headers ok = {{"Content-Length", "1234"}};
  1294. is_invalid_value = false;
  1295. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1296. is_invalid_value);
  1297. EXPECT_EQ(1234ull, val);
  1298. EXPECT_FALSE(is_invalid_value);
  1299. }
  1300. TEST(GetHeaderValueTest, Range) {
  1301. {
  1302. Headers headers = {make_range_header({{1, -1}})};
  1303. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1304. EXPECT_STREQ("bytes=1-", val);
  1305. }
  1306. {
  1307. Headers headers = {make_range_header({{-1, 1}})};
  1308. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1309. EXPECT_STREQ("bytes=-1", val);
  1310. }
  1311. {
  1312. Headers headers = {make_range_header({{1, 10}})};
  1313. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1314. EXPECT_STREQ("bytes=1-10", val);
  1315. }
  1316. {
  1317. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1318. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1319. EXPECT_STREQ("bytes=1-10, 100-", val);
  1320. }
  1321. {
  1322. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1323. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1324. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1325. }
  1326. {
  1327. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=0-0, -1", val);
  1330. }
  1331. }
  1332. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1333. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1334. // to depend on the standard library (libstdc++ handed back duplicates in
  1335. // reverse insertion order, libc++ in insertion order).
  1336. Request req;
  1337. req.set_header("Accept-Encoding", "gzip");
  1338. req.set_header("Accept-Encoding", "deflate");
  1339. req.set_header("Accept-Encoding", "br");
  1340. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1341. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1342. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1343. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1344. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1345. }
  1346. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1347. Request req;
  1348. req.set_header("X-Test", "only");
  1349. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1350. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1351. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1352. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1353. }
  1354. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1355. Headers headers;
  1356. headers.emplace("Host", "example.com");
  1357. headers.emplace("Accept-Encoding", "gzip");
  1358. headers.emplace("User-Agent", "test");
  1359. headers.emplace("Accept-Encoding", "deflate");
  1360. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1361. "Accept-Encoding=deflate ",
  1362. entries_to_string(headers));
  1363. }
  1364. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1365. Headers headers = {{"Content-Type", "text/html"},
  1366. {"CONTENT-TYPE", "text/xml"}};
  1367. EXPECT_EQ(2U, headers.count("content-type"));
  1368. auto it = headers.find("content-type");
  1369. ASSERT_TRUE(it != headers.end());
  1370. EXPECT_EQ("text/html", it->second);
  1371. }
  1372. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1373. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1374. // drop only those fields and leave everything positioned between them.
  1375. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1376. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1377. auto rng = headers.equal_range("a");
  1378. headers.erase(rng.first, rng.second);
  1379. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1380. }
  1381. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1382. Headers headers = {
  1383. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1384. EXPECT_EQ(3U, headers.erase("A"));
  1385. EXPECT_EQ(0U, headers.count("A"));
  1386. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1387. }
  1388. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1389. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1390. headers.emplace_front("Host", "example.com");
  1391. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1392. entries_to_string(headers));
  1393. }
  1394. TEST(ParseHeaderValueTest, Range) {
  1395. {
  1396. Ranges ranges;
  1397. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1398. EXPECT_TRUE(ret);
  1399. EXPECT_EQ(1u, ranges.size());
  1400. EXPECT_EQ(1u, ranges[0].first);
  1401. EXPECT_EQ(-1, ranges[0].second);
  1402. }
  1403. {
  1404. Ranges ranges;
  1405. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1406. EXPECT_TRUE(ret);
  1407. EXPECT_EQ(1u, ranges.size());
  1408. EXPECT_EQ(-1, ranges[0].first);
  1409. EXPECT_EQ(1u, ranges[0].second);
  1410. }
  1411. {
  1412. Ranges ranges;
  1413. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1414. EXPECT_TRUE(ret);
  1415. EXPECT_EQ(1u, ranges.size());
  1416. EXPECT_EQ(1u, ranges[0].first);
  1417. EXPECT_EQ(10u, ranges[0].second);
  1418. }
  1419. {
  1420. Ranges ranges;
  1421. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1422. EXPECT_FALSE(ret);
  1423. }
  1424. {
  1425. Ranges ranges;
  1426. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1427. EXPECT_TRUE(ret);
  1428. EXPECT_EQ(2u, ranges.size());
  1429. EXPECT_EQ(1u, ranges[0].first);
  1430. EXPECT_EQ(10u, ranges[0].second);
  1431. EXPECT_EQ(100u, ranges[1].first);
  1432. EXPECT_EQ(-1, ranges[1].second);
  1433. }
  1434. {
  1435. Ranges ranges;
  1436. auto ret =
  1437. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1438. EXPECT_TRUE(ret);
  1439. EXPECT_EQ(3u, ranges.size());
  1440. EXPECT_EQ(1u, ranges[0].first);
  1441. EXPECT_EQ(10u, ranges[0].second);
  1442. EXPECT_EQ(100u, ranges[1].first);
  1443. EXPECT_EQ(200u, ranges[1].second);
  1444. EXPECT_EQ(300u, ranges[2].first);
  1445. EXPECT_EQ(400u, ranges[2].second);
  1446. }
  1447. {
  1448. Ranges ranges;
  1449. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1450. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1451. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1452. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1453. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1454. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1455. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1456. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1457. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1458. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1459. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1460. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1461. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1462. EXPECT_TRUE(ranges.empty());
  1463. }
  1464. }
  1465. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1466. Request req;
  1467. req.set_header("Accept-Encoding", "gzip");
  1468. Response res;
  1469. res.set_header("Content-Type", "text/plain");
  1470. auto ret = detail::encoding_type(req, res);
  1471. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1472. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1473. #else
  1474. EXPECT_TRUE(ret == detail::EncodingType::None);
  1475. #endif
  1476. }
  1477. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1478. Request req;
  1479. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1480. Response res;
  1481. res.set_header("Content-Type", "text/plain");
  1482. auto ret = detail::encoding_type(req, res);
  1483. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1484. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1485. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1486. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1487. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1488. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1489. #else
  1490. EXPECT_TRUE(ret == detail::EncodingType::None);
  1491. #endif
  1492. }
  1493. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1494. Request req;
  1495. req.set_header("Accept-Encoding",
  1496. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1497. Response res;
  1498. res.set_header("Content-Type", "text/plain");
  1499. auto ret = detail::encoding_type(req, res);
  1500. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1501. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1502. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1503. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1504. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1505. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1506. #else
  1507. EXPECT_TRUE(ret == detail::EncodingType::None);
  1508. #endif
  1509. }
  1510. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1511. // All supported encodings rejected with q=0 should return None
  1512. Request req;
  1513. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1514. Response res;
  1515. res.set_header("Content-Type", "text/plain");
  1516. auto ret = detail::encoding_type(req, res);
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. }
  1519. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1520. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1521. Request req;
  1522. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1523. Response res;
  1524. res.set_header("Content-Type", "text/plain");
  1525. auto ret = detail::encoding_type(req, res);
  1526. EXPECT_TRUE(ret == detail::EncodingType::None);
  1527. }
  1528. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1529. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1530. Request req;
  1531. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1532. Response res;
  1533. res.set_header("Content-Type", "text/plain");
  1534. auto ret = detail::encoding_type(req, res);
  1535. EXPECT_TRUE(ret == detail::EncodingType::None);
  1536. }
  1537. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1538. // RFC 7231: Accept-Encoding values are case-insensitive
  1539. Request req;
  1540. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1541. Response res;
  1542. res.set_header("Content-Type", "text/plain");
  1543. auto ret = detail::encoding_type(req, res);
  1544. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1545. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1546. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1547. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1548. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1549. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1550. #else
  1551. EXPECT_TRUE(ret == detail::EncodingType::None);
  1552. #endif
  1553. }
  1554. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1555. // q value should determine priority, not hardcoded order
  1556. Request req;
  1557. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1558. Response res;
  1559. res.set_header("Content-Type", "text/plain");
  1560. auto ret = detail::encoding_type(req, res);
  1561. // gzip has highest q=1.0, so it should be selected even though
  1562. // br and zstd are also supported
  1563. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1564. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1565. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1566. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1567. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1568. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1569. #else
  1570. EXPECT_TRUE(ret == detail::EncodingType::None);
  1571. #endif
  1572. }
  1573. TEST(BufferStreamTest, read) {
  1574. detail::BufferStream strm1;
  1575. Stream &strm = strm1;
  1576. EXPECT_EQ(5, strm.write("hello"));
  1577. char buf[512];
  1578. EXPECT_EQ(2, strm.read(buf, 2));
  1579. EXPECT_EQ('h', buf[0]);
  1580. EXPECT_EQ('e', buf[1]);
  1581. EXPECT_EQ(2, strm.read(buf, 2));
  1582. EXPECT_EQ('l', buf[0]);
  1583. EXPECT_EQ('l', buf[1]);
  1584. EXPECT_EQ(1, strm.read(buf, 1));
  1585. EXPECT_EQ('o', buf[0]);
  1586. EXPECT_EQ(0, strm.read(buf, 1));
  1587. }
  1588. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1589. auto host = "www.httpwatch.com";
  1590. auto ip = hosted_at(host);
  1591. EXPECT_EQ("23.96.13.243", ip);
  1592. std::vector<std::string> addrs;
  1593. hosted_at(host, addrs);
  1594. EXPECT_EQ(1u, addrs.size());
  1595. }
  1596. #if 0 // It depends on each test environment...
  1597. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1598. auto host = "www.youtube.com";
  1599. std::vector<std::string> addrs;
  1600. hosted_at(host, addrs);
  1601. EXPECT_EQ(20u, addrs.size());
  1602. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1603. EXPECT_TRUE(it != addrs.end());
  1604. }
  1605. #endif
  1606. class ChunkedEncodingTest : public ::testing::Test {
  1607. protected:
  1608. ChunkedEncodingTest()
  1609. : cli_(HOST, PORT)
  1610. #ifdef CPPHTTPLIB_SSL_ENABLED
  1611. ,
  1612. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1613. #endif
  1614. {
  1615. cli_.set_connection_timeout(2);
  1616. #ifdef CPPHTTPLIB_SSL_ENABLED
  1617. cli_.enable_server_certificate_verification(false);
  1618. #endif
  1619. }
  1620. virtual void SetUp() {
  1621. read_file("./image.jpg", image_data_);
  1622. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1623. res.set_content("Hello World!", "text/plain");
  1624. });
  1625. svr_.Get(
  1626. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1627. res.set_chunked_content_provider(
  1628. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1629. size_t remaining = image_data_.size() - offset;
  1630. if (remaining == 0) {
  1631. sink.done();
  1632. } else {
  1633. constexpr size_t CHUNK_SIZE = 1024;
  1634. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1635. sink.write(&image_data_[offset], send_size);
  1636. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1637. }
  1638. return true;
  1639. });
  1640. });
  1641. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1642. svr_.wait_until_ready();
  1643. }
  1644. virtual void TearDown() {
  1645. svr_.stop();
  1646. if (!request_threads_.empty()) {
  1647. std::this_thread::sleep_for(std::chrono::seconds(1));
  1648. for (auto &t : request_threads_) {
  1649. t.join();
  1650. }
  1651. }
  1652. t_.join();
  1653. }
  1654. #ifdef CPPHTTPLIB_SSL_ENABLED
  1655. SSLClient cli_;
  1656. SSLServer svr_;
  1657. #else
  1658. Client cli_;
  1659. Server svr_;
  1660. #endif
  1661. thread t_;
  1662. std::vector<thread> request_threads_;
  1663. std::string image_data_;
  1664. };
  1665. TEST_F(ChunkedEncodingTest, NormalGet) {
  1666. auto res = cli_.Get("/chunked");
  1667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1668. std::string out;
  1669. read_file("./image.jpg", out);
  1670. EXPECT_EQ(StatusCode::OK_200, res->status);
  1671. EXPECT_EQ(out, res->body);
  1672. }
  1673. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1674. std::string body;
  1675. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1676. body.append(data, data_length);
  1677. return true;
  1678. });
  1679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1680. std::string out;
  1681. read_file("./image.jpg", out);
  1682. EXPECT_EQ(StatusCode::OK_200, res->status);
  1683. EXPECT_EQ(out, body);
  1684. }
  1685. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1686. std::string body;
  1687. auto res = cli_.Get(
  1688. "/chunked",
  1689. [&](const Response &response) {
  1690. EXPECT_EQ(StatusCode::OK_200, response.status);
  1691. return true;
  1692. },
  1693. [&](const char *data, size_t data_length) {
  1694. body.append(data, data_length);
  1695. return true;
  1696. });
  1697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1698. std::string out;
  1699. read_file("./image.jpg", out);
  1700. EXPECT_EQ(StatusCode::OK_200, res->status);
  1701. EXPECT_EQ(out, body);
  1702. }
  1703. TEST(RangeTest, FromHTTPBin_Online) {
  1704. auto host = "httpbingo.org";
  1705. auto path = std::string{"/range/32"};
  1706. #ifdef CPPHTTPLIB_SSL_ENABLED
  1707. auto port = 443;
  1708. SSLClient cli(host, port);
  1709. #else
  1710. auto port = 80;
  1711. Client cli(host, port);
  1712. #endif
  1713. cli.set_connection_timeout(5);
  1714. {
  1715. auto res = cli.Get(path);
  1716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1717. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1718. EXPECT_EQ(StatusCode::OK_200, res->status);
  1719. }
  1720. {
  1721. Headers headers = {make_range_header({{1, -1}})};
  1722. auto res = cli.Get(path, headers);
  1723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1724. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1725. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1726. }
  1727. {
  1728. Headers headers = {make_range_header({{1, 10}})};
  1729. auto res = cli.Get(path, headers);
  1730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1731. EXPECT_EQ("bcdefghijk", res->body);
  1732. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1733. }
  1734. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1735. // entire resource, while the original httpbin returned 200. Both are
  1736. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1737. {
  1738. Headers headers = {make_range_header({{0, 31}})};
  1739. auto res = cli.Get(path, headers);
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1742. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1743. res->status == StatusCode::PartialContent_206);
  1744. }
  1745. {
  1746. Headers headers = {make_range_header({{0, -1}})};
  1747. auto res = cli.Get(path, headers);
  1748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1749. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1750. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1751. res->status == StatusCode::PartialContent_206);
  1752. }
  1753. // go-httpbin returns 206 with clamped range for over-range requests,
  1754. // while the original httpbin returned 416. Both behaviors are observed
  1755. // in real servers, so we only verify the request succeeds.
  1756. {
  1757. Headers headers = {make_range_header({{0, 32}})};
  1758. auto res = cli.Get(path, headers);
  1759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1760. }
  1761. }
  1762. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1763. auto host = "unresolvableaddress.local";
  1764. auto path = std::string{"/"};
  1765. #ifdef CPPHTTPLIB_SSL_ENABLED
  1766. auto port = 443;
  1767. SSLClient cli(host, port);
  1768. #else
  1769. auto port = 80;
  1770. Client cli(host, port);
  1771. #endif
  1772. cli.set_connection_timeout(1);
  1773. {
  1774. auto res = cli.Get(path);
  1775. ASSERT_FALSE(res);
  1776. }
  1777. std::this_thread::sleep_for(std::chrono::seconds(8));
  1778. }
  1779. #if defined(__linux__) && defined(__GLIBC__) && \
  1780. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1781. // Forward declaration: in split builds split.py strips `inline` and moves the
  1782. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1783. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1784. // against the symbol in both header-only and split builds.
  1785. namespace httplib {
  1786. namespace detail {
  1787. int getaddrinfo_with_timeout(const char *node, const char *service,
  1788. const struct addrinfo *hints,
  1789. struct addrinfo **res, time_t timeout_sec);
  1790. } // namespace detail
  1791. } // namespace httplib
  1792. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1793. //
  1794. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1795. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1796. // gai_suspend() call hits the connection timeout the function calls
  1797. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1798. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1799. // still alive and still references the now-destroyed stack frame.
  1800. //
  1801. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1802. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1803. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1804. // and runs them in a container.
  1805. namespace {
  1806. bool should_run_issue_2431_tests() {
  1807. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1808. return v && *v && std::string(v) != "0";
  1809. }
  1810. std::string unique_unresolvable_host(int n) {
  1811. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1812. // glibc still asks the configured nameserver — which is exactly the path
  1813. // we want to exercise. A unique label per call avoids the resolver cache.
  1814. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1815. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1816. std::to_string(n) + ".invalid";
  1817. }
  1818. } // namespace
  1819. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1820. if (!should_run_issue_2431_tests()) {
  1821. GTEST_SKIP()
  1822. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1823. }
  1824. for (int i = 0; i < 8; ++i) {
  1825. struct addrinfo hints;
  1826. memset(&hints, 0, sizeof(hints));
  1827. hints.ai_family = AF_UNSPEC;
  1828. hints.ai_socktype = SOCK_STREAM;
  1829. auto host = unique_unresolvable_host(i);
  1830. struct addrinfo *result = nullptr;
  1831. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1832. &result, /*timeout_sec=*/1);
  1833. if (rc == 0 && result) { freeaddrinfo(result); }
  1834. }
  1835. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1836. // stack region they still believe holds their gaicb.
  1837. std::this_thread::sleep_for(std::chrono::seconds(3));
  1838. }
  1839. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1840. if (!should_run_issue_2431_tests()) {
  1841. GTEST_SKIP()
  1842. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1843. }
  1844. std::atomic<bool> stop{false};
  1845. std::vector<std::thread> threads;
  1846. for (int t = 0; t < 8; ++t) {
  1847. threads.emplace_back([t, &stop] {
  1848. int i = 0;
  1849. while (!stop.load(std::memory_order_relaxed)) {
  1850. struct addrinfo hints;
  1851. memset(&hints, 0, sizeof(hints));
  1852. hints.ai_family = AF_UNSPEC;
  1853. hints.ai_socktype = SOCK_STREAM;
  1854. auto host = unique_unresolvable_host(t * 100000 + i++);
  1855. struct addrinfo *result = nullptr;
  1856. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1857. &result, /*timeout_sec=*/1);
  1858. if (rc == 0 && result) { freeaddrinfo(result); }
  1859. }
  1860. });
  1861. }
  1862. std::this_thread::sleep_for(std::chrono::seconds(8));
  1863. stop.store(true, std::memory_order_relaxed);
  1864. for (auto &th : threads) {
  1865. th.join();
  1866. }
  1867. std::this_thread::sleep_for(std::chrono::seconds(3));
  1868. }
  1869. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1870. if (!should_run_issue_2431_tests()) {
  1871. GTEST_SKIP()
  1872. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1873. }
  1874. std::atomic<bool> stop{false};
  1875. std::vector<std::thread> threads;
  1876. for (int t = 0; t < 8; ++t) {
  1877. threads.emplace_back([t, &stop] {
  1878. int i = 0;
  1879. while (!stop.load(std::memory_order_relaxed)) {
  1880. auto host = unique_unresolvable_host(t * 100000 + i++);
  1881. Client cli(host, 80);
  1882. cli.set_connection_timeout(1, 0);
  1883. cli.set_read_timeout(1, 0);
  1884. cli.set_write_timeout(1, 0);
  1885. (void)cli.Get("/");
  1886. }
  1887. });
  1888. }
  1889. std::this_thread::sleep_for(std::chrono::seconds(8));
  1890. stop.store(true, std::memory_order_relaxed);
  1891. for (auto &th : threads) {
  1892. th.join();
  1893. }
  1894. std::this_thread::sleep_for(std::chrono::seconds(3));
  1895. }
  1896. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1897. TEST(ConnectionErrorTest, InvalidHost) {
  1898. auto host = "-abcde.com";
  1899. #ifdef CPPHTTPLIB_SSL_ENABLED
  1900. auto port = 443;
  1901. SSLClient cli(host, port);
  1902. #else
  1903. auto port = 80;
  1904. Client cli(host, port);
  1905. #endif
  1906. cli.set_connection_timeout(std::chrono::seconds(2));
  1907. auto res = cli.Get("/");
  1908. ASSERT_TRUE(!res);
  1909. EXPECT_EQ(Error::Connection, res.error());
  1910. }
  1911. TEST(ConnectionErrorTest, InvalidHost2) {
  1912. auto host = "httpcan.org/";
  1913. #ifdef CPPHTTPLIB_SSL_ENABLED
  1914. SSLClient cli(host);
  1915. #else
  1916. Client cli(host);
  1917. #endif
  1918. cli.set_connection_timeout(std::chrono::seconds(2));
  1919. auto res = cli.Get("/");
  1920. ASSERT_TRUE(!res);
  1921. EXPECT_EQ(Error::Connection, res.error());
  1922. }
  1923. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1924. auto host = "httpcan.org/";
  1925. #ifdef CPPHTTPLIB_SSL_ENABLED
  1926. SSLClient cli(host);
  1927. #else
  1928. Client cli(host);
  1929. #endif
  1930. cli.set_connection_timeout(std::chrono::seconds(2));
  1931. auto res = cli.Get("/");
  1932. ASSERT_TRUE(!res);
  1933. stringstream s;
  1934. s << "error code: " << res.error();
  1935. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1936. }
  1937. TEST(ConnectionErrorTest, InvalidPort) {
  1938. auto host = "localhost";
  1939. auto port = 44380;
  1940. #ifdef CPPHTTPLIB_SSL_ENABLED
  1941. SSLClient cli(host, port);
  1942. #else
  1943. Client cli(host, port);
  1944. #endif
  1945. cli.set_connection_timeout(std::chrono::seconds(2));
  1946. auto res = cli.Get("/");
  1947. ASSERT_TRUE(!res);
  1948. EXPECT_TRUE(Error::Connection == res.error() ||
  1949. Error::ConnectionTimeout == res.error());
  1950. }
  1951. TEST(ConnectionErrorTest, Timeout_Online) {
  1952. auto host = "google.com";
  1953. #ifdef CPPHTTPLIB_SSL_ENABLED
  1954. auto port = 44380;
  1955. SSLClient cli(host, port);
  1956. #else
  1957. auto port = 8080;
  1958. Client cli(host, port);
  1959. #endif
  1960. cli.set_connection_timeout(std::chrono::seconds(2));
  1961. // only probe one address type so that the error reason
  1962. // correlates to the timed-out IPv4, not the unsupported
  1963. // IPv6 connection attempt
  1964. cli.set_address_family(AF_INET);
  1965. auto res = cli.Get("/");
  1966. ASSERT_TRUE(!res);
  1967. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1968. }
  1969. TEST(CancelTest, NoCancel_Online) {
  1970. auto host = "httpbingo.org";
  1971. auto path = std::string{"/range/32"};
  1972. #ifdef CPPHTTPLIB_SSL_ENABLED
  1973. auto port = 443;
  1974. SSLClient cli(host, port);
  1975. #else
  1976. auto port = 80;
  1977. Client cli(host, port);
  1978. #endif
  1979. cli.set_connection_timeout(std::chrono::seconds(5));
  1980. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1982. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1983. EXPECT_EQ(StatusCode::OK_200, res->status);
  1984. }
  1985. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1986. // Use /bytes with a large payload so that the DownloadProgress callback
  1987. // (which only fires for Content-Length responses) is invoked before the
  1988. // entire body is received, giving cancellation a chance to fire.
  1989. auto host = "httpbingo.org";
  1990. auto path = std::string{"/bytes/524288"};
  1991. #ifdef CPPHTTPLIB_SSL_ENABLED
  1992. auto port = 443;
  1993. SSLClient cli(host, port);
  1994. #else
  1995. auto port = 80;
  1996. Client cli(host, port);
  1997. #endif
  1998. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1999. cli.set_connection_timeout(std::chrono::seconds(5));
  2000. ASSERT_TRUE(!res);
  2001. EXPECT_EQ(Error::Canceled, res.error());
  2002. }
  2003. TEST(CancelTest, WithCancelLargePayload_Online) {
  2004. auto host = "httpbingo.org";
  2005. auto path = std::string{"/bytes/524288"};
  2006. #ifdef CPPHTTPLIB_SSL_ENABLED
  2007. auto port = 443;
  2008. SSLClient cli(host, port);
  2009. #else
  2010. auto port = 80;
  2011. Client cli(host, port);
  2012. #endif
  2013. cli.set_connection_timeout(std::chrono::seconds(5));
  2014. uint32_t count = 0;
  2015. auto res =
  2016. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2017. ASSERT_TRUE(!res);
  2018. EXPECT_EQ(Error::Canceled, res.error());
  2019. }
  2020. TEST(CancelTest, NoCancelPost) {
  2021. Server svr;
  2022. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2023. res.set_content("Hello World!", "text/plain");
  2024. });
  2025. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2026. auto se = detail::scope_exit([&] {
  2027. svr.stop();
  2028. thread.join();
  2029. ASSERT_FALSE(svr.is_running());
  2030. });
  2031. svr.wait_until_ready();
  2032. Client cli(HOST, PORT);
  2033. cli.set_connection_timeout(std::chrono::seconds(5));
  2034. auto res =
  2035. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2036. "application/json", [](uint64_t, uint64_t) { return true; });
  2037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2038. EXPECT_EQ("Hello World!", res->body);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. }
  2041. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2042. Server svr;
  2043. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2044. res.set_content("Hello World!", "text/plain");
  2045. });
  2046. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2047. auto se = detail::scope_exit([&] {
  2048. svr.stop();
  2049. thread.join();
  2050. ASSERT_FALSE(svr.is_running());
  2051. });
  2052. svr.wait_until_ready();
  2053. Client cli(HOST, PORT);
  2054. cli.set_connection_timeout(std::chrono::seconds(5));
  2055. auto res =
  2056. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2057. "application/json", [](uint64_t, uint64_t) { return false; });
  2058. ASSERT_TRUE(!res);
  2059. EXPECT_EQ(Error::Canceled, res.error());
  2060. }
  2061. TEST(CancelTest, WithCancelLargePayloadPost) {
  2062. Server svr;
  2063. svr.set_payload_max_length(200 * 1024 * 1024);
  2064. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2065. res.set_content(LARGE_DATA, "text/plain");
  2066. });
  2067. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2068. auto se = detail::scope_exit([&] {
  2069. svr.stop();
  2070. thread.join();
  2071. ASSERT_FALSE(svr.is_running());
  2072. });
  2073. svr.wait_until_ready();
  2074. Client cli(HOST, PORT);
  2075. cli.set_payload_max_length(200 * 1024 * 1024);
  2076. cli.set_connection_timeout(std::chrono::seconds(5));
  2077. auto res =
  2078. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2079. "application/json", [](uint64_t, uint64_t) { return false; });
  2080. ASSERT_TRUE(!res);
  2081. EXPECT_EQ(Error::Canceled, res.error());
  2082. }
  2083. TEST(CancelTest, NoCancelPut) {
  2084. Server svr;
  2085. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2086. res.set_content("Hello World!", "text/plain");
  2087. });
  2088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2089. auto se = detail::scope_exit([&] {
  2090. svr.stop();
  2091. thread.join();
  2092. ASSERT_FALSE(svr.is_running());
  2093. });
  2094. svr.wait_until_ready();
  2095. Client cli(HOST, PORT);
  2096. cli.set_connection_timeout(std::chrono::seconds(5));
  2097. auto res =
  2098. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2099. "application/json", [](uint64_t, uint64_t) { return true; });
  2100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2101. EXPECT_EQ("Hello World!", res->body);
  2102. EXPECT_EQ(StatusCode::OK_200, res->status);
  2103. }
  2104. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2105. Server svr;
  2106. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2107. res.set_content("Hello World!", "text/plain");
  2108. });
  2109. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2110. auto se = detail::scope_exit([&] {
  2111. svr.stop();
  2112. thread.join();
  2113. ASSERT_FALSE(svr.is_running());
  2114. });
  2115. svr.wait_until_ready();
  2116. Client cli(HOST, PORT);
  2117. cli.set_connection_timeout(std::chrono::seconds(5));
  2118. auto res =
  2119. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2120. "application/json", [](uint64_t, uint64_t) { return false; });
  2121. ASSERT_TRUE(!res);
  2122. EXPECT_EQ(Error::Canceled, res.error());
  2123. }
  2124. TEST(CancelTest, WithCancelLargePayloadPut) {
  2125. Server svr;
  2126. svr.set_payload_max_length(200 * 1024 * 1024);
  2127. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2128. res.set_content(LARGE_DATA, "text/plain");
  2129. });
  2130. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2131. auto se = detail::scope_exit([&] {
  2132. svr.stop();
  2133. thread.join();
  2134. ASSERT_FALSE(svr.is_running());
  2135. });
  2136. svr.wait_until_ready();
  2137. Client cli(HOST, PORT);
  2138. cli.set_payload_max_length(200 * 1024 * 1024);
  2139. cli.set_connection_timeout(std::chrono::seconds(5));
  2140. auto res =
  2141. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2142. "application/json", [](uint64_t, uint64_t) { return false; });
  2143. ASSERT_TRUE(!res);
  2144. EXPECT_EQ(Error::Canceled, res.error());
  2145. }
  2146. TEST(CancelTest, NoCancelPatch) {
  2147. Server svr;
  2148. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2149. res.set_content("Hello World!", "text/plain");
  2150. });
  2151. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2152. auto se = detail::scope_exit([&] {
  2153. svr.stop();
  2154. thread.join();
  2155. ASSERT_FALSE(svr.is_running());
  2156. });
  2157. svr.wait_until_ready();
  2158. Client cli(HOST, PORT);
  2159. cli.set_connection_timeout(std::chrono::seconds(5));
  2160. auto res =
  2161. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2162. "application/json", [](uint64_t, uint64_t) { return true; });
  2163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2164. EXPECT_EQ("Hello World!", res->body);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. }
  2167. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2168. Server svr;
  2169. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2170. res.set_content("Hello World!", "text/plain");
  2171. });
  2172. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2173. auto se = detail::scope_exit([&] {
  2174. svr.stop();
  2175. thread.join();
  2176. ASSERT_FALSE(svr.is_running());
  2177. });
  2178. svr.wait_until_ready();
  2179. Client cli(HOST, PORT);
  2180. cli.set_connection_timeout(std::chrono::seconds(5));
  2181. auto res =
  2182. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2183. "application/json", [](uint64_t, uint64_t) { return false; });
  2184. ASSERT_TRUE(!res);
  2185. EXPECT_EQ(Error::Canceled, res.error());
  2186. }
  2187. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2188. Server svr;
  2189. svr.set_payload_max_length(200 * 1024 * 1024);
  2190. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2191. res.set_content(LARGE_DATA, "text/plain");
  2192. });
  2193. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2194. auto se = detail::scope_exit([&] {
  2195. svr.stop();
  2196. thread.join();
  2197. ASSERT_FALSE(svr.is_running());
  2198. });
  2199. svr.wait_until_ready();
  2200. Client cli(HOST, PORT);
  2201. cli.set_payload_max_length(200 * 1024 * 1024);
  2202. cli.set_connection_timeout(std::chrono::seconds(5));
  2203. auto res =
  2204. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2205. "application/json", [](uint64_t, uint64_t) { return false; });
  2206. ASSERT_TRUE(!res);
  2207. EXPECT_EQ(Error::Canceled, res.error());
  2208. }
  2209. TEST(CancelTest, NoCancelDelete) {
  2210. Server svr;
  2211. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2212. res.set_content("Hello World!", "text/plain");
  2213. });
  2214. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2215. auto se = detail::scope_exit([&] {
  2216. svr.stop();
  2217. thread.join();
  2218. ASSERT_FALSE(svr.is_running());
  2219. });
  2220. svr.wait_until_ready();
  2221. Client cli(HOST, PORT);
  2222. cli.set_connection_timeout(std::chrono::seconds(5));
  2223. auto res =
  2224. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2225. "application/json", [](uint64_t, uint64_t) { return true; });
  2226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2227. EXPECT_EQ("Hello World!", res->body);
  2228. EXPECT_EQ(StatusCode::OK_200, res->status);
  2229. }
  2230. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2231. Server svr;
  2232. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2233. res.set_content("Hello World!", "text/plain");
  2234. });
  2235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2236. auto se = detail::scope_exit([&] {
  2237. svr.stop();
  2238. thread.join();
  2239. ASSERT_FALSE(svr.is_running());
  2240. });
  2241. svr.wait_until_ready();
  2242. Client cli(HOST, PORT);
  2243. cli.set_connection_timeout(std::chrono::seconds(5));
  2244. auto res =
  2245. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2246. "application/json", [](uint64_t, uint64_t) { return false; });
  2247. ASSERT_TRUE(!res);
  2248. EXPECT_EQ(Error::Canceled, res.error());
  2249. }
  2250. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2251. Server svr;
  2252. svr.set_payload_max_length(200 * 1024 * 1024);
  2253. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2254. res.set_content(LARGE_DATA, "text/plain");
  2255. });
  2256. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2257. auto se = detail::scope_exit([&] {
  2258. svr.stop();
  2259. thread.join();
  2260. ASSERT_FALSE(svr.is_running());
  2261. });
  2262. svr.wait_until_ready();
  2263. Client cli(HOST, PORT);
  2264. cli.set_payload_max_length(200 * 1024 * 1024);
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. auto res =
  2267. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2268. "application/json", [](uint64_t, uint64_t) { return false; });
  2269. ASSERT_TRUE(!res);
  2270. EXPECT_EQ(Error::Canceled, res.error());
  2271. }
  2272. static std::string remove_whitespace(const std::string &input) {
  2273. std::string output;
  2274. output.reserve(input.size());
  2275. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2276. [](unsigned char c) { return !std::isspace(c); });
  2277. return output;
  2278. }
  2279. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2280. auto host = "httpbingo.org";
  2281. auto path = std::string{"/basic-auth/hello/world"};
  2282. #ifdef CPPHTTPLIB_SSL_ENABLED
  2283. auto port = 443;
  2284. SSLClient cli(host, port);
  2285. #else
  2286. auto port = 80;
  2287. Client cli(host, port);
  2288. #endif
  2289. {
  2290. auto res = cli.Get(path);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2293. }
  2294. {
  2295. auto res = cli.Get(
  2296. path, Headers{make_basic_authentication_header("hello", "world")});
  2297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2298. auto body = remove_whitespace(res->body);
  2299. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2300. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. {
  2304. cli.set_basic_auth("hello", "world");
  2305. auto res = cli.Get(path);
  2306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2307. auto body = remove_whitespace(res->body);
  2308. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2309. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2310. EXPECT_EQ(StatusCode::OK_200, res->status);
  2311. }
  2312. {
  2313. cli.set_basic_auth("hello", "bad");
  2314. auto res = cli.Get(path);
  2315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2316. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2317. }
  2318. {
  2319. cli.set_basic_auth("bad", "world");
  2320. auto res = cli.Get(path);
  2321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2322. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2323. }
  2324. }
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2327. auto host = "httpbingo.org";
  2328. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2329. auto paths = std::vector<std::string>{
  2330. "/digest-auth/auth/hello/world/MD5",
  2331. "/digest-auth/auth/hello/world/SHA-256",
  2332. };
  2333. auto port = 443;
  2334. SSLClient cli(host, port);
  2335. {
  2336. auto res = cli.Get(unauth_path);
  2337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2338. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2339. }
  2340. {
  2341. cli.set_digest_auth("hello", "world");
  2342. for (const auto &path : paths) {
  2343. auto res = cli.Get(path.c_str());
  2344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2345. auto body = remove_whitespace(res->body);
  2346. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2347. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2348. EXPECT_EQ(StatusCode::OK_200, res->status);
  2349. }
  2350. cli.set_digest_auth("hello", "bad");
  2351. for (const auto &path : paths) {
  2352. auto res = cli.Get(path.c_str());
  2353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2354. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2355. }
  2356. }
  2357. }
  2358. #endif
  2359. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2360. auto host = "google.com";
  2361. auto another_host = "example.com";
  2362. auto wrong_ip = "0.0.0.0";
  2363. #ifdef CPPHTTPLIB_SSL_ENABLED
  2364. SSLClient cli(host);
  2365. #else
  2366. Client cli(host);
  2367. #endif
  2368. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2369. auto res = cli.Get("/");
  2370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2371. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2372. }
  2373. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2374. auto host = "google.com";
  2375. auto wrong_ip = "0.0.0.0";
  2376. #ifdef CPPHTTPLIB_SSL_ENABLED
  2377. SSLClient cli(host);
  2378. #else
  2379. Client cli(host);
  2380. #endif
  2381. cli.set_hostname_addr_map({{host, wrong_ip}});
  2382. auto res = cli.Get("/");
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Connection, res.error());
  2385. }
  2386. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2387. // A mapped value that is not an IP literal must be resolved. "localhost"
  2388. // resolves from the hosts file, so this test needs no external DNS.
  2389. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2390. auto host = "target.invalid";
  2391. Server svr;
  2392. std::string received_host;
  2393. svr.Get("/hi", [&](const Request &req, Response &res) {
  2394. received_host = req.get_header_value("Host");
  2395. res.set_content("Hello World!", "text/plain");
  2396. });
  2397. auto port = svr.bind_to_any_port(HOST);
  2398. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2399. auto se = detail::scope_exit([&] {
  2400. svr.stop();
  2401. thread.join();
  2402. ASSERT_FALSE(svr.is_running());
  2403. });
  2404. svr.wait_until_ready();
  2405. Client cli(host, port);
  2406. cli.set_hostname_addr_map({{host, HOST}});
  2407. auto res = cli.Get("/hi");
  2408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2409. EXPECT_EQ(StatusCode::OK_200, res->status);
  2410. // The mapping only redirects the connection; the identity stays host_.
  2411. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2412. }
  2413. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2414. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2415. auto host = "target.invalid";
  2416. Server svr;
  2417. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2418. res.set_content("Hello World!", "text/plain");
  2419. });
  2420. auto port = svr.bind_to_any_port("127.0.0.1");
  2421. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2422. auto se = detail::scope_exit([&] {
  2423. svr.stop();
  2424. thread.join();
  2425. ASSERT_FALSE(svr.is_running());
  2426. });
  2427. svr.wait_until_ready();
  2428. Client cli(host, port);
  2429. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2430. auto res = cli.Get("/hi");
  2431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2432. EXPECT_EQ(StatusCode::OK_200, res->status);
  2433. }
  2434. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2435. // An empty mapped value must leave host_ as the connection target. Without
  2436. // that guard the empty value would become the host argument, getaddrinfo
  2437. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2438. // loopback - silently connecting somewhere the caller never asked for.
  2439. // The server listens on loopback, so such a fallback would succeed and is
  2440. // therefore observable as a failure of this test.
  2441. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2442. Server svr;
  2443. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2444. res.set_content("Hello World!", "text/plain");
  2445. });
  2446. auto port = svr.bind_to_any_port(HOST);
  2447. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2448. auto se = detail::scope_exit([&] {
  2449. svr.stop();
  2450. thread.join();
  2451. ASSERT_FALSE(svr.is_running());
  2452. });
  2453. svr.wait_until_ready();
  2454. Client cli(blackhole, port);
  2455. cli.set_hostname_addr_map({{blackhole, ""}});
  2456. cli.set_connection_timeout(1);
  2457. auto res = cli.Get("/hi");
  2458. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2459. }
  2460. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2461. auto host = "httpbingo.org";
  2462. auto path = std::string{"/absolute-redirect/3"};
  2463. #ifdef CPPHTTPLIB_SSL_ENABLED
  2464. SSLClient cli(host);
  2465. #else
  2466. Client cli(host);
  2467. #endif
  2468. cli.set_follow_location(true);
  2469. auto res = cli.Get(path);
  2470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2471. EXPECT_EQ(StatusCode::OK_200, res->status);
  2472. }
  2473. TEST(RedirectTest, Redirect_Online) {
  2474. auto host = "httpbingo.org";
  2475. auto path = std::string{"/redirect/3"};
  2476. #ifdef CPPHTTPLIB_SSL_ENABLED
  2477. SSLClient cli(host);
  2478. #else
  2479. Client cli(host);
  2480. #endif
  2481. cli.set_follow_location(true);
  2482. auto res = cli.Get(path);
  2483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2484. EXPECT_EQ(StatusCode::OK_200, res->status);
  2485. }
  2486. TEST(RelativeRedirectTest, Redirect_Online) {
  2487. auto host = "httpbingo.org";
  2488. auto path = std::string{"/relative-redirect/3"};
  2489. #ifdef CPPHTTPLIB_SSL_ENABLED
  2490. SSLClient cli(host);
  2491. #else
  2492. Client cli(host);
  2493. #endif
  2494. cli.set_follow_location(true);
  2495. auto res = cli.Get(path);
  2496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2497. EXPECT_EQ(StatusCode::OK_200, res->status);
  2498. }
  2499. TEST(TooManyRedirectTest, Redirect_Online) {
  2500. auto host = "httpbingo.org";
  2501. auto path = std::string{"/redirect/21"};
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. SSLClient cli(host);
  2504. #else
  2505. Client cli(host);
  2506. #endif
  2507. cli.set_follow_location(true);
  2508. auto res = cli.Get(path);
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2511. }
  2512. #ifdef CPPHTTPLIB_SSL_ENABLED
  2513. TEST(YahooRedirectTest, Redirect_Online) {
  2514. Client cli("yahoo.com");
  2515. auto res = cli.Get("/");
  2516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2517. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2518. cli.set_follow_location(true);
  2519. res = cli.Get("/");
  2520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2521. EXPECT_EQ(StatusCode::OK_200, res->status);
  2522. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2523. }
  2524. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2525. #define REDIR_HOST "httpbingo.org"
  2526. #define REDIR_PATH "/redirect-to"
  2527. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2528. SSLClient cli(REDIR_HOST);
  2529. cli.set_follow_location(true);
  2530. auto res =
  2531. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2533. EXPECT_EQ(StatusCode::OK_200, res->status);
  2534. }
  2535. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2536. SSLClient cli(REDIR_HOST);
  2537. cli.set_follow_location(true);
  2538. Params params;
  2539. params.emplace("url", "http://example.com");
  2540. params.emplace("status_code", "302");
  2541. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. }
  2545. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2546. SSLClient cli(REDIR_HOST);
  2547. cli.set_follow_location(true);
  2548. Params params;
  2549. params.emplace("url", "http://example.com");
  2550. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ(StatusCode::OK_200, res->status);
  2553. }
  2554. TEST(UrlWithSpace, Redirect_Online) {
  2555. SSLClient cli("edge.forgecdn.net");
  2556. cli.set_follow_location(true);
  2557. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. EXPECT_EQ(StatusCode::OK_200, res->status);
  2560. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2561. }
  2562. #endif
  2563. #if !defined(_WIN32) && !defined(_WIN64)
  2564. TEST(ReceiveSignals, Signal) {
  2565. auto setupSignalHandlers = []() {
  2566. struct sigaction act;
  2567. sigemptyset(&act.sa_mask);
  2568. act.sa_flags = SA_SIGINFO;
  2569. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2570. switch (sig) {
  2571. case SIGINT:
  2572. default: break;
  2573. }
  2574. };
  2575. ::sigaction(SIGINT, &act, nullptr);
  2576. };
  2577. Server svr;
  2578. int port = 0;
  2579. auto thread = std::thread([&]() {
  2580. setupSignalHandlers();
  2581. port = svr.bind_to_any_port(HOST);
  2582. svr.listen_after_bind();
  2583. });
  2584. auto se = detail::scope_exit([&] {
  2585. svr.stop();
  2586. thread.join();
  2587. ASSERT_FALSE(svr.is_running());
  2588. });
  2589. svr.wait_until_ready();
  2590. ASSERT_TRUE(svr.is_running());
  2591. pthread_kill(thread.native_handle(), SIGINT);
  2592. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2593. ASSERT_TRUE(svr.is_running());
  2594. }
  2595. #endif
  2596. TEST(RedirectToDifferentPort, Redirect) {
  2597. Server svr1;
  2598. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. int svr1_port = 0;
  2602. auto thread1 = std::thread([&]() {
  2603. svr1_port = svr1.bind_to_any_port(HOST);
  2604. svr1.listen_after_bind();
  2605. });
  2606. Server svr2;
  2607. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2608. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2609. });
  2610. int svr2_port = 0;
  2611. auto thread2 = std::thread([&]() {
  2612. svr2_port = svr2.bind_to_any_port(HOST);
  2613. svr2.listen_after_bind();
  2614. });
  2615. auto se = detail::scope_exit([&] {
  2616. svr2.stop();
  2617. thread2.join();
  2618. svr1.stop();
  2619. thread1.join();
  2620. ASSERT_FALSE(svr2.is_running());
  2621. ASSERT_FALSE(svr1.is_running());
  2622. });
  2623. svr1.wait_until_ready();
  2624. svr2.wait_until_ready();
  2625. Client cli("localhost", svr2_port);
  2626. cli.set_follow_location(true);
  2627. auto res = cli.Get("/2");
  2628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. EXPECT_EQ("Hello World!", res->body);
  2631. }
  2632. static void
  2633. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2634. Server svr1;
  2635. std::string captured_authorization;
  2636. svr1.Get("/target", [&](const Request &req, Response &res) {
  2637. captured_authorization = req.get_header_value("Authorization");
  2638. res.set_content("OK", "text/plain");
  2639. });
  2640. int svr1_port = 0;
  2641. auto thread1 = std::thread([&]() {
  2642. svr1_port = svr1.bind_to_any_port(HOST);
  2643. svr1.listen_after_bind();
  2644. });
  2645. Server svr2;
  2646. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2647. res.set_redirect(
  2648. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2649. });
  2650. int svr2_port = 0;
  2651. auto thread2 = std::thread([&]() {
  2652. svr2_port = svr2.bind_to_any_port(HOST);
  2653. svr2.listen_after_bind();
  2654. });
  2655. auto se = detail::scope_exit([&] {
  2656. svr2.stop();
  2657. thread2.join();
  2658. svr1.stop();
  2659. thread1.join();
  2660. ASSERT_FALSE(svr2.is_running());
  2661. ASSERT_FALSE(svr1.is_running());
  2662. });
  2663. svr1.wait_until_ready();
  2664. svr2.wait_until_ready();
  2665. Client cli("localhost", svr2_port);
  2666. cli.set_follow_location(true);
  2667. set_auth(cli);
  2668. auto res = cli.Get("/redir");
  2669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2670. EXPECT_EQ(StatusCode::OK_200, res->status);
  2671. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2672. EXPECT_TRUE(captured_authorization.empty());
  2673. }
  2674. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2675. TestDoNotForwardCredentialsOnRedirect(
  2676. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2677. }
  2678. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2679. TestDoNotForwardCredentialsOnRedirect(
  2680. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2681. }
  2682. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2683. Server svr1;
  2684. std::string captured_cookie;
  2685. bool target_hit = false;
  2686. svr1.Get("/target", [&](const Request &req, Response &res) {
  2687. captured_cookie = req.get_header_value("Cookie");
  2688. target_hit = true;
  2689. res.set_content("OK", "text/plain");
  2690. });
  2691. int svr1_port = 0;
  2692. auto thread1 = std::thread([&]() {
  2693. svr1_port = svr1.bind_to_any_port(HOST);
  2694. svr1.listen_after_bind();
  2695. });
  2696. Server svr2;
  2697. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2698. res.set_redirect(
  2699. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2700. });
  2701. int svr2_port = 0;
  2702. auto thread2 = std::thread([&]() {
  2703. svr2_port = svr2.bind_to_any_port(HOST);
  2704. svr2.listen_after_bind();
  2705. });
  2706. auto se = detail::scope_exit([&] {
  2707. svr2.stop();
  2708. thread2.join();
  2709. svr1.stop();
  2710. thread1.join();
  2711. ASSERT_FALSE(svr2.is_running());
  2712. ASSERT_FALSE(svr1.is_running());
  2713. });
  2714. svr1.wait_until_ready();
  2715. svr2.wait_until_ready();
  2716. Client cli("localhost", svr2_port);
  2717. cli.set_follow_location(true);
  2718. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2719. auto res = cli.Get("/redir", headers);
  2720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2721. EXPECT_EQ(StatusCode::OK_200, res->status);
  2722. EXPECT_TRUE(target_hit);
  2723. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2724. EXPECT_TRUE(captured_cookie.empty());
  2725. }
  2726. TEST(RedirectToSamePort, ForwardCookie) {
  2727. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2728. // header so that ordinary session flows keep working.
  2729. Server svr;
  2730. std::string captured_cookie;
  2731. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2732. res.set_redirect("/target", 302);
  2733. });
  2734. svr.Get("/target", [&](const Request &req, Response &res) {
  2735. captured_cookie = req.get_header_value("Cookie");
  2736. res.set_content("OK", "text/plain");
  2737. });
  2738. auto port = svr.bind_to_any_port(HOST);
  2739. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2740. auto se = detail::scope_exit([&] {
  2741. svr.stop();
  2742. thread.join();
  2743. ASSERT_FALSE(svr.is_running());
  2744. });
  2745. svr.wait_until_ready();
  2746. Client cli(HOST, port);
  2747. cli.set_follow_location(true);
  2748. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2749. auto res = cli.Get("/redir", headers);
  2750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2753. }
  2754. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2755. Server svr;
  2756. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2757. // Port number that overflows int — should not crash
  2758. res.set_redirect("http://localhost:99999999999999999999/target");
  2759. });
  2760. auto port = svr.bind_to_any_port(HOST);
  2761. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2762. auto se = detail::scope_exit([&] {
  2763. svr.stop();
  2764. thread.join();
  2765. ASSERT_FALSE(svr.is_running());
  2766. });
  2767. svr.wait_until_ready();
  2768. Client cli(HOST, port);
  2769. cli.set_follow_location(true);
  2770. auto res = cli.Get("/redir");
  2771. // Should fail gracefully, not crash (no valid response due to bad port)
  2772. EXPECT_FALSE(res);
  2773. }
  2774. TEST(RedirectFromPageWithContent, Redirect) {
  2775. Server svr;
  2776. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2777. res.set_content("___", "text/plain");
  2778. res.set_redirect("/2");
  2779. });
  2780. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content("Hello World!", "text/plain");
  2782. });
  2783. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. th.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. {
  2791. Client cli("localhost", PORT);
  2792. cli.set_follow_location(true);
  2793. std::string body;
  2794. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2795. body.append(data, data_length);
  2796. return true;
  2797. });
  2798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2799. EXPECT_EQ(StatusCode::OK_200, res->status);
  2800. EXPECT_EQ("Hello World!", body);
  2801. }
  2802. {
  2803. Client cli("localhost", PORT);
  2804. std::string body;
  2805. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2806. body.append(data, data_length);
  2807. return true;
  2808. });
  2809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2810. EXPECT_EQ(StatusCode::Found_302, res->status);
  2811. EXPECT_EQ("___", body);
  2812. }
  2813. }
  2814. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2815. Server svr;
  2816. auto port_str = std::to_string(PORT);
  2817. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2818. auto expected_host = "[::1]:" + port_str;
  2819. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2820. res.set_content("___", "text/plain");
  2821. // res.set_redirect("/2");
  2822. res.set_redirect(redirect_url);
  2823. });
  2824. svr.Get("/2", [&](const Request &req, Response &res) {
  2825. auto host_header = req.headers.find("Host");
  2826. ASSERT_TRUE(host_header != req.headers.end());
  2827. EXPECT_EQ(expected_host, host_header->second);
  2828. res.set_content("Hello World!", "text/plain");
  2829. });
  2830. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2831. auto se = detail::scope_exit([&] {
  2832. svr.stop();
  2833. th.join();
  2834. ASSERT_FALSE(svr.is_running());
  2835. });
  2836. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2837. // actually starts anything, so the condition !svr.is_running() will
  2838. // always remain true, and the loop never stops.
  2839. // This basically counts how many milliseconds have passed since the
  2840. // call to svr.listen(), and if after 5 seconds nothing started yet
  2841. // aborts the test.
  2842. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2843. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2844. ASSERT_LT(milliseconds, 5000U);
  2845. }
  2846. {
  2847. Client cli("::1", PORT);
  2848. cli.set_follow_location(true);
  2849. std::string body;
  2850. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2851. body.append(data, data_length);
  2852. return true;
  2853. });
  2854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2855. EXPECT_EQ(StatusCode::OK_200, res->status);
  2856. EXPECT_EQ("Hello World!", body);
  2857. }
  2858. {
  2859. Client cli("::1", PORT);
  2860. std::string body;
  2861. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2862. body.append(data, data_length);
  2863. return true;
  2864. });
  2865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2866. EXPECT_EQ(StatusCode::Found_302, res->status);
  2867. EXPECT_EQ("___", body);
  2868. }
  2869. }
  2870. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2871. Server svr;
  2872. svr.Get("/foo", [](const Request &req, Response &res) {
  2873. auto a = req.params.find("a");
  2874. if (a != req.params.end()) {
  2875. res.set_content((*a).second, "text/plain");
  2876. res.status = StatusCode::OK_200;
  2877. } else {
  2878. res.status = StatusCode::BadRequest_400;
  2879. }
  2880. });
  2881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. thread.join();
  2885. ASSERT_FALSE(svr.is_running());
  2886. });
  2887. svr.wait_until_ready();
  2888. {
  2889. Client cli(HOST, PORT);
  2890. cli.set_path_encode(false);
  2891. auto res = cli.Get("/foo?a=explicitly+encoded");
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::OK_200, res->status);
  2894. // This expects it back with a space, as the `+` won't have been
  2895. // url-encoded, and server-side the params get decoded turning `+`
  2896. // into spaces.
  2897. EXPECT_EQ("explicitly encoded", res->body);
  2898. }
  2899. }
  2900. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2901. // When path encoding is disabled the client must transmit the supplied
  2902. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2903. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2904. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2905. // than a space (0x20). Assert on the raw wire target to catch this.
  2906. Server svr;
  2907. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2908. svr.Get("/foo", [&](const Request &req, Response &res) {
  2909. EXPECT_EQ(expected_target, req.target);
  2910. res.status = StatusCode::OK_200;
  2911. });
  2912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2913. auto se = detail::scope_exit([&] {
  2914. svr.stop();
  2915. thread.join();
  2916. ASSERT_FALSE(svr.is_running());
  2917. });
  2918. svr.wait_until_ready();
  2919. {
  2920. Client cli(HOST, PORT);
  2921. cli.set_path_encode(false);
  2922. auto res = cli.Get(expected_target.c_str());
  2923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2924. EXPECT_EQ(StatusCode::OK_200, res->status);
  2925. }
  2926. }
  2927. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2928. // `open_stream()` used to skip the path encoding that the buffered send
  2929. // path applies, so the same `path` produced different bytes in the request
  2930. // line depending on which API was used. Assert the two agree.
  2931. Server svr;
  2932. std::string target;
  2933. svr.Get(".*", [&](const Request &req, Response &res) {
  2934. target = req.target;
  2935. res.status = StatusCode::OK_200;
  2936. });
  2937. auto port = svr.bind_to_any_port(HOST);
  2938. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2939. auto se = detail::scope_exit([&] {
  2940. svr.stop();
  2941. thread.join();
  2942. ASSERT_FALSE(svr.is_running());
  2943. });
  2944. svr.wait_until_ready();
  2945. struct {
  2946. const char *path;
  2947. const char *expected;
  2948. } cases[] = {
  2949. {"/a b?x=1", "/a%20b?x=1"},
  2950. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2951. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2952. };
  2953. for (const auto &c : cases) {
  2954. Client cli(HOST, port);
  2955. target.clear();
  2956. auto res = cli.Get(c.path);
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2959. auto buffered_target = target;
  2960. target.clear();
  2961. auto handle = cli.open_stream("GET", c.path);
  2962. EXPECT_TRUE(handle.is_valid())
  2963. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2964. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2965. }
  2966. }
  2967. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2968. // The `set_path_encode(false)` contract — transmit the supplied target
  2969. // verbatim — must hold for the streaming API too.
  2970. Server svr;
  2971. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2972. std::string target;
  2973. svr.Get("/foo", [&](const Request &req, Response &res) {
  2974. target = req.target;
  2975. res.status = StatusCode::OK_200;
  2976. });
  2977. auto port = svr.bind_to_any_port(HOST);
  2978. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2979. auto se = detail::scope_exit([&] {
  2980. svr.stop();
  2981. thread.join();
  2982. ASSERT_FALSE(svr.is_running());
  2983. });
  2984. svr.wait_until_ready();
  2985. {
  2986. Client cli(HOST, port);
  2987. cli.set_path_encode(false);
  2988. auto handle = cli.open_stream("GET", expected_target);
  2989. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2990. EXPECT_EQ(expected_target, target);
  2991. }
  2992. }
  2993. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2994. // With path encoding enabled a CR/LF in the target is percent-encoded
  2995. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2996. // write_request_line still backstops `set_path_encode(false)`, which is
  2997. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2998. Server svr;
  2999. // Captured before routing: the decoded path contains a newline, which a
  3000. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3001. std::string target;
  3002. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3003. target = req.target;
  3004. res.status = StatusCode::OK_200;
  3005. return Server::HandlerResponse::Handled;
  3006. });
  3007. auto port = svr.bind_to_any_port(HOST);
  3008. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. thread.join();
  3012. ASSERT_FALSE(svr.is_running());
  3013. });
  3014. svr.wait_until_ready();
  3015. {
  3016. Client cli(HOST, port);
  3017. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3018. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3019. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3020. }
  3021. }
  3022. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3023. // Nothing may reach the wire: a raw CR/LF target would split the request
  3024. // line and inject headers.
  3025. Server svr;
  3026. // Pre-routing so that "not called" means nothing reached the server at all,
  3027. // rather than merely failing to match a handler pattern.
  3028. auto handler_called = false;
  3029. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3030. handler_called = true;
  3031. res.status = StatusCode::OK_200;
  3032. return Server::HandlerResponse::Handled;
  3033. });
  3034. auto port = svr.bind_to_any_port(HOST);
  3035. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3036. auto se = detail::scope_exit([&] {
  3037. svr.stop();
  3038. thread.join();
  3039. ASSERT_FALSE(svr.is_running());
  3040. });
  3041. svr.wait_until_ready();
  3042. {
  3043. Client cli(HOST, port);
  3044. cli.set_path_encode(false);
  3045. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3046. EXPECT_FALSE(handle.is_valid());
  3047. EXPECT_EQ(Error::Write, handle.error);
  3048. EXPECT_FALSE(handler_called);
  3049. }
  3050. }
  3051. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3052. // Which of the two branches runs is decided by whether the query component
  3053. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3054. // an empty query and must still fall back to building one from
  3055. // `req.params`, while a non-empty query must win over `req.params`.
  3056. Server svr;
  3057. std::string target;
  3058. svr.Get("/foo", [&](const Request &req, Response &res) {
  3059. target = req.target;
  3060. res.status = StatusCode::OK_200;
  3061. });
  3062. auto port = svr.bind_to_any_port(HOST);
  3063. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3064. auto se = detail::scope_exit([&] {
  3065. svr.stop();
  3066. thread.join();
  3067. ASSERT_FALSE(svr.is_running());
  3068. });
  3069. svr.wait_until_ready();
  3070. {
  3071. // Trailing `?` -> empty query component -> `req.params` is used.
  3072. Client cli(HOST, port);
  3073. Request req;
  3074. req.method = "GET";
  3075. req.path = "/foo?";
  3076. req.params.emplace("a", "1");
  3077. target.clear();
  3078. auto res = cli.send(req);
  3079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3080. EXPECT_EQ("/foo?a=1", target);
  3081. }
  3082. {
  3083. // Non-empty query in `req.path` -> `req.params` is not appended.
  3084. Client cli(HOST, port);
  3085. Request req;
  3086. req.method = "GET";
  3087. req.path = "/foo?b=2";
  3088. req.params.emplace("a", "1");
  3089. target.clear();
  3090. auto res = cli.send(req);
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. EXPECT_EQ("/foo?b=2", target);
  3093. }
  3094. }
  3095. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3096. Server svr;
  3097. svr.Get("/", [](const Request &req, Response &) {
  3098. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3099. });
  3100. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3101. auto se = detail::scope_exit([&] {
  3102. svr.stop();
  3103. thread.join();
  3104. ASSERT_FALSE(svr.is_running());
  3105. });
  3106. svr.wait_until_ready();
  3107. {
  3108. Client cli(HOST, PORT);
  3109. cli.set_path_encode(false);
  3110. auto res = cli.Get("/?something=%0A");
  3111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. }
  3114. }
  3115. TEST(BindServerTest, BindDualStack) {
  3116. Server svr;
  3117. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3118. res.set_content("Hello World!", "text/plain");
  3119. });
  3120. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3121. auto se = detail::scope_exit([&] {
  3122. svr.stop();
  3123. thread.join();
  3124. ASSERT_FALSE(svr.is_running());
  3125. });
  3126. svr.wait_until_ready();
  3127. {
  3128. Client cli("127.0.0.1", PORT);
  3129. auto res = cli.Get("/1");
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. EXPECT_EQ("Hello World!", res->body);
  3133. }
  3134. {
  3135. Client cli("::1", PORT);
  3136. auto res = cli.Get("/1");
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. EXPECT_EQ("Hello World!", res->body);
  3140. }
  3141. }
  3142. TEST(BindServerTest, BindAndListenSeparately) {
  3143. Server svr;
  3144. int port = svr.bind_to_any_port("0.0.0.0");
  3145. ASSERT_TRUE(svr.is_valid());
  3146. ASSERT_TRUE(port > 0);
  3147. svr.stop();
  3148. }
  3149. // Reports whether anything is still listening on a loopback port. A plain
  3150. // connect() is used instead of a Client request because a socket left bound by
  3151. // mistake accepts the connection into its backlog and never answers, which
  3152. // would hang the test instead of failing it.
  3153. static bool is_loopback_port_accepting(int port) {
  3154. sockaddr_in addr{};
  3155. addr.sin_family = AF_INET;
  3156. addr.sin_port = htons(static_cast<uint16_t>(port));
  3157. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3158. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3159. EXPECT_NE(sock, INVALID_SOCKET);
  3160. if (sock == INVALID_SOCKET) { return false; }
  3161. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3162. static_cast<socklen_t>(sizeof(addr)));
  3163. detail::close_socket(sock);
  3164. return ret == 0;
  3165. }
  3166. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3167. Server svr;
  3168. auto port = svr.bind_to_any_port("127.0.0.1");
  3169. ASSERT_TRUE(port > 0);
  3170. svr.stop();
  3171. // bind_to_any_port() already called listen(2), so until stop() closed the
  3172. // descriptor the port kept accepting connections into the backlog. ASSERT
  3173. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3174. // below blocks forever in the accept loop.
  3175. ASSERT_FALSE(is_loopback_port_accepting(port));
  3176. // Nothing is left to accept on, so listen_after_bind() must report failure
  3177. // instead of returning success without ever serving.
  3178. EXPECT_FALSE(svr.listen_after_bind());
  3179. // The failed listen marks the server decommissioned, so a waiter returns
  3180. // instead of spinning forever.
  3181. svr.wait_until_ready();
  3182. }
  3183. #ifdef CPPHTTPLIB_SSL_ENABLED
  3184. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3186. CLIENT_CA_CERT_DIR);
  3187. int port = svr.bind_to_any_port("0.0.0.0");
  3188. ASSERT_TRUE(svr.is_valid());
  3189. ASSERT_TRUE(port > 0);
  3190. svr.stop();
  3191. }
  3192. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3193. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3194. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3195. int port = svr.bind_to_any_port("0.0.0.0");
  3196. ASSERT_TRUE(svr.is_valid());
  3197. ASSERT_TRUE(port > 0);
  3198. svr.stop();
  3199. }
  3200. TEST(BindServerTest, UpdateCertsPem) {
  3201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3202. int port = svr.bind_to_any_port("0.0.0.0");
  3203. ASSERT_TRUE(svr.is_valid());
  3204. ASSERT_TRUE(port > 0);
  3205. // Read PEM files
  3206. std::string cert_pem, key_pem, ca_pem;
  3207. read_file(SERVER_CERT_FILE, cert_pem);
  3208. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3209. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3210. // Update server certificates using PEM API
  3211. ASSERT_TRUE(
  3212. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3213. ASSERT_TRUE(svr.is_valid());
  3214. svr.stop();
  3215. }
  3216. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3217. // Start server with client CA (enables client auth)
  3218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3219. ASSERT_TRUE(svr.is_valid());
  3220. bool handler_called = false;
  3221. svr.Get("/test", [&](const Request &req, Response &res) {
  3222. handler_called = true;
  3223. // Verify client certificate is present
  3224. auto cert = req.peer_cert();
  3225. EXPECT_TRUE(static_cast<bool>(cert));
  3226. res.set_content("ok", "text/plain");
  3227. });
  3228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3229. auto se = detail::scope_exit([&] {
  3230. svr.stop();
  3231. t.join();
  3232. ASSERT_FALSE(svr.is_running());
  3233. });
  3234. svr.wait_until_ready();
  3235. // Read PEM files
  3236. std::string cert_pem, key_pem, ca_pem;
  3237. read_file(SERVER_CERT_FILE, cert_pem);
  3238. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3239. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3240. // Update server certificates and client CA using PEM API while server running
  3241. ASSERT_TRUE(
  3242. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3243. // Connect with client certificate
  3244. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3245. cli.enable_server_certificate_verification(false);
  3246. cli.set_connection_timeout(30);
  3247. auto res = cli.Get("/test");
  3248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3249. ASSERT_EQ(StatusCode::OK_200, res->status);
  3250. ASSERT_TRUE(handler_called);
  3251. EXPECT_EQ("ok", res->body);
  3252. }
  3253. #endif
  3254. TEST(ErrorHandlerTest, ContentLength) {
  3255. Server svr;
  3256. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3257. res.status = StatusCode::OK_200;
  3258. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3259. "text/html"); // <= Content-Length still 13
  3260. });
  3261. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3262. res.set_content("Hello World!\n", "text/plain");
  3263. res.status = 524;
  3264. });
  3265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3266. auto se = detail::scope_exit([&] {
  3267. svr.stop();
  3268. thread.join();
  3269. ASSERT_FALSE(svr.is_running());
  3270. });
  3271. svr.wait_until_ready();
  3272. {
  3273. Client cli(HOST, PORT);
  3274. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3278. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3280. }
  3281. }
  3282. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3283. TEST(ExceptionTest, WithoutExceptionHandler) {
  3284. Server svr;
  3285. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3286. throw std::runtime_error("exception...");
  3287. });
  3288. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3289. throw std::runtime_error("exception\r\n...");
  3290. });
  3291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3292. auto se = detail::scope_exit([&] {
  3293. svr.stop();
  3294. listen_thread.join();
  3295. ASSERT_FALSE(svr.is_running());
  3296. });
  3297. svr.wait_until_ready();
  3298. Client cli("localhost", PORT);
  3299. {
  3300. auto res = cli.Get("/exception");
  3301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3303. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3304. }
  3305. {
  3306. auto res = cli.Get("/unknown");
  3307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3308. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3309. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3310. }
  3311. }
  3312. TEST(ExceptionTest, WithExceptionHandler) {
  3313. Server svr;
  3314. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3315. std::exception_ptr ep) {
  3316. EXPECT_FALSE(ep == nullptr);
  3317. try {
  3318. std::rethrow_exception(ep);
  3319. } catch (std::exception &e) {
  3320. EXPECT_EQ("abc", std::string(e.what()));
  3321. } catch (...) {}
  3322. res.status = StatusCode::InternalServerError_500;
  3323. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3324. "text/html"); // <= Content-Length still 13 at this point
  3325. });
  3326. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3327. res.set_content("Hello World!\n", "text/plain");
  3328. throw std::runtime_error("abc");
  3329. });
  3330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3331. auto se = detail::scope_exit([&] {
  3332. svr.stop();
  3333. thread.join();
  3334. ASSERT_FALSE(svr.is_running());
  3335. });
  3336. svr.wait_until_ready();
  3337. for (size_t i = 0; i < 10; i++) {
  3338. Client cli(HOST, PORT);
  3339. for (size_t j = 0; j < 100; j++) {
  3340. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3342. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3344. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3345. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3346. }
  3347. cli.set_keep_alive(true);
  3348. for (size_t j = 0; j < 100; j++) {
  3349. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3351. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3353. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3354. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3355. }
  3356. }
  3357. }
  3358. TEST(ExceptionTest, AndErrorHandler) {
  3359. Server svr;
  3360. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3361. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3362. });
  3363. svr.set_exception_handler(
  3364. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3365. EXPECT_FALSE(ep == nullptr);
  3366. try {
  3367. std::rethrow_exception(ep);
  3368. } catch (std::exception &e) {
  3369. res.set_content(e.what(), "text/html");
  3370. } catch (...) {}
  3371. res.status = StatusCode::InternalServerError_500;
  3372. });
  3373. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3374. throw std::runtime_error("EXCEPTION");
  3375. });
  3376. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3377. res.set_content("ERROR", "text/html");
  3378. res.status = StatusCode::InternalServerError_500;
  3379. });
  3380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3381. auto se = detail::scope_exit([&] {
  3382. svr.stop();
  3383. thread.join();
  3384. ASSERT_FALSE(svr.is_running());
  3385. });
  3386. svr.wait_until_ready();
  3387. Client cli(HOST, PORT);
  3388. {
  3389. auto res = cli.Get("/exception");
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3392. EXPECT_EQ("EXCEPTION", res->body);
  3393. }
  3394. {
  3395. auto res = cli.Get("/error");
  3396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3397. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3398. EXPECT_EQ("ERROR", res->body);
  3399. }
  3400. {
  3401. auto res = cli.Get("/invalid");
  3402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3404. EXPECT_EQ("NOT_FOUND", res->body);
  3405. }
  3406. }
  3407. #endif
  3408. TEST(NoContentTest, ContentLength) {
  3409. Server svr;
  3410. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3411. res.status = StatusCode::NoContent_204;
  3412. });
  3413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3414. auto se = detail::scope_exit([&] {
  3415. svr.stop();
  3416. thread.join();
  3417. ASSERT_FALSE(svr.is_running());
  3418. });
  3419. svr.wait_until_ready();
  3420. {
  3421. Client cli(HOST, PORT);
  3422. auto res = cli.Get("/hi");
  3423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3424. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3425. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3426. }
  3427. }
  3428. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3429. #ifdef CPPHTTPLIB_SSL_ENABLED
  3430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3431. ASSERT_TRUE(svr.is_valid());
  3432. #else
  3433. Server svr;
  3434. #endif
  3435. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3436. if (req.path == "/routing_handler") {
  3437. res.set_header("PRE_ROUTING", "on");
  3438. res.set_content("Routing Handler", "text/plain");
  3439. return httplib::Server::HandlerResponse::Handled;
  3440. }
  3441. return httplib::Server::HandlerResponse::Unhandled;
  3442. });
  3443. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3444. res.set_content("Error", "text/html");
  3445. });
  3446. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3447. if (req.path == "/routing_handler") {
  3448. res.set_header("POST_ROUTING", "on");
  3449. }
  3450. });
  3451. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3452. res.set_content("Hello World!\n", "text/plain");
  3453. });
  3454. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3455. auto se = detail::scope_exit([&] {
  3456. svr.stop();
  3457. thread.join();
  3458. ASSERT_FALSE(svr.is_running());
  3459. });
  3460. svr.wait_until_ready();
  3461. {
  3462. #ifdef CPPHTTPLIB_SSL_ENABLED
  3463. SSLClient cli(HOST, PORT);
  3464. cli.enable_server_certificate_verification(false);
  3465. #else
  3466. Client cli(HOST, PORT);
  3467. #endif
  3468. auto res = cli.Get("/routing_handler");
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("Routing Handler", res->body);
  3472. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3473. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3474. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3475. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3476. }
  3477. {
  3478. #ifdef CPPHTTPLIB_SSL_ENABLED
  3479. SSLClient cli(HOST, PORT);
  3480. cli.enable_server_certificate_verification(false);
  3481. #else
  3482. Client cli(HOST, PORT);
  3483. #endif
  3484. auto res = cli.Get("/hi");
  3485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3486. EXPECT_EQ(StatusCode::OK_200, res->status);
  3487. EXPECT_EQ("Hello World!\n", res->body);
  3488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3490. }
  3491. {
  3492. #ifdef CPPHTTPLIB_SSL_ENABLED
  3493. SSLClient cli(HOST, PORT);
  3494. cli.enable_server_certificate_verification(false);
  3495. #else
  3496. Client cli(HOST, PORT);
  3497. #endif
  3498. auto res = cli.Get("/aaa");
  3499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3501. EXPECT_EQ("Error", res->body);
  3502. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3503. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3504. }
  3505. }
  3506. TEST(RequestHandlerTest, PreRequestHandler) {
  3507. auto route_path = "/user/:user";
  3508. Server svr;
  3509. svr.Get("/hi", [](const Request &, Response &res) {
  3510. res.set_content("hi", "text/plain");
  3511. });
  3512. svr.Get(route_path, [](const Request &req, Response &res) {
  3513. res.set_content(req.path_params.at("user"), "text/plain");
  3514. });
  3515. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3516. if (req.matched_route == route_path) {
  3517. auto user = req.path_params.at("user");
  3518. if (user != "john") {
  3519. res.status = StatusCode::Forbidden_403;
  3520. res.set_content("error", "text/html");
  3521. return Server::HandlerResponse::Handled;
  3522. }
  3523. }
  3524. return Server::HandlerResponse::Unhandled;
  3525. });
  3526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3527. auto se = detail::scope_exit([&] {
  3528. svr.stop();
  3529. thread.join();
  3530. ASSERT_FALSE(svr.is_running());
  3531. });
  3532. svr.wait_until_ready();
  3533. Client cli(HOST, PORT);
  3534. {
  3535. auto res = cli.Get("/hi");
  3536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3537. EXPECT_EQ(StatusCode::OK_200, res->status);
  3538. EXPECT_EQ("hi", res->body);
  3539. }
  3540. {
  3541. auto res = cli.Get("/user/john");
  3542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3543. EXPECT_EQ(StatusCode::OK_200, res->status);
  3544. EXPECT_EQ("john", res->body);
  3545. }
  3546. {
  3547. auto res = cli.Get("/user/invalid-user");
  3548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3549. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3550. EXPECT_EQ("error", res->body);
  3551. }
  3552. }
  3553. // The pre-request handler must run before the request body is read, so a
  3554. // rejected request never forces the server to buffer a (potentially large)
  3555. // body. Here the posted body is larger than the payload limit: if the body
  3556. // were read first the server would answer 413, but because the pre-request
  3557. // handler runs first it answers 403 and the body is never read.
  3558. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3559. Server svr;
  3560. svr.set_payload_max_length(8);
  3561. auto handler_ran = false;
  3562. svr.Post("/reject", [&](const Request &req, Response &res) {
  3563. handler_ran = true;
  3564. res.set_content(req.body, "text/plain");
  3565. });
  3566. svr.Post("/accept", [](const Request &req, Response &res) {
  3567. res.set_content(req.body, "text/plain");
  3568. });
  3569. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3570. if (req.matched_route == "/reject") {
  3571. res.status = StatusCode::Forbidden_403;
  3572. res.set_content("denied", "text/plain");
  3573. return Server::HandlerResponse::Handled;
  3574. }
  3575. return Server::HandlerResponse::Unhandled;
  3576. });
  3577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3578. auto se = detail::scope_exit([&] {
  3579. svr.stop();
  3580. thread.join();
  3581. ASSERT_FALSE(svr.is_running());
  3582. });
  3583. svr.wait_until_ready();
  3584. Client cli(HOST, PORT);
  3585. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3586. // rejects with 403 before the body is read, so 413 is never reached.
  3587. {
  3588. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3591. EXPECT_EQ("denied", res->body);
  3592. EXPECT_FALSE(handler_ran);
  3593. }
  3594. // An approved route still reads the body and enforces the payload limit.
  3595. {
  3596. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3599. }
  3600. }
  3601. TEST(UserDataTest, BasicOperations) {
  3602. httplib::UserData ud;
  3603. // Initially empty
  3604. EXPECT_FALSE(ud.has("key"));
  3605. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3606. // set and get
  3607. ud.set("key", 42);
  3608. EXPECT_TRUE(ud.has("key"));
  3609. auto *p = ud.get<int>("key");
  3610. ASSERT_NE(nullptr, p);
  3611. EXPECT_EQ(42, *p);
  3612. // Type mismatch → nullptr
  3613. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3614. // Overwrite with different type
  3615. ud.set("key", std::string("hello"));
  3616. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3617. auto *s = ud.get<std::string>("key");
  3618. ASSERT_NE(nullptr, s);
  3619. EXPECT_EQ("hello", *s);
  3620. // erase
  3621. ud.erase("key");
  3622. EXPECT_FALSE(ud.has("key"));
  3623. // clear
  3624. ud.set("a", 1);
  3625. ud.set("b", 2);
  3626. ud.clear();
  3627. EXPECT_FALSE(ud.has("a"));
  3628. EXPECT_FALSE(ud.has("b"));
  3629. }
  3630. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3631. struct AuthCtx {
  3632. std::string user_id;
  3633. };
  3634. Server svr;
  3635. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3636. res.user_data.set("auth", AuthCtx{"alice"});
  3637. return Server::HandlerResponse::Unhandled;
  3638. });
  3639. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3640. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3641. ASSERT_NE(nullptr, ctx);
  3642. res.set_content("Hello " + ctx->user_id, "text/plain");
  3643. });
  3644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3645. auto se = detail::scope_exit([&] {
  3646. svr.stop();
  3647. thread.join();
  3648. ASSERT_FALSE(svr.is_running());
  3649. });
  3650. svr.wait_until_ready();
  3651. Client cli(HOST, PORT);
  3652. auto res = cli.Get("/me");
  3653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3654. EXPECT_EQ(StatusCode::OK_200, res->status);
  3655. EXPECT_EQ("Hello alice", res->body);
  3656. }
  3657. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3658. struct RoleCtx {
  3659. std::string role;
  3660. };
  3661. Server svr;
  3662. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3663. res.user_data.set("role", RoleCtx{"admin"});
  3664. return Server::HandlerResponse::Unhandled;
  3665. });
  3666. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3667. auto *ctx = res.user_data.get<RoleCtx>("role");
  3668. ASSERT_NE(nullptr, ctx);
  3669. res.set_content(ctx->role, "text/plain");
  3670. });
  3671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3672. auto se = detail::scope_exit([&] {
  3673. svr.stop();
  3674. thread.join();
  3675. ASSERT_FALSE(svr.is_running());
  3676. });
  3677. svr.wait_until_ready();
  3678. Client cli(HOST, PORT);
  3679. auto res = cli.Get("/role");
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. EXPECT_EQ("admin", res->body);
  3683. }
  3684. TEST(InvalidFormatTest, StatusCode) {
  3685. Server svr;
  3686. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3687. res.set_content("Hello World!\n", "text/plain");
  3688. res.status = 9999; // Status should be a three-digit code...
  3689. });
  3690. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3691. auto se = detail::scope_exit([&] {
  3692. svr.stop();
  3693. thread.join();
  3694. ASSERT_FALSE(svr.is_running());
  3695. });
  3696. svr.wait_until_ready();
  3697. {
  3698. Client cli(HOST, PORT);
  3699. auto res = cli.Get("/hi");
  3700. ASSERT_FALSE(res);
  3701. }
  3702. }
  3703. TEST(URLFragmentTest, WithFragment) {
  3704. Server svr;
  3705. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3706. EXPECT_TRUE(req.target == "/hi");
  3707. });
  3708. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3709. auto se = detail::scope_exit([&] {
  3710. svr.stop();
  3711. thread.join();
  3712. ASSERT_FALSE(svr.is_running());
  3713. });
  3714. svr.wait_until_ready();
  3715. {
  3716. Client cli(HOST, PORT);
  3717. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3718. EXPECT_TRUE(res);
  3719. EXPECT_EQ(StatusCode::OK_200, res->status);
  3720. res = cli.Get("/hi%23key1=val1=key2=val2");
  3721. EXPECT_TRUE(res);
  3722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3723. }
  3724. }
  3725. TEST(HeaderWriter, SetHeaderWriter) {
  3726. Server svr;
  3727. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3728. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3729. return detail::write_headers(strm, hdrs);
  3730. });
  3731. svr.Get("/hi", [](const Request &req, Response &res) {
  3732. auto it = req.headers.find("CustomClientHeader");
  3733. EXPECT_TRUE(it != req.headers.end());
  3734. EXPECT_EQ(it->second, "CustomClientValue");
  3735. res.set_content("Hello World!\n", "text/plain");
  3736. });
  3737. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3738. auto se = detail::scope_exit([&] {
  3739. svr.stop();
  3740. thread.join();
  3741. ASSERT_FALSE(svr.is_running());
  3742. });
  3743. svr.wait_until_ready();
  3744. {
  3745. Client cli(HOST, PORT);
  3746. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3747. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3748. return detail::write_headers(strm, hdrs);
  3749. });
  3750. auto res = cli.Get("/hi");
  3751. EXPECT_TRUE(res);
  3752. EXPECT_EQ(StatusCode::OK_200, res->status);
  3753. auto it = res->headers.find("CustomServerHeader");
  3754. EXPECT_TRUE(it != res->headers.end());
  3755. EXPECT_EQ(it->second, "CustomServerValue");
  3756. }
  3757. }
  3758. class ServerTest : public ::testing::Test {
  3759. protected:
  3760. ServerTest()
  3761. : cli_(HOST, PORT)
  3762. #ifdef CPPHTTPLIB_SSL_ENABLED
  3763. ,
  3764. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3765. #endif
  3766. {
  3767. #ifdef CPPHTTPLIB_SSL_ENABLED
  3768. cli_.enable_server_certificate_verification(false);
  3769. #endif
  3770. // Allow LARGE_DATA (100MB) responses
  3771. cli_.set_payload_max_length(200 * 1024 * 1024);
  3772. }
  3773. virtual void SetUp() {
  3774. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3775. svr_.set_payload_max_length(200 * 1024 * 1024);
  3776. svr_.set_mount_point("/", "./www");
  3777. svr_.set_mount_point("/mount", "./www2");
  3778. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3779. svr_.Get("/hi",
  3780. [&](const Request & /*req*/, Response &res) {
  3781. res.set_content("Hello World!", "text/plain");
  3782. })
  3783. .Get("/file_content",
  3784. [&](const Request & /*req*/, Response &res) {
  3785. res.set_file_content("./www/dir/test.html");
  3786. })
  3787. .Get("/file_content_with_content_type",
  3788. [&](const Request & /*req*/, Response &res) {
  3789. res.set_file_content("./www/file", "text/plain");
  3790. })
  3791. .Get("/invalid_file_content",
  3792. [&](const Request & /*req*/, Response &res) {
  3793. res.set_file_content("./www/dir/invalid_file_path");
  3794. })
  3795. .Get("/http_response_splitting",
  3796. [&](const Request & /*req*/, Response &res) {
  3797. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3798. EXPECT_EQ(0U, res.headers.size());
  3799. EXPECT_FALSE(res.has_header("a"));
  3800. res.set_header("a", "1\nSet-Cookie: a=1");
  3801. EXPECT_EQ(0U, res.headers.size());
  3802. EXPECT_FALSE(res.has_header("a"));
  3803. res.set_header("a", "1\rSet-Cookie: a=1");
  3804. EXPECT_EQ(0U, res.headers.size());
  3805. EXPECT_FALSE(res.has_header("a"));
  3806. res.set_header("a\r\nb", "0");
  3807. EXPECT_EQ(0U, res.headers.size());
  3808. EXPECT_FALSE(res.has_header("a"));
  3809. res.set_header("a\rb", "0");
  3810. EXPECT_EQ(0U, res.headers.size());
  3811. EXPECT_FALSE(res.has_header("a"));
  3812. res.set_header("a\nb", "0");
  3813. EXPECT_EQ(0U, res.headers.size());
  3814. EXPECT_FALSE(res.has_header("a"));
  3815. res.set_redirect("1\r\nSet-Cookie: a=1");
  3816. EXPECT_EQ(0U, res.headers.size());
  3817. EXPECT_FALSE(res.has_header("Location"));
  3818. })
  3819. .Get("/slow",
  3820. [&](const Request & /*req*/, Response &res) {
  3821. std::this_thread::sleep_for(std::chrono::seconds(4));
  3822. res.set_content("slow", "text/plain");
  3823. })
  3824. #if 0
  3825. .Post("/slowpost",
  3826. [&](const Request & /*req*/, Response &res) {
  3827. std::this_thread::sleep_for(std::chrono::seconds(2));
  3828. res.set_content("slow", "text/plain");
  3829. })
  3830. #endif
  3831. .Get("/remote_addr",
  3832. [&](const Request &req, Response &res) {
  3833. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3834. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3835. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3836. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3837. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3838. #endif
  3839. res.set_content(req.remote_addr, "text/plain");
  3840. })
  3841. .Get("/local_addr",
  3842. [&](const Request &req, Response &res) {
  3843. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3844. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3845. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3846. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3847. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3848. #endif
  3849. auto local_addr = req.local_addr;
  3850. auto local_port = std::to_string(req.local_port);
  3851. res.set_content(local_addr.append(":").append(local_port),
  3852. "text/plain");
  3853. })
  3854. .Get("/endwith%",
  3855. [&](const Request & /*req*/, Response &res) {
  3856. res.set_content("Hello World!", "text/plain");
  3857. })
  3858. .Get("/a\\+\\+b",
  3859. [&](const Request &req, Response &res) {
  3860. ASSERT_TRUE(req.has_param("a +b"));
  3861. auto val = req.get_param_value("a +b");
  3862. res.set_content(val, "text/plain");
  3863. })
  3864. .Get("/", [&](const Request & /*req*/,
  3865. Response &res) { res.set_redirect("/hi"); })
  3866. .Post("/1",
  3867. [](const Request & /*req*/, Response &res) {
  3868. res.set_redirect("/2", StatusCode::SeeOther_303);
  3869. })
  3870. .Get("/2",
  3871. [](const Request & /*req*/, Response &res) {
  3872. res.set_content("redirected.", "text/plain");
  3873. res.status = StatusCode::OK_200;
  3874. })
  3875. .Post("/person",
  3876. [&](const Request &req, Response &res) {
  3877. if (req.has_param("name") && req.has_param("note")) {
  3878. persons_[req.get_param_value("name")] =
  3879. req.get_param_value("note");
  3880. } else {
  3881. res.status = StatusCode::BadRequest_400;
  3882. }
  3883. })
  3884. .Put("/person",
  3885. [&](const Request &req, Response &res) {
  3886. if (req.has_param("name") && req.has_param("note")) {
  3887. persons_[req.get_param_value("name")] =
  3888. req.get_param_value("note");
  3889. } else {
  3890. res.status = StatusCode::BadRequest_400;
  3891. }
  3892. })
  3893. .Get("/person/(.*)",
  3894. [&](const Request &req, Response &res) {
  3895. string name = req.matches[1];
  3896. if (persons_.find(name) != persons_.end()) {
  3897. auto note = persons_[name];
  3898. res.set_content(note, "text/plain");
  3899. } else {
  3900. res.status = StatusCode::NotFound_404;
  3901. }
  3902. })
  3903. .Delete("/person",
  3904. [&](const Request &req, Response &res) {
  3905. if (req.has_param("name")) {
  3906. string name = req.get_param_value("name");
  3907. if (persons_.find(name) != persons_.end()) {
  3908. persons_.erase(name);
  3909. res.set_content("DELETED", "text/plain");
  3910. } else {
  3911. res.status = StatusCode::NotFound_404;
  3912. }
  3913. } else {
  3914. res.status = StatusCode::BadRequest_400;
  3915. }
  3916. })
  3917. .Post("/x-www-form-urlencoded-json",
  3918. [&](const Request &req, Response &res) {
  3919. auto json = req.get_param_value("json");
  3920. ASSERT_EQ(JSON_DATA, json);
  3921. res.set_content(json, "appliation/json");
  3922. res.status = StatusCode::OK_200;
  3923. })
  3924. .Get("/streamed-chunked",
  3925. [&](const Request & /*req*/, Response &res) {
  3926. res.set_chunked_content_provider(
  3927. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3928. sink.os << "123";
  3929. sink.os << "456";
  3930. sink.os << "789";
  3931. sink.done();
  3932. return true;
  3933. });
  3934. })
  3935. .Get("/streamed-chunked-with-prohibited-trailer",
  3936. [&](const Request & /*req*/, Response &res) {
  3937. auto i = new int(0);
  3938. // Declare both a prohibited trailer (Content-Length) and an
  3939. // allowed one
  3940. res.set_header("Trailer", "Content-Length, X-Allowed");
  3941. res.set_chunked_content_provider(
  3942. "text/plain",
  3943. [i](size_t /*offset*/, DataSink &sink) {
  3944. switch (*i) {
  3945. case 0: sink.os << "123"; break;
  3946. case 1: sink.os << "456"; break;
  3947. case 2: sink.os << "789"; break;
  3948. case 3: {
  3949. sink.done_with_trailer(
  3950. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3951. } break;
  3952. }
  3953. (*i)++;
  3954. return true;
  3955. },
  3956. [i](bool success) {
  3957. EXPECT_TRUE(success);
  3958. delete i;
  3959. });
  3960. })
  3961. .Get("/streamed-chunked2",
  3962. [&](const Request & /*req*/, Response &res) {
  3963. auto i = new int(0);
  3964. res.set_chunked_content_provider(
  3965. "text/plain",
  3966. [i](size_t /*offset*/, DataSink &sink) {
  3967. switch (*i) {
  3968. case 0: sink.os << "123"; break;
  3969. case 1: sink.os << "456"; break;
  3970. case 2: sink.os << "789"; break;
  3971. case 3: sink.done(); break;
  3972. }
  3973. (*i)++;
  3974. return true;
  3975. },
  3976. [i](bool success) {
  3977. EXPECT_TRUE(success);
  3978. delete i;
  3979. });
  3980. })
  3981. .Get("/streamed-chunked-with-trailer",
  3982. [&](const Request & /*req*/, Response &res) {
  3983. auto i = new int(0);
  3984. res.set_header("Trailer", "Dummy1, Dummy2");
  3985. res.set_chunked_content_provider(
  3986. "text/plain",
  3987. [i](size_t /*offset*/, DataSink &sink) {
  3988. switch (*i) {
  3989. case 0: sink.os << "123"; break;
  3990. case 1: sink.os << "456"; break;
  3991. case 2: sink.os << "789"; break;
  3992. case 3: {
  3993. sink.done_with_trailer(
  3994. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3995. } break;
  3996. }
  3997. (*i)++;
  3998. return true;
  3999. },
  4000. [i](bool success) {
  4001. EXPECT_TRUE(success);
  4002. delete i;
  4003. });
  4004. })
  4005. .Get("/streamed",
  4006. [&](const Request & /*req*/, Response &res) {
  4007. res.set_content_provider(
  4008. 6, "text/plain",
  4009. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4010. sink.os << (offset < 3 ? "a" : "b");
  4011. return true;
  4012. });
  4013. })
  4014. .Get("/streamed-without-length",
  4015. [&](const Request & /*req*/, Response &res) {
  4016. auto data = new std::string("abcdefg");
  4017. res.set_content_provider(
  4018. "text/plain",
  4019. [data](size_t offset, DataSink &sink) {
  4020. if (offset < data->size()) {
  4021. sink.os << data->substr(offset);
  4022. }
  4023. sink.done();
  4024. return true;
  4025. },
  4026. [data](bool success) {
  4027. EXPECT_TRUE(success);
  4028. delete data;
  4029. });
  4030. })
  4031. .Get("/streamed-with-range",
  4032. [&](const Request &req, Response &res) {
  4033. auto data = new std::string("abcdefg");
  4034. // An explicit status keeps the server from picking the 206 it
  4035. // would otherwise choose for a ranged request, so the response
  4036. // is not a partial representation.
  4037. auto status = req.get_param_value("status");
  4038. if (status == "200") {
  4039. res.status = StatusCode::OK_200;
  4040. } else if (status == "403") {
  4041. res.status = StatusCode::Forbidden_403;
  4042. }
  4043. res.set_content_provider(
  4044. data->size(), "text/plain",
  4045. [data](size_t offset, size_t length, DataSink &sink) {
  4046. size_t DATA_CHUNK_SIZE = 4;
  4047. const auto &d = *data;
  4048. auto out_len =
  4049. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4050. auto ret =
  4051. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4052. EXPECT_TRUE(ret);
  4053. return true;
  4054. },
  4055. [data, &req](bool success) {
  4056. EXPECT_EQ(success, !req.has_param("error"));
  4057. delete data;
  4058. });
  4059. })
  4060. .Get("/streamed-cancel",
  4061. [&](const Request & /*req*/, Response &res) {
  4062. res.set_content_provider(
  4063. size_t(-1), "text/plain",
  4064. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4065. sink.os << "data_chunk";
  4066. return true;
  4067. });
  4068. })
  4069. .Get("/regex-with-delimiter",
  4070. [&](const Request &req, Response & /*res*/) {
  4071. ASSERT_TRUE(req.has_param("key"));
  4072. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4073. })
  4074. .Get("/with-range",
  4075. [&](const Request & /*req*/, Response &res) {
  4076. res.set_content("abcdefg", "text/plain");
  4077. })
  4078. .Get("/test-start-time",
  4079. [&](const Request &req, Response & /*res*/) {
  4080. EXPECT_NE(req.start_time_,
  4081. std::chrono::steady_clock::time_point::min());
  4082. })
  4083. .Get("/with-range-customized-response",
  4084. [&](const Request & /*req*/, Response &res) {
  4085. res.status = StatusCode::BadRequest_400;
  4086. res.set_content(JSON_DATA, "application/json");
  4087. })
  4088. .Post("/chunked",
  4089. [&](const Request &req, Response & /*res*/) {
  4090. EXPECT_EQ(req.body, "dechunked post body");
  4091. })
  4092. .Post("/large-chunked",
  4093. [&](const Request &req, Response & /*res*/) {
  4094. std::string expected(6 * 30 * 1024u, 'a');
  4095. EXPECT_EQ(req.body, expected);
  4096. })
  4097. .Post("/multipart",
  4098. [&](const Request &req, Response & /*res*/) {
  4099. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4100. req.form.get_field_count("text2") +
  4101. req.form.get_field_count("file3") +
  4102. req.form.get_field_count("file4"));
  4103. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4104. req.form.get_file_count("file2"));
  4105. ASSERT_TRUE(!req.form.has_file("???"));
  4106. ASSERT_TRUE(!req.form.has_field("???"));
  4107. ASSERT_TRUE(req.body.empty());
  4108. {
  4109. const auto &text = req.form.get_field("text1");
  4110. EXPECT_EQ("text default", text);
  4111. }
  4112. {
  4113. const auto &text = req.form.get_field("text2");
  4114. EXPECT_EQ("aωb", text);
  4115. }
  4116. {
  4117. const auto &file = req.form.get_file("file1");
  4118. EXPECT_EQ("hello.txt", file.filename);
  4119. EXPECT_EQ("text/plain", file.content_type);
  4120. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4121. }
  4122. {
  4123. const auto &file = req.form.get_file("file2");
  4124. EXPECT_EQ("world.json", file.filename);
  4125. EXPECT_EQ("application/json", file.content_type);
  4126. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4127. }
  4128. {
  4129. const auto &text = req.form.get_field("file3");
  4130. EXPECT_EQ(0u, text.size());
  4131. }
  4132. {
  4133. const auto &text = req.form.get_field("file4");
  4134. EXPECT_EQ(0u, text.size());
  4135. }
  4136. })
  4137. .Post("/multipart/multi_file_values",
  4138. [&](const Request &req, Response & /*res*/) {
  4139. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4140. req.form.get_field_count("multi_text1"));
  4141. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4142. ASSERT_TRUE(!req.form.has_file("???"));
  4143. ASSERT_TRUE(!req.form.has_field("???"));
  4144. ASSERT_TRUE(req.body.empty());
  4145. {
  4146. const auto &text = req.form.get_field("text");
  4147. EXPECT_EQ("default text", text);
  4148. }
  4149. {
  4150. const auto &text1_values = req.form.get_fields("multi_text1");
  4151. EXPECT_EQ(2u, text1_values.size());
  4152. EXPECT_EQ("aaaaa", text1_values[0]);
  4153. EXPECT_EQ("bbbbb", text1_values[1]);
  4154. }
  4155. {
  4156. const auto &file1_values = req.form.get_files("multi_file1");
  4157. EXPECT_EQ(2u, file1_values.size());
  4158. auto file1 = file1_values[0];
  4159. EXPECT_EQ(file1.filename, "hello.txt");
  4160. EXPECT_EQ(file1.content_type, "text/plain");
  4161. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4162. auto file2 = file1_values[1];
  4163. EXPECT_EQ(file2.filename, "world.json");
  4164. EXPECT_EQ(file2.content_type, "application/json");
  4165. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4166. }
  4167. })
  4168. .Post("/empty",
  4169. [&](const Request &req, Response &res) {
  4170. EXPECT_EQ(req.body, "");
  4171. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4172. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4173. res.set_content("empty", "text/plain");
  4174. })
  4175. .Post("/empty-no-content-type",
  4176. [&](const Request &req, Response &res) {
  4177. EXPECT_EQ(req.body, "");
  4178. EXPECT_FALSE(req.has_header("Content-Type"));
  4179. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4180. res.set_content("empty-no-content-type", "text/plain");
  4181. })
  4182. .Post("/path-only",
  4183. [&](const Request &req, Response &res) {
  4184. EXPECT_EQ(req.body, "");
  4185. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4186. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4187. res.set_content("path-only", "text/plain");
  4188. })
  4189. .Post("/path-headers-only",
  4190. [&](const Request &req, Response &res) {
  4191. EXPECT_EQ(req.body, "");
  4192. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4193. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4194. EXPECT_EQ("world", req.get_header_value("hello"));
  4195. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4196. res.set_content("path-headers-only", "text/plain");
  4197. })
  4198. .Post("/post-large",
  4199. [&](const Request &req, Response &res) {
  4200. EXPECT_EQ(req.body, LARGE_DATA);
  4201. res.set_content(req.body, "text/plain");
  4202. })
  4203. .Post("/post-loopback",
  4204. [&](const Request &, Response &res,
  4205. ContentReader const &content_reader) {
  4206. std::string body;
  4207. content_reader([&](const char *data, size_t data_length) {
  4208. body.append(data, data_length);
  4209. return true;
  4210. });
  4211. res.set_content(body, "text/plain");
  4212. })
  4213. .Put("/put-loopback",
  4214. [&](const Request &, Response &res,
  4215. ContentReader const &content_reader) {
  4216. std::string body;
  4217. content_reader([&](const char *data, size_t data_length) {
  4218. body.append(data, data_length);
  4219. return true;
  4220. });
  4221. res.set_content(body, "text/plain");
  4222. })
  4223. .Patch("/patch-loopback",
  4224. [&](const Request &, Response &res,
  4225. ContentReader const &content_reader) {
  4226. std::string body;
  4227. content_reader([&](const char *data, size_t data_length) {
  4228. body.append(data, data_length);
  4229. return true;
  4230. });
  4231. res.set_content(body, "text/plain");
  4232. })
  4233. .Put("/empty-no-content-type",
  4234. [&](const Request &req, Response &res) {
  4235. EXPECT_EQ(req.body, "");
  4236. EXPECT_FALSE(req.has_header("Content-Type"));
  4237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4238. res.set_content("empty-no-content-type", "text/plain");
  4239. })
  4240. .Put("/put",
  4241. [&](const Request &req, Response &res) {
  4242. EXPECT_EQ(req.body, "PUT");
  4243. res.set_content(req.body, "text/plain");
  4244. })
  4245. .Put("/put-large",
  4246. [&](const Request &req, Response &res) {
  4247. EXPECT_EQ(req.body, LARGE_DATA);
  4248. res.set_content(req.body, "text/plain");
  4249. })
  4250. .Patch("/patch",
  4251. [&](const Request &req, Response &res) {
  4252. EXPECT_EQ(req.body, "PATCH");
  4253. res.set_content(req.body, "text/plain");
  4254. })
  4255. .Delete("/delete",
  4256. [&](const Request & /*req*/, Response &res) {
  4257. res.set_content("DELETE", "text/plain");
  4258. })
  4259. .Delete("/delete-body",
  4260. [&](const Request &req, Response &res) {
  4261. EXPECT_EQ(req.body, "content");
  4262. res.set_content(req.body, "text/plain");
  4263. })
  4264. .Options(R"(\*)",
  4265. [&](const Request & /*req*/, Response &res) {
  4266. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4267. })
  4268. .Get("/request-target",
  4269. [&](const Request &req, Response & /*res*/) {
  4270. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4271. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4272. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4273. })
  4274. .Get("/long-query-value",
  4275. [&](const Request &req, Response & /*res*/) {
  4276. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4277. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4278. })
  4279. .Get("/too-long-query-value",
  4280. [&](const Request &req, Response & /*res*/) {
  4281. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4282. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4283. })
  4284. .Get("/array-param",
  4285. [&](const Request &req, Response & /*res*/) {
  4286. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4287. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4288. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4289. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4290. })
  4291. .Get("/array-param-values",
  4292. [&](const Request &req, Response & /*res*/) {
  4293. auto values = req.get_param_values("array");
  4294. EXPECT_EQ(3u, values.size());
  4295. EXPECT_EQ("value1", values[0]);
  4296. EXPECT_EQ("value2", values[1]);
  4297. EXPECT_EQ("value3", values[2]);
  4298. auto empty = req.get_param_values("nonexistent");
  4299. EXPECT_TRUE(empty.empty());
  4300. })
  4301. .Post("/validate-no-multiple-headers",
  4302. [&](const Request &req, Response & /*res*/) {
  4303. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4304. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4305. })
  4306. .Post("/content_receiver",
  4307. [&](const Request &req, Response &res,
  4308. const ContentReader &content_reader) {
  4309. if (req.is_multipart_form_data()) {
  4310. std::vector<FormData> items;
  4311. content_reader(
  4312. [&](const FormData &file) {
  4313. items.push_back(file);
  4314. return true;
  4315. },
  4316. [&](const char *data, size_t data_length) {
  4317. items.back().content.append(data, data_length);
  4318. return true;
  4319. });
  4320. EXPECT_EQ(5u, items.size());
  4321. {
  4322. const auto &file = get_file_value(items, "text1");
  4323. EXPECT_TRUE(file.filename.empty());
  4324. EXPECT_EQ("text default", file.content);
  4325. }
  4326. {
  4327. const auto &file = get_file_value(items, "text2");
  4328. EXPECT_TRUE(file.filename.empty());
  4329. EXPECT_EQ("aωb", file.content);
  4330. }
  4331. {
  4332. const auto &file = get_file_value(items, "file1");
  4333. EXPECT_EQ("hello.txt", file.filename);
  4334. EXPECT_EQ("text/plain", file.content_type);
  4335. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4336. }
  4337. {
  4338. const auto &file = get_file_value(items, "file2");
  4339. EXPECT_EQ("world.json", file.filename);
  4340. EXPECT_EQ("application/json", file.content_type);
  4341. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4342. }
  4343. {
  4344. const auto &file = get_file_value(items, "file3");
  4345. EXPECT_TRUE(file.filename.empty());
  4346. EXPECT_EQ("application/octet-stream", file.content_type);
  4347. EXPECT_EQ(0u, file.content.size());
  4348. }
  4349. } else {
  4350. std::string body;
  4351. content_reader([&](const char *data, size_t data_length) {
  4352. EXPECT_EQ(7U, data_length);
  4353. body.append(data, data_length);
  4354. return true;
  4355. });
  4356. EXPECT_EQ(body, "content");
  4357. res.set_content(body, "text/plain");
  4358. }
  4359. })
  4360. .Put("/content_receiver",
  4361. [&](const Request & /*req*/, Response &res,
  4362. const ContentReader &content_reader) {
  4363. std::string body;
  4364. content_reader([&](const char *data, size_t data_length) {
  4365. body.append(data, data_length);
  4366. return true;
  4367. });
  4368. EXPECT_EQ(body, "content");
  4369. res.set_content(body, "text/plain");
  4370. })
  4371. .Patch("/content_receiver",
  4372. [&](const Request & /*req*/, Response &res,
  4373. const ContentReader &content_reader) {
  4374. std::string body;
  4375. content_reader([&](const char *data, size_t data_length) {
  4376. body.append(data, data_length);
  4377. return true;
  4378. });
  4379. EXPECT_EQ(body, "content");
  4380. res.set_content(body, "text/plain");
  4381. })
  4382. .Post("/query-string-and-body",
  4383. [&](const Request &req, Response & /*res*/) {
  4384. ASSERT_TRUE(req.has_param("key"));
  4385. EXPECT_EQ(req.get_param_value("key"), "value");
  4386. EXPECT_EQ(req.body, "content");
  4387. })
  4388. .Get("/last-request",
  4389. [&](const Request &req, Response & /*res*/) {
  4390. EXPECT_EQ("close", req.get_header_value("Connection"));
  4391. })
  4392. .Get(R"(/redirect/(\d+))",
  4393. [&](const Request &req, Response &res) {
  4394. auto num = std::stoi(req.matches[1]) + 1;
  4395. std::string url = "/redirect/" + std::to_string(num);
  4396. res.set_redirect(url);
  4397. })
  4398. .Post("/binary",
  4399. [&](const Request &req, Response &res) {
  4400. EXPECT_EQ(4U, req.body.size());
  4401. EXPECT_EQ("application/octet-stream",
  4402. req.get_header_value("Content-Type"));
  4403. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4404. res.set_content(req.body, "application/octet-stream");
  4405. })
  4406. .Put("/binary",
  4407. [&](const Request &req, Response &res) {
  4408. EXPECT_EQ(4U, req.body.size());
  4409. EXPECT_EQ("application/octet-stream",
  4410. req.get_header_value("Content-Type"));
  4411. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4412. res.set_content(req.body, "application/octet-stream");
  4413. })
  4414. .Patch("/binary",
  4415. [&](const Request &req, Response &res) {
  4416. EXPECT_EQ(4U, req.body.size());
  4417. EXPECT_EQ("application/octet-stream",
  4418. req.get_header_value("Content-Type"));
  4419. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4420. res.set_content(req.body, "application/octet-stream");
  4421. })
  4422. .Delete("/binary",
  4423. [&](const Request &req, Response &res) {
  4424. EXPECT_EQ(4U, req.body.size());
  4425. EXPECT_EQ("application/octet-stream",
  4426. req.get_header_value("Content-Type"));
  4427. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4428. res.set_content(req.body, "application/octet-stream");
  4429. })
  4430. .Get("/issue1772",
  4431. [&](const Request & /*req*/, Response &res) {
  4432. res.status = 401;
  4433. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4434. })
  4435. .Delete("/issue609",
  4436. [](const httplib::Request &, httplib::Response &res,
  4437. const httplib::ContentReader &) {
  4438. res.set_content("ok", "text/plain");
  4439. })
  4440. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4441. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4442. .Get("/compress",
  4443. [&](const Request & /*req*/, Response &res) {
  4444. res.set_content(
  4445. "12345678901234567890123456789012345678901234567890123456789"
  4446. "01234567890123456789012345678901234567890",
  4447. "text/plain");
  4448. })
  4449. .Get("/compress-with-charset",
  4450. [&](const Request & /*req*/, Response &res) {
  4451. res.set_content(
  4452. "12345678901234567890123456789012345678901234567890123456789"
  4453. "01234567890123456789012345678901234567890",
  4454. "application/json; charset=utf-8");
  4455. })
  4456. .Get("/nocompress",
  4457. [&](const Request & /*req*/, Response &res) {
  4458. res.set_content(
  4459. "12345678901234567890123456789012345678901234567890123456789"
  4460. "01234567890123456789012345678901234567890",
  4461. "application/octet-stream");
  4462. })
  4463. .Post("/compress-multipart",
  4464. [&](const Request &req, Response & /*res*/) {
  4465. EXPECT_EQ(2u, req.form.fields.size());
  4466. ASSERT_TRUE(!req.form.has_field("???"));
  4467. {
  4468. const auto &text = req.form.get_field("key1");
  4469. EXPECT_EQ("test", text);
  4470. }
  4471. {
  4472. const auto &text = req.form.get_field("key2");
  4473. EXPECT_EQ("--abcdefg123", text);
  4474. }
  4475. })
  4476. #endif
  4477. ;
  4478. persons_["john"] = "programmer";
  4479. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4480. svr_.wait_until_ready();
  4481. }
  4482. virtual void TearDown() {
  4483. svr_.stop();
  4484. if (!request_threads_.empty()) {
  4485. std::this_thread::sleep_for(std::chrono::seconds(1));
  4486. for (auto &t : request_threads_) {
  4487. t.join();
  4488. }
  4489. }
  4490. t_.join();
  4491. }
  4492. map<string, string> persons_;
  4493. #ifdef CPPHTTPLIB_SSL_ENABLED
  4494. SSLClient cli_;
  4495. SSLServer svr_;
  4496. #else
  4497. Client cli_;
  4498. Server svr_;
  4499. #endif
  4500. thread t_;
  4501. std::vector<thread> request_threads_;
  4502. };
  4503. TEST_F(ServerTest, GetMethod200) {
  4504. auto res = cli_.Get("/hi");
  4505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4506. EXPECT_EQ("HTTP/1.1", res->version);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("OK", res->reason);
  4509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4510. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4511. EXPECT_EQ("Hello World!", res->body);
  4512. }
  4513. TEST_F(ServerTest, GetEmptyFile) {
  4514. auto res = cli_.Get("/empty_file");
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. EXPECT_EQ(StatusCode::OK_200, res->status);
  4517. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4518. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4519. EXPECT_EQ("", res->body);
  4520. }
  4521. TEST_F(ServerTest, GetFileContent) {
  4522. auto res = cli_.Get("/file_content");
  4523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4524. EXPECT_EQ(StatusCode::OK_200, res->status);
  4525. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4526. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4527. EXPECT_EQ("test.html", res->body);
  4528. }
  4529. TEST_F(ServerTest, GetFileContentWithRange) {
  4530. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4533. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4534. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4535. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4536. EXPECT_EQ("est", res->body);
  4537. }
  4538. TEST_F(ServerTest, GetFileContentWithContentType) {
  4539. auto res = cli_.Get("/file_content_with_content_type");
  4540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4543. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4544. EXPECT_EQ("file\n", res->body);
  4545. }
  4546. TEST_F(ServerTest, GetInvalidFileContent) {
  4547. auto res = cli_.Get("/invalid_file_content");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4550. }
  4551. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4552. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. EXPECT_EQ("HTTP/1.1", res->version);
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4557. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4558. EXPECT_EQ("Hello World!", res->body);
  4559. }
  4560. TEST_F(ServerTest, GetMethod302) {
  4561. auto res = cli_.Get("/");
  4562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4563. EXPECT_EQ(StatusCode::Found_302, res->status);
  4564. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4565. }
  4566. TEST_F(ServerTest, GetMethod302Redirect) {
  4567. cli_.set_follow_location(true);
  4568. auto res = cli_.Get("/");
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::OK_200, res->status);
  4571. EXPECT_EQ("Hello World!", res->body);
  4572. EXPECT_EQ("/hi", res->location);
  4573. }
  4574. TEST_F(ServerTest, GetMethod404) {
  4575. auto res = cli_.Get("/invalid");
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4578. }
  4579. TEST_F(ServerTest, HeadMethod200) {
  4580. auto res = cli_.Head("/hi");
  4581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4584. EXPECT_TRUE(res->body.empty());
  4585. }
  4586. TEST_F(ServerTest, HeadMethod200Static) {
  4587. auto res = cli_.Head("/mount/dir/index.html");
  4588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4589. EXPECT_EQ(StatusCode::OK_200, res->status);
  4590. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4591. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4592. EXPECT_TRUE(res->body.empty());
  4593. }
  4594. TEST_F(ServerTest, HeadMethod404) {
  4595. auto res = cli_.Head("/invalid");
  4596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4598. EXPECT_TRUE(res->body.empty());
  4599. }
  4600. TEST_F(ServerTest, GetMethodPersonJohn) {
  4601. auto res = cli_.Get("/person/john");
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4605. EXPECT_EQ("programmer", res->body);
  4606. }
  4607. TEST_F(ServerTest, PostMethod1) {
  4608. auto res = cli_.Get("/person/john1");
  4609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4610. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4611. res = cli_.Post("/person", "name=john1&note=coder",
  4612. "application/x-www-form-urlencoded");
  4613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4614. ASSERT_EQ(StatusCode::OK_200, res->status);
  4615. res = cli_.Get("/person/john1");
  4616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4617. ASSERT_EQ(StatusCode::OK_200, res->status);
  4618. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4619. ASSERT_EQ("coder", res->body);
  4620. }
  4621. TEST_F(ServerTest, PostMethod2) {
  4622. auto res = cli_.Get("/person/john2");
  4623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4624. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4625. Params params;
  4626. params.emplace("name", "john2");
  4627. params.emplace("note", "coder");
  4628. res = cli_.Post("/person", params);
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. ASSERT_EQ(StatusCode::OK_200, res->status);
  4631. res = cli_.Get("/person/john2");
  4632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4633. ASSERT_EQ(StatusCode::OK_200, res->status);
  4634. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4635. ASSERT_EQ("coder", res->body);
  4636. }
  4637. TEST_F(ServerTest, PutMethod3) {
  4638. auto res = cli_.Get("/person/john3");
  4639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4640. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4641. Params params;
  4642. params.emplace("name", "john3");
  4643. params.emplace("note", "coder");
  4644. res = cli_.Put("/person", params);
  4645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4646. ASSERT_EQ(StatusCode::OK_200, res->status);
  4647. res = cli_.Get("/person/john3");
  4648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4649. ASSERT_EQ(StatusCode::OK_200, res->status);
  4650. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4651. ASSERT_EQ("coder", res->body);
  4652. }
  4653. TEST_F(ServerTest, DeleteMethod1) {
  4654. auto res = cli_.Get("/person/john4");
  4655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4656. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4657. Params params;
  4658. params.emplace("name", "john4");
  4659. params.emplace("note", "coder");
  4660. res = cli_.Post("/person", params);
  4661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4662. ASSERT_EQ(StatusCode::OK_200, res->status);
  4663. res = cli_.Get("/person/john4");
  4664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4665. ASSERT_EQ(StatusCode::OK_200, res->status);
  4666. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4667. ASSERT_EQ("coder", res->body);
  4668. Params delete_params;
  4669. delete_params.emplace("name", "john4");
  4670. res = cli_.Delete("/person", delete_params);
  4671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4672. ASSERT_EQ(StatusCode::OK_200, res->status);
  4673. ASSERT_EQ("DELETED", res->body);
  4674. res = cli_.Get("/person/john4");
  4675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4676. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4677. }
  4678. TEST_F(ServerTest, DeleteMethod2) {
  4679. auto res = cli_.Get("/person/john5");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4682. Params params;
  4683. params.emplace("name", "john5");
  4684. params.emplace("note", "developer");
  4685. res = cli_.Post("/person", params);
  4686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4687. ASSERT_EQ(StatusCode::OK_200, res->status);
  4688. res = cli_.Get("/person/john5");
  4689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4690. ASSERT_EQ(StatusCode::OK_200, res->status);
  4691. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4692. ASSERT_EQ("developer", res->body);
  4693. Params delete_params;
  4694. delete_params.emplace("name", "john5");
  4695. Headers headers;
  4696. headers.emplace("Custom-Header", "test-value");
  4697. res = cli_.Delete("/person", headers, delete_params);
  4698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4699. ASSERT_EQ(StatusCode::OK_200, res->status);
  4700. ASSERT_EQ("DELETED", res->body);
  4701. res = cli_.Get("/person/john5");
  4702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4703. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4704. }
  4705. TEST_F(ServerTest, DeleteMethod3) {
  4706. auto res = cli_.Get("/person/john6");
  4707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4708. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4709. Params params;
  4710. params.emplace("name", "john6");
  4711. params.emplace("note", "tester");
  4712. res = cli_.Post("/person", params);
  4713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4714. ASSERT_EQ(StatusCode::OK_200, res->status);
  4715. res = cli_.Get("/person/john6");
  4716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4717. ASSERT_EQ(StatusCode::OK_200, res->status);
  4718. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4719. ASSERT_EQ("tester", res->body);
  4720. Params delete_params;
  4721. delete_params.emplace("name", "john6");
  4722. Headers headers;
  4723. headers.emplace("Custom-Header", "test-value");
  4724. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. ASSERT_EQ(StatusCode::OK_200, res->status);
  4727. ASSERT_EQ("DELETED", res->body);
  4728. res = cli_.Get("/person/john6");
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4731. }
  4732. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4733. Params params;
  4734. params.emplace("json", JSON_DATA);
  4735. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4737. ASSERT_EQ(StatusCode::OK_200, res->status);
  4738. ASSERT_EQ(JSON_DATA, res->body);
  4739. }
  4740. TEST_F(ServerTest, PostEmptyContent) {
  4741. auto res = cli_.Post("/empty", "", "text/plain");
  4742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4743. ASSERT_EQ(StatusCode::OK_200, res->status);
  4744. ASSERT_EQ("empty", res->body);
  4745. }
  4746. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4747. auto res = cli_.Post("/empty-no-content-type");
  4748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4749. ASSERT_EQ(StatusCode::OK_200, res->status);
  4750. ASSERT_EQ("empty-no-content-type", res->body);
  4751. }
  4752. TEST_F(ServerTest, PostPathOnly) {
  4753. auto res = cli_.Post("/path-only");
  4754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4755. ASSERT_EQ(StatusCode::OK_200, res->status);
  4756. ASSERT_EQ("path-only", res->body);
  4757. }
  4758. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4759. auto res = cli_.Post("/path-headers-only",
  4760. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4762. ASSERT_EQ(StatusCode::OK_200, res->status);
  4763. ASSERT_EQ("path-headers-only", res->body);
  4764. }
  4765. TEST_F(ServerTest, PostLarge) {
  4766. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. ASSERT_EQ(StatusCode::OK_200, res->status);
  4769. EXPECT_EQ(LARGE_DATA, res->body);
  4770. }
  4771. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4772. auto res = cli_.Put("/empty-no-content-type");
  4773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4774. ASSERT_EQ(StatusCode::OK_200, res->status);
  4775. ASSERT_EQ("empty-no-content-type", res->body);
  4776. }
  4777. TEST_F(ServerTest, GetMethodDir) {
  4778. auto res = cli_.Get("/dir/");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. EXPECT_EQ(StatusCode::OK_200, res->status);
  4781. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4782. auto body = R"(<html>
  4783. <head>
  4784. </head>
  4785. <body>
  4786. <a href="/dir/test.html">Test</a>
  4787. <a href="/hi">hi</a>
  4788. </body>
  4789. </html>
  4790. )";
  4791. EXPECT_EQ(body, res->body);
  4792. }
  4793. TEST_F(ServerTest, GetMethodDirTest) {
  4794. auto res = cli_.Get("/dir/test.html");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4798. EXPECT_EQ("test.html", res->body);
  4799. }
  4800. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4801. auto res = cli_.Get("/dir/../dir/test.html");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ(StatusCode::OK_200, res->status);
  4804. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4805. EXPECT_EQ("test.html", res->body);
  4806. }
  4807. TEST_F(ServerTest, GetMethodInvalidPath) {
  4808. auto res = cli_.Get("/dir/../test.html");
  4809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4810. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4811. }
  4812. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4813. auto res = cli_.Get("/../www/dir/test.html");
  4814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4815. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4816. }
  4817. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4818. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4821. }
  4822. TEST_F(ServerTest, GetMethodDirMountTest) {
  4823. auto res = cli_.Get("/mount/dir/test.html");
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ(StatusCode::OK_200, res->status);
  4826. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4827. EXPECT_EQ("test.html", res->body);
  4828. }
  4829. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4830. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4832. EXPECT_EQ(StatusCode::OK_200, res->status);
  4833. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4834. EXPECT_EQ("test.html", res->body);
  4835. }
  4836. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4837. auto res = cli_.Get("/mount/dir/../test.html");
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4840. }
  4841. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4842. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4845. }
  4846. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4847. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4850. }
  4851. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4852. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4855. }
  4856. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4857. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4860. }
  4861. TEST_F(ServerTest, PostMethod303) {
  4862. auto res = cli_.Post("/1", "body", "text/plain");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4865. EXPECT_EQ("/2", res->get_header_value("Location"));
  4866. }
  4867. TEST_F(ServerTest, PostMethod303Redirect) {
  4868. cli_.set_follow_location(true);
  4869. auto res = cli_.Post("/1", "body", "text/plain");
  4870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4871. EXPECT_EQ(StatusCode::OK_200, res->status);
  4872. EXPECT_EQ("redirected.", res->body);
  4873. EXPECT_EQ("/2", res->location);
  4874. }
  4875. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4876. auto res = cli_.Get("/dir/test.abcde");
  4877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4878. EXPECT_EQ(StatusCode::OK_200, res->status);
  4879. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4880. EXPECT_EQ("abcde", res->body);
  4881. }
  4882. TEST_F(ServerTest, StaticFileRange) {
  4883. auto res =
  4884. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4886. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4887. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4888. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4889. EXPECT_EQ(true, res->has_header("Content-Range"));
  4890. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4891. EXPECT_EQ(std::string("cd"), res->body);
  4892. }
  4893. TEST_F(ServerTest, StaticFileRanges) {
  4894. auto res = cli_.Get("/dir/test.abcde",
  4895. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4898. EXPECT_TRUE(
  4899. res->get_header_value("Content-Type")
  4900. .find(
  4901. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4902. 0);
  4903. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4904. }
  4905. TEST_F(ServerTest, StaticFileRangeHead) {
  4906. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4909. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4910. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4911. EXPECT_EQ(true, res->has_header("Content-Range"));
  4912. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4913. }
  4914. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4915. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4919. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4920. EXPECT_EQ(true, res->has_header("Content-Range"));
  4921. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4922. res->get_header_value("Content-Range"));
  4923. EXPECT_EQ("LAST\n", res->body);
  4924. }
  4925. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4926. auto res =
  4927. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4931. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4932. EXPECT_EQ(true, res->has_header("Content-Range"));
  4933. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4934. }
  4935. TEST_F(ServerTest, StaticFileBigFile) {
  4936. auto res = cli_.Get("/dir/1MB.txt");
  4937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4938. EXPECT_EQ(StatusCode::OK_200, res->status);
  4939. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4940. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4941. }
  4942. TEST_F(ServerTest, InvalidBaseDirMount) {
  4943. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4944. }
  4945. TEST_F(ServerTest, Binary) {
  4946. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4947. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4948. "application/octet-stream");
  4949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4950. ASSERT_EQ(StatusCode::OK_200, res->status);
  4951. ASSERT_EQ(4U, res->body.size());
  4952. res = cli_.Put("/binary", binary.data(), binary.size(),
  4953. "application/octet-stream");
  4954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4955. ASSERT_EQ(StatusCode::OK_200, res->status);
  4956. ASSERT_EQ(4U, res->body.size());
  4957. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4958. "application/octet-stream");
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. ASSERT_EQ(StatusCode::OK_200, res->status);
  4961. ASSERT_EQ(4U, res->body.size());
  4962. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4963. "application/octet-stream");
  4964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4965. ASSERT_EQ(StatusCode::OK_200, res->status);
  4966. ASSERT_EQ(4U, res->body.size());
  4967. }
  4968. TEST_F(ServerTest, BinaryString) {
  4969. auto binary = std::string("\x00\x01\x02\x03", 4);
  4970. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4972. ASSERT_EQ(StatusCode::OK_200, res->status);
  4973. ASSERT_EQ(4U, res->body.size());
  4974. res = cli_.Put("/binary", binary, "application/octet-stream");
  4975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4976. ASSERT_EQ(StatusCode::OK_200, res->status);
  4977. ASSERT_EQ(4U, res->body.size());
  4978. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. ASSERT_EQ(StatusCode::OK_200, res->status);
  4981. ASSERT_EQ(4U, res->body.size());
  4982. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. ASSERT_EQ(StatusCode::OK_200, res->status);
  4985. ASSERT_EQ(4U, res->body.size());
  4986. }
  4987. TEST_F(ServerTest, EmptyRequest) {
  4988. auto res = cli_.Get("");
  4989. ASSERT_TRUE(!res);
  4990. EXPECT_EQ(Error::Connection, res.error());
  4991. }
  4992. TEST_F(ServerTest, LongRequest) {
  4993. std::string request;
  4994. for (size_t i = 0; i < 545; i++) {
  4995. request += "/TooLongRequest";
  4996. }
  4997. request += "OK";
  4998. auto res = cli_.Get(request.c_str());
  4999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5000. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5001. }
  5002. TEST_F(ServerTest, TooLongRequest) {
  5003. std::string request;
  5004. for (size_t i = 0; i < 546; i++) {
  5005. request += "/TooLongRequest";
  5006. }
  5007. request += "_NG";
  5008. auto start = std::chrono::high_resolution_clock::now();
  5009. cli_.set_keep_alive(true);
  5010. auto res = cli_.Get(request.c_str());
  5011. auto end = std::chrono::high_resolution_clock::now();
  5012. auto elapsed =
  5013. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5014. .count();
  5015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5016. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5017. EXPECT_LE(elapsed, 1000);
  5018. EXPECT_EQ("close", res->get_header_value("Connection"));
  5019. EXPECT_FALSE(cli_.is_socket_open());
  5020. }
  5021. TEST_F(ServerTest, AlmostTooLongRequest) {
  5022. // test for #2046 - URI length check shouldn't include other content on req
  5023. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5024. // leading /, space, HTTP/1.1)
  5025. std::string request =
  5026. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5027. auto res = cli_.Get(request.c_str());
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5030. }
  5031. TEST_F(ServerTest, LongHeader) {
  5032. Request req;
  5033. req.method = "GET";
  5034. req.path = "/hi";
  5035. std::string host_and_port;
  5036. host_and_port += HOST;
  5037. host_and_port += ":";
  5038. host_and_port += std::to_string(PORT);
  5039. req.headers.emplace("Host", host_and_port.c_str());
  5040. req.headers.emplace("Accept", "*/*");
  5041. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5042. req.headers.emplace(
  5043. "Header-Name",
  5044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@");
  5073. auto res = std::make_shared<Response>();
  5074. auto error = Error::Success;
  5075. auto ret = cli_.send(req, *res, error);
  5076. ASSERT_TRUE(ret);
  5077. EXPECT_EQ(StatusCode::OK_200, res->status);
  5078. }
  5079. TEST_F(ServerTest, LongQueryValue) {
  5080. auto start = std::chrono::high_resolution_clock::now();
  5081. cli_.set_keep_alive(true);
  5082. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5083. auto end = std::chrono::high_resolution_clock::now();
  5084. auto elapsed =
  5085. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5086. .count();
  5087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5088. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5089. EXPECT_LE(elapsed, 1000);
  5090. EXPECT_EQ("close", res->get_header_value("Connection"));
  5091. EXPECT_FALSE(cli_.is_socket_open());
  5092. }
  5093. TEST_F(ServerTest, TooLongQueryValue) {
  5094. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5095. ASSERT_FALSE(res);
  5096. EXPECT_EQ(Error::Read, res.error());
  5097. }
  5098. TEST_F(ServerTest, TooLongHeader) {
  5099. Request req;
  5100. req.method = "GET";
  5101. req.path = "/hi";
  5102. std::string host_and_port;
  5103. host_and_port += HOST;
  5104. host_and_port += ":";
  5105. host_and_port += std::to_string(PORT);
  5106. req.headers.emplace("Host", host_and_port.c_str());
  5107. req.headers.emplace("Accept", "*/*");
  5108. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5109. req.headers.emplace(
  5110. "Header-Name",
  5111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@");
  5140. auto res = std::make_shared<Response>();
  5141. auto error = Error::Success;
  5142. auto ret = cli_.send(req, *res, error);
  5143. ASSERT_TRUE(ret);
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. }
  5146. TEST_F(ServerTest, HeaderCountAtLimit) {
  5147. // Test with headers just under the 100 limit
  5148. httplib::Headers headers;
  5149. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5150. // This should keep us just under the 100 header limit
  5151. for (int i = 0; i < 95; i++) {
  5152. std::string name = "X-Test-Header-" + std::to_string(i);
  5153. std::string value = "value" + std::to_string(i);
  5154. headers.emplace(name, value);
  5155. }
  5156. // This should work fine as we're under the limit
  5157. auto res = cli_.Get("/hi", headers);
  5158. EXPECT_TRUE(res);
  5159. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5160. }
  5161. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5162. // Test with many headers to exceed the 100 limit
  5163. httplib::Headers headers;
  5164. // Add 150 headers to definitely exceed the 100 limit
  5165. for (int i = 0; i < 150; i++) {
  5166. std::string name = "X-Test-Header-" + std::to_string(i);
  5167. std::string value = "value" + std::to_string(i);
  5168. headers.emplace(name, value);
  5169. }
  5170. // This should fail due to exceeding header count limit
  5171. cli_.set_keep_alive(true);
  5172. auto res = cli_.Get("/hi", headers);
  5173. // The server should respond with 400 Bad Request
  5174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5175. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5176. EXPECT_EQ("close", res->get_header_value("Connection"));
  5177. EXPECT_FALSE(cli_.is_socket_open());
  5178. }
  5179. TEST_F(ServerTest, PercentEncoding) {
  5180. auto res = cli_.Get("/e%6edwith%");
  5181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5182. EXPECT_EQ(StatusCode::OK_200, res->status);
  5183. }
  5184. TEST_F(ServerTest, PercentEncodingUnicode) {
  5185. auto res = cli_.Get("/e%u006edwith%");
  5186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5187. EXPECT_EQ(StatusCode::OK_200, res->status);
  5188. }
  5189. TEST_F(ServerTest, InvalidPercentEncoding) {
  5190. auto res = cli_.Get("/%endwith%");
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5193. }
  5194. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5195. auto res = cli_.Get("/%uendwith%");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5198. }
  5199. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5200. auto res = cli_.Get("/hello?aaa=bbb%");
  5201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5203. }
  5204. TEST_F(ServerTest, PlusSignEncoding) {
  5205. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. EXPECT_EQ("a +b", res->body);
  5209. }
  5210. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5211. // This test simulates a potential DoS attack using many headers
  5212. // to verify our security fix prevents memory exhaustion
  5213. httplib::Headers attack_headers;
  5214. // Attempt to add many headers like an attacker would (200 headers to far
  5215. // exceed limit)
  5216. for (int i = 0; i < 200; i++) {
  5217. std::string name = "X-Attack-Header-" + std::to_string(i);
  5218. std::string value = "attack_payload_" + std::to_string(i);
  5219. attack_headers.emplace(name, value);
  5220. }
  5221. // Try to POST with excessive headers
  5222. cli_.set_keep_alive(true);
  5223. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5224. // Should either fail or return 400 Bad Request due to security limit
  5225. if (res) {
  5226. // If we get a response, it should be 400 Bad Request
  5227. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5228. EXPECT_EQ("close", res->get_header_value("Connection"));
  5229. }
  5230. EXPECT_FALSE(cli_.is_socket_open());
  5231. }
  5232. TEST_F(ServerTest, MultipartFormData) {
  5233. UploadFormDataItems items = {
  5234. {"text1", "text default", "", ""},
  5235. {"text2", "aωb", "", ""},
  5236. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5237. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5238. {"file3", "", "", "application/octet-stream"},
  5239. {"file4", "", "", " application/json tmp-string "}};
  5240. auto res = cli_.Post("/multipart", items);
  5241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5242. EXPECT_EQ(StatusCode::OK_200, res->status);
  5243. }
  5244. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5245. UploadFormDataItems items = {
  5246. {"text", "default text", "", ""},
  5247. {"multi_text1", "aaaaa", "", ""},
  5248. {"multi_text1", "bbbbb", "", ""},
  5249. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5250. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5251. "application/json"},
  5252. };
  5253. auto res = cli_.Post("/multipart/multi_file_values", items);
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. }
  5257. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5258. auto res = cli_.Get("/hi");
  5259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5260. EXPECT_EQ(StatusCode::OK_200, res->status);
  5261. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5262. EXPECT_EQ("Hello World!", res->body);
  5263. }
  5264. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5265. Request req;
  5266. req.method = "POST";
  5267. req.path = "/chunked";
  5268. std::string host_and_port;
  5269. host_and_port += HOST;
  5270. host_and_port += ":";
  5271. host_and_port += std::to_string(PORT);
  5272. req.headers.emplace("Host", host_and_port.c_str());
  5273. req.headers.emplace("Accept", "*/*");
  5274. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5275. req.headers.emplace("Content-Type", "text/plain");
  5276. req.headers.emplace("Content-Length", "0");
  5277. req.headers.emplace(
  5278. "Transfer-Encoding",
  5279. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5280. // Client does not chunk, so make a chunked body manually.
  5281. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5282. auto res = std::make_shared<Response>();
  5283. auto error = Error::Success;
  5284. auto ret = cli_.send(req, *res, error);
  5285. ASSERT_TRUE(ret);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. }
  5288. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5289. // rather than treat them as valid lengths.
  5290. template <typename ClientT>
  5291. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5292. Request req;
  5293. req.method = "POST";
  5294. req.path = "/chunked";
  5295. std::string host_and_port;
  5296. host_and_port += HOST;
  5297. host_and_port += ":";
  5298. host_and_port += std::to_string(PORT);
  5299. req.headers.emplace("Host", host_and_port.c_str());
  5300. req.headers.emplace("Content-Length", "0");
  5301. req.headers.emplace("Transfer-Encoding", "chunked");
  5302. req.body = body;
  5303. auto res = std::make_shared<Response>();
  5304. auto error = Error::Success;
  5305. ASSERT_TRUE(cli.send(req, *res, error));
  5306. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5307. }
  5308. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5309. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5310. }
  5311. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5312. expect_chunked_body_rejected(
  5313. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5314. }
  5315. TEST_F(ServerTest, GetStreamed2) {
  5316. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5318. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5319. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5320. EXPECT_EQ(true, res->has_header("Content-Range"));
  5321. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5322. EXPECT_EQ(std::string("ab"), res->body);
  5323. }
  5324. TEST_F(ServerTest, GetStreamed) {
  5325. auto res = cli_.Get("/streamed");
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. EXPECT_EQ(StatusCode::OK_200, res->status);
  5328. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5329. EXPECT_EQ(std::string("aaabbb"), res->body);
  5330. }
  5331. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5332. auto res = cli_.Get("/streamed-without-length",
  5333. Headers{make_range_header({{0, -1}})});
  5334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5335. EXPECT_EQ(StatusCode::OK_200, res->status);
  5336. EXPECT_EQ(false, res->has_header("Content-Length"));
  5337. EXPECT_EQ(false, res->has_header("Content-Range"));
  5338. EXPECT_EQ(std::string("abcdefg"), res->body);
  5339. }
  5340. TEST_F(ServerTest, GetStreamedWithRange1) {
  5341. auto res =
  5342. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5345. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5346. EXPECT_EQ(true, res->has_header("Content-Range"));
  5347. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5348. EXPECT_EQ(std::string("def"), res->body);
  5349. }
  5350. TEST_F(ServerTest, GetStreamedWithRange2) {
  5351. auto res =
  5352. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5355. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5356. EXPECT_EQ(true, res->has_header("Content-Range"));
  5357. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5358. EXPECT_EQ(std::string("bcdefg"), res->body);
  5359. }
  5360. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5361. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5364. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5365. EXPECT_EQ(true, res->has_header("Content-Range"));
  5366. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5367. EXPECT_EQ(std::string("efg"), res->body);
  5368. }
  5369. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5370. auto res =
  5371. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5374. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ(false, res->has_header("Content-Range"));
  5376. EXPECT_EQ(0U, res->body.size());
  5377. }
  5378. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5379. // Only a 206 is served as a partial representation. Under any other status
  5380. // `apply_ranges()` reported the full content length, so the body must match
  5381. // that header, and the content provider must never be asked for an offset
  5382. // outside the representation.
  5383. auto check = [&](int status, const char *range) {
  5384. auto path =
  5385. std::string("/streamed-with-range?status=") + std::to_string(status);
  5386. auto ctx = path + " Range: " + range;
  5387. auto res = cli_.Get(path, Headers{{"Range", range}});
  5388. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5389. EXPECT_EQ(status, res->status) << ctx;
  5390. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5391. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5392. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5393. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5394. };
  5395. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5396. check(403, "bytes=3-5");
  5397. // The offset is far past the representation.
  5398. check(403, "bytes=100000-100200");
  5399. // `first_pos` is still -1 here, and the bounds asserts in
  5400. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5401. check(403, "bytes=-3");
  5402. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5403. // multipart branch would have written one that is empty.
  5404. check(403, "bytes=1-2, 4-5");
  5405. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5406. // covers the whole representation.
  5407. check(200, "bytes=3-5");
  5408. check(200, "bytes=1-2, 4-5");
  5409. }
  5410. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5411. auto res =
  5412. cli_.Get("/streamed-with-range",
  5413. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5414. "92233720368547758079223372036854775807"}});
  5415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5416. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5417. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5418. EXPECT_EQ(false, res->has_header("Content-Range"));
  5419. EXPECT_EQ(0U, res->body.size());
  5420. }
  5421. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5422. auto res = cli_.Get(
  5423. "/with-range",
  5424. Headers{{"Range",
  5425. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5426. {"Accept-Encoding", ""}});
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5429. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5430. EXPECT_EQ(true, res->has_header("Content-Range"));
  5431. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5432. EXPECT_EQ(std::string("abcdefg"), res->body);
  5433. }
  5434. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5435. auto res = cli_.Get("/with-range", Headers{
  5436. {"Range", "bytes=0-"},
  5437. {"Accept-Encoding", ""},
  5438. });
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5441. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5442. EXPECT_EQ(true, res->has_header("Content-Range"));
  5443. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5444. EXPECT_EQ(std::string("abcdefg"), res->body);
  5445. }
  5446. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5447. auto res = cli_.Get("/streamed-with-range",
  5448. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5451. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5452. EXPECT_EQ(false, res->has_header("Content-Range"));
  5453. EXPECT_EQ(267U, res->body.size());
  5454. // Check that both range contents are present
  5455. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5456. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5457. // Check that Content-Range headers are present for both ranges
  5458. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5459. std::string::npos);
  5460. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5461. std::string::npos);
  5462. }
  5463. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5464. Ranges ranges;
  5465. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5466. ranges.emplace_back(0, -1);
  5467. }
  5468. auto res = cli_.Get("/streamed-with-range?error",
  5469. Headers{{make_range_header(ranges)}});
  5470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5471. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5472. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5473. EXPECT_EQ(false, res->has_header("Content-Range"));
  5474. EXPECT_EQ(0U, res->body.size());
  5475. }
  5476. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5477. auto res = cli_.Get("/streamed-with-range",
  5478. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5481. EXPECT_EQ(5U, res->body.size());
  5482. // Check that overlapping ranges are coalesced into a single range
  5483. EXPECT_EQ("bcdef", res->body);
  5484. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5485. // Should be single range, not multipart
  5486. EXPECT_TRUE(res->has_header("Content-Range"));
  5487. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5488. }
  5489. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5490. auto res = cli_.Get("/streamed-with-range",
  5491. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5494. EXPECT_EQ(268U, res->body.size());
  5495. // Check that both range contents are present
  5496. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5497. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5498. // Check that Content-Range headers are present for both ranges
  5499. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5500. std::string::npos);
  5501. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5502. std::string::npos);
  5503. }
  5504. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5505. auto res = cli_.Get("/streamed-with-range",
  5506. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5509. EXPECT_EQ(269U, res->body.size());
  5510. // Check that both duplicate range contents are present
  5511. size_t first_abc = res->body.find("abc\r\n");
  5512. EXPECT_TRUE(first_abc != std::string::npos);
  5513. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5514. EXPECT_TRUE(second_abc != std::string::npos);
  5515. // Check that Content-Range headers are present for both ranges
  5516. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5517. EXPECT_TRUE(first_range != std::string::npos);
  5518. size_t second_range =
  5519. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5520. EXPECT_TRUE(second_range != std::string::npos);
  5521. }
  5522. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5523. auto res =
  5524. cli_.Get("/streamed-with-range?error",
  5525. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5528. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5529. EXPECT_EQ(false, res->has_header("Content-Range"));
  5530. EXPECT_EQ(0U, res->body.size());
  5531. }
  5532. TEST_F(ServerTest, GetStreamedEndless) {
  5533. uint64_t offset = 0;
  5534. auto res = cli_.Get("/streamed-cancel",
  5535. [&](const char * /*data*/, uint64_t data_length) {
  5536. if (offset < 100) {
  5537. offset += data_length;
  5538. return true;
  5539. }
  5540. return false;
  5541. });
  5542. ASSERT_TRUE(!res);
  5543. EXPECT_EQ(Error::Canceled, res.error());
  5544. }
  5545. TEST_F(ServerTest, ClientStop) {
  5546. std::atomic_size_t count{4};
  5547. std::vector<std::thread> threads;
  5548. for (auto i = count.load(); i != 0; --i) {
  5549. threads.emplace_back([&]() {
  5550. auto res = cli_.Get("/streamed-cancel",
  5551. [&](const char *, uint64_t) { return true; });
  5552. --count;
  5553. ASSERT_TRUE(!res);
  5554. EXPECT_TRUE(res.error() == Error::Canceled ||
  5555. res.error() == Error::Read || res.error() == Error::Write);
  5556. });
  5557. }
  5558. std::this_thread::sleep_for(std::chrono::seconds(2));
  5559. while (count != 0) {
  5560. cli_.stop();
  5561. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5562. }
  5563. for (auto &t : threads) {
  5564. t.join();
  5565. }
  5566. }
  5567. TEST_F(ServerTest, GetWithRange1) {
  5568. auto res = cli_.Get("/with-range", Headers{
  5569. make_range_header({{3, 5}}),
  5570. {"Accept-Encoding", ""},
  5571. });
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5574. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5575. EXPECT_EQ(true, res->has_header("Content-Range"));
  5576. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5577. EXPECT_EQ(std::string("def"), res->body);
  5578. }
  5579. TEST_F(ServerTest, GetWithRange2) {
  5580. auto res = cli_.Get("/with-range", Headers{
  5581. make_range_header({{1, -1}}),
  5582. {"Accept-Encoding", ""},
  5583. });
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5586. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5587. EXPECT_EQ(true, res->has_header("Content-Range"));
  5588. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5589. EXPECT_EQ(std::string("bcdefg"), res->body);
  5590. }
  5591. TEST_F(ServerTest, GetWithRange3) {
  5592. auto res = cli_.Get("/with-range", Headers{
  5593. make_range_header({{0, 0}}),
  5594. {"Accept-Encoding", ""},
  5595. });
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5598. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5599. EXPECT_EQ(true, res->has_header("Content-Range"));
  5600. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5601. EXPECT_EQ(std::string("a"), res->body);
  5602. }
  5603. TEST_F(ServerTest, GetWithRange4) {
  5604. auto res = cli_.Get("/with-range", Headers{
  5605. make_range_header({{-1, 2}}),
  5606. {"Accept-Encoding", ""},
  5607. });
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5610. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5611. EXPECT_EQ(true, res->has_header("Content-Range"));
  5612. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5613. EXPECT_EQ(std::string("fg"), res->body);
  5614. }
  5615. TEST_F(ServerTest, GetWithRange5) {
  5616. auto res = cli_.Get("/with-range", Headers{
  5617. make_range_header({{0, 5}}),
  5618. {"Accept-Encoding", ""},
  5619. });
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5622. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5623. EXPECT_EQ(true, res->has_header("Content-Range"));
  5624. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5625. EXPECT_EQ(std::string("abcdef"), res->body);
  5626. }
  5627. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5628. auto res =
  5629. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5632. }
  5633. TEST_F(ServerTest, GetWithRangeMultipart) {
  5634. auto res =
  5635. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5638. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5639. EXPECT_EQ(false, res->has_header("Content-Range"));
  5640. EXPECT_EQ(267U, res->body.size());
  5641. }
  5642. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5643. auto res = cli_.Get("/with-range",
  5644. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5646. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5647. }
  5648. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5649. auto res = cli_.Get("/with-range-customized-response",
  5650. Headers{{make_range_header({{1, 2}})}});
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5653. EXPECT_EQ(true, res->has_header("Content-Length"));
  5654. EXPECT_EQ(false, res->has_header("Content-Range"));
  5655. EXPECT_EQ(JSON_DATA, res->body);
  5656. }
  5657. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5658. auto res = cli_.Get("/with-range-customized-response",
  5659. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5661. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5662. EXPECT_EQ(true, res->has_header("Content-Length"));
  5663. EXPECT_EQ(false, res->has_header("Content-Range"));
  5664. EXPECT_EQ(JSON_DATA, res->body);
  5665. }
  5666. TEST_F(ServerTest, Issue1772) {
  5667. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5670. }
  5671. TEST_F(ServerTest, Issue609) {
  5672. auto res = cli_.Delete("/issue609");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::OK_200, res->status);
  5675. EXPECT_EQ(std::string("ok"), res->body);
  5676. }
  5677. TEST_F(ServerTest, GetStreamedChunked) {
  5678. auto res = cli_.Get("/streamed-chunked");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. EXPECT_EQ(std::string("123456789"), res->body);
  5682. }
  5683. TEST_F(ServerTest, GetStreamedChunked2) {
  5684. auto res = cli_.Get("/streamed-chunked2");
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. EXPECT_EQ(StatusCode::OK_200, res->status);
  5687. EXPECT_EQ(std::string("123456789"), res->body);
  5688. }
  5689. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5690. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. EXPECT_EQ(StatusCode::OK_200, res->status);
  5693. EXPECT_EQ(std::string("123456789"), res->body);
  5694. EXPECT_TRUE(res->has_header("Trailer"));
  5695. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5696. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5697. // Trailers are now stored separately from headers (security fix)
  5698. EXPECT_EQ(2U, res->trailers.size());
  5699. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5700. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5701. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5702. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5703. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5704. // Verify trailers are NOT in headers (security verification)
  5705. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5706. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5707. }
  5708. TEST_F(ServerTest, LargeChunkedPost) {
  5709. Request req;
  5710. req.method = "POST";
  5711. req.path = "/large-chunked";
  5712. std::string host_and_port;
  5713. host_and_port += HOST;
  5714. host_and_port += ":";
  5715. host_and_port += std::to_string(PORT);
  5716. req.headers.emplace("Host", host_and_port.c_str());
  5717. req.headers.emplace("Accept", "*/*");
  5718. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5719. req.headers.emplace("Content-Type", "text/plain");
  5720. req.headers.emplace("Content-Length", "0");
  5721. req.headers.emplace("Transfer-Encoding", "chunked");
  5722. std::string long_string(30 * 1024u, 'a');
  5723. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5724. // Attempt to make a large enough post to exceed OS buffers, to test that
  5725. // the server handles short reads if the full chunk data isn't available.
  5726. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5727. auto res = std::make_shared<Response>();
  5728. auto error = Error::Success;
  5729. auto ret = cli_.send(req, *res, error);
  5730. ASSERT_TRUE(ret);
  5731. EXPECT_EQ(StatusCode::OK_200, res->status);
  5732. }
  5733. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5734. auto res = cli_.Get("/remote_addr");
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. EXPECT_EQ(StatusCode::OK_200, res->status);
  5737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5738. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5739. }
  5740. TEST_F(ServerTest, GetMethodLocalAddr) {
  5741. auto res = cli_.Get("/local_addr");
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. EXPECT_EQ(StatusCode::OK_200, res->status);
  5744. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5745. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5746. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5747. }
  5748. TEST_F(ServerTest, HTTPResponseSplitting) {
  5749. auto res = cli_.Get("/http_response_splitting");
  5750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5751. EXPECT_EQ(StatusCode::OK_200, res->status);
  5752. }
  5753. TEST_F(ServerTest, SlowRequest) {
  5754. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5755. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5756. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5757. }
  5758. #if 0
  5759. TEST_F(ServerTest, SlowPost) {
  5760. char buffer[64 * 1024];
  5761. memset(buffer, 0x42, sizeof(buffer));
  5762. auto res = cli_.Post(
  5763. "/slowpost", 64 * 1024 * 1024,
  5764. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5765. auto ret = sink.write(buffer, sizeof(buffer));
  5766. EXPECT_TRUE(ret);
  5767. return true;
  5768. },
  5769. "text/plain");
  5770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5771. EXPECT_EQ(StatusCode::OK_200, res->status);
  5772. }
  5773. TEST_F(ServerTest, SlowPostFail) {
  5774. char buffer[64 * 1024];
  5775. memset(buffer, 0x42, sizeof(buffer));
  5776. cli_.set_write_timeout(std::chrono::seconds(0));
  5777. auto res = cli_.Post(
  5778. "/slowpost", 64 * 1024 * 1024,
  5779. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5780. sink.write(buffer, sizeof(buffer));
  5781. return true;
  5782. },
  5783. "text/plain");
  5784. ASSERT_TRUE(!res);
  5785. EXPECT_EQ(Error::Write, res.error());
  5786. }
  5787. #endif
  5788. TEST_F(ServerTest, Put) {
  5789. auto res = cli_.Put("/put", "PUT", "text/plain");
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. EXPECT_EQ("PUT", res->body);
  5793. }
  5794. TEST_F(ServerTest, PutWithContentProvider) {
  5795. auto res = cli_.Put(
  5796. "/put", 3,
  5797. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5798. sink.os << "PUT";
  5799. return true;
  5800. },
  5801. "text/plain");
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. EXPECT_EQ(StatusCode::OK_200, res->status);
  5804. EXPECT_EQ("PUT", res->body);
  5805. }
  5806. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5807. auto res = cli_.Post(
  5808. "/post", 42,
  5809. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5810. return false;
  5811. },
  5812. "text/plain");
  5813. ASSERT_TRUE(!res);
  5814. EXPECT_EQ(Error::Canceled, res.error());
  5815. }
  5816. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5817. auto res = cli_.Put(
  5818. "/put",
  5819. [](size_t /*offset*/, DataSink &sink) {
  5820. sink.os << "PUT";
  5821. sink.done();
  5822. return true;
  5823. },
  5824. "text/plain");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. EXPECT_EQ("PUT", res->body);
  5828. }
  5829. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5830. auto res = cli_.Post(
  5831. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5832. "text/plain");
  5833. ASSERT_TRUE(!res);
  5834. EXPECT_EQ(Error::Canceled, res.error());
  5835. }
  5836. TEST_F(ServerTest, PostLoopBack) {
  5837. std::string body;
  5838. auto res = cli_.Post(
  5839. "/post-loopback", 9,
  5840. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5841. EXPECT_EQ(9u, length);
  5842. sink.write("123", 3);
  5843. sink.write("456", 3);
  5844. sink.write("789", 3);
  5845. return true;
  5846. },
  5847. "text/plain",
  5848. [&body](const char *data, size_t data_length) {
  5849. body.append(data, data_length);
  5850. return true;
  5851. });
  5852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5853. EXPECT_EQ(StatusCode::OK_200, res->status);
  5854. EXPECT_EQ("123456789", body);
  5855. }
  5856. TEST_F(ServerTest, PutLoopBack) {
  5857. std::string body;
  5858. auto res = cli_.Put(
  5859. "/put-loopback", 9,
  5860. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5861. EXPECT_EQ(9u, length);
  5862. sink.write("123", 3);
  5863. sink.write("456", 3);
  5864. sink.write("789", 3);
  5865. return true;
  5866. },
  5867. "text/plain",
  5868. [&body](const char *data, size_t data_length) {
  5869. body.append(data, data_length);
  5870. return true;
  5871. });
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. EXPECT_EQ(StatusCode::OK_200, res->status);
  5874. EXPECT_EQ("123456789", body);
  5875. }
  5876. TEST_F(ServerTest, PatchLoopBack) {
  5877. std::string body;
  5878. auto res = cli_.Patch(
  5879. "/patch-loopback", 9,
  5880. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5881. EXPECT_EQ(9u, length);
  5882. sink.write("123", 3);
  5883. sink.write("456", 3);
  5884. sink.write("789", 3);
  5885. return true;
  5886. },
  5887. "text/plain",
  5888. [&body](const char *data, size_t data_length) {
  5889. body.append(data, data_length);
  5890. return true;
  5891. });
  5892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5893. EXPECT_EQ(StatusCode::OK_200, res->status);
  5894. EXPECT_EQ("123456789", body);
  5895. }
  5896. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5897. std::string body;
  5898. auto res = cli_.Post(
  5899. "/post-loopback",
  5900. [](size_t /*offset*/, DataSink &sink) {
  5901. sink.write("123", 3);
  5902. sink.write("456", 3);
  5903. sink.write("789", 3);
  5904. sink.done();
  5905. return true;
  5906. },
  5907. "text/plain",
  5908. [&body](const char *data, size_t data_length) {
  5909. body.append(data, data_length);
  5910. return true;
  5911. });
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. EXPECT_EQ("123456789", body);
  5915. }
  5916. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5917. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5918. cli_.set_compress(true);
  5919. auto res = cli_.Put(
  5920. "/put", 3,
  5921. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5922. sink.os << "PUT";
  5923. return true;
  5924. },
  5925. "text/plain");
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. EXPECT_EQ("PUT", res->body);
  5929. }
  5930. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5931. cli_.set_compress(true);
  5932. auto res = cli_.Post(
  5933. "/post", 42,
  5934. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5935. return false;
  5936. },
  5937. "text/plain");
  5938. ASSERT_TRUE(!res);
  5939. EXPECT_EQ(Error::Canceled, res.error());
  5940. }
  5941. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5942. cli_.set_compress(true);
  5943. auto res = cli_.Put(
  5944. "/put",
  5945. [](size_t /*offset*/, DataSink &sink) {
  5946. sink.os << "PUT";
  5947. sink.done();
  5948. return true;
  5949. },
  5950. "text/plain");
  5951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5952. EXPECT_EQ(StatusCode::OK_200, res->status);
  5953. EXPECT_EQ("PUT", res->body);
  5954. }
  5955. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5956. cli_.set_compress(true);
  5957. auto res = cli_.Post(
  5958. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5959. "text/plain");
  5960. ASSERT_TRUE(!res);
  5961. EXPECT_EQ(Error::Canceled, res.error());
  5962. }
  5963. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5964. cli_.set_compress(true);
  5965. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. EXPECT_EQ(LARGE_DATA, res->body);
  5969. }
  5970. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5971. #ifdef CPPHTTPLIB_SSL_ENABLED
  5972. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5973. Client cli(s.c_str());
  5974. cli.enable_server_certificate_verification(false);
  5975. #else
  5976. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5977. Client cli(s.c_str());
  5978. #endif
  5979. cli.set_compress(true);
  5980. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5982. EXPECT_EQ(StatusCode::OK_200, res->status);
  5983. EXPECT_EQ(LARGE_DATA, res->body);
  5984. // The compressed size should be less than a 10th of the original. May vary
  5985. // depending on the zlib library.
  5986. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5987. static_cast<uint64_t>(10 * 1024 * 1024));
  5988. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5989. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5990. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5991. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5992. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5993. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5994. #endif
  5995. }
  5996. TEST_F(ServerTest, PutContentWithDeflate) {
  5997. cli_.set_compress(false);
  5998. Headers headers;
  5999. headers.emplace("Content-Encoding", "deflate");
  6000. // PUT in deflate format:
  6001. auto res = cli_.Put("/put", headers,
  6002. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6004. EXPECT_EQ(StatusCode::OK_200, res->status);
  6005. EXPECT_EQ("PUT", res->body);
  6006. }
  6007. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6008. Headers headers;
  6009. headers.emplace("Accept-Encoding", "gzip, deflate");
  6010. auto res = cli_.Get("/streamed-chunked", headers);
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. EXPECT_EQ(StatusCode::OK_200, res->status);
  6013. EXPECT_EQ(std::string("123456789"), res->body);
  6014. }
  6015. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6016. Headers headers;
  6017. headers.emplace("Accept-Encoding", "gzip, deflate");
  6018. auto res = cli_.Get("/streamed-chunked2", headers);
  6019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6020. EXPECT_EQ(StatusCode::OK_200, res->status);
  6021. EXPECT_EQ(std::string("123456789"), res->body);
  6022. }
  6023. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6024. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. }
  6028. TEST(GzipDecompressor, ChunkedDecompression) {
  6029. std::string data;
  6030. for (size_t i = 0; i < 32 * 1024; ++i) {
  6031. data.push_back(static_cast<char>('a' + i % 26));
  6032. }
  6033. std::string compressed_data;
  6034. {
  6035. httplib::detail::gzip_compressor compressor;
  6036. bool result = compressor.compress(
  6037. data.data(), data.size(),
  6038. /*last=*/true,
  6039. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6040. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6041. compressed_data_size);
  6042. return true;
  6043. });
  6044. ASSERT_TRUE(result);
  6045. }
  6046. std::string decompressed_data;
  6047. {
  6048. httplib::detail::gzip_decompressor decompressor;
  6049. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6050. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6051. size_t chunk_size = 130;
  6052. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6053. chunk_begin += chunk_size) {
  6054. size_t current_chunk_size =
  6055. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6056. bool result = decompressor.decompress(
  6057. compressed_data.data() + chunk_begin, current_chunk_size,
  6058. [&](const char *decompressed_data_chunk,
  6059. size_t decompressed_data_chunk_size) {
  6060. decompressed_data.insert(decompressed_data.size(),
  6061. decompressed_data_chunk,
  6062. decompressed_data_chunk_size);
  6063. return true;
  6064. });
  6065. ASSERT_TRUE(result);
  6066. }
  6067. }
  6068. ASSERT_EQ(data, decompressed_data);
  6069. }
  6070. TEST(GzipDecompressor, DeflateDecompression) {
  6071. std::string original_text = "Raw deflate without gzip";
  6072. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6073. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6074. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6075. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6076. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6077. std::string decompressed_data;
  6078. {
  6079. httplib::detail::gzip_decompressor decompressor;
  6080. bool result = decompressor.decompress(
  6081. compressed_data.data(), compressed_data.size(),
  6082. [&](const char *decompressed_data_chunk,
  6083. size_t decompressed_data_chunk_size) {
  6084. decompressed_data.insert(decompressed_data.size(),
  6085. decompressed_data_chunk,
  6086. decompressed_data_chunk_size);
  6087. return true;
  6088. });
  6089. ASSERT_TRUE(result);
  6090. }
  6091. ASSERT_EQ(original_text, decompressed_data);
  6092. }
  6093. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6094. std::string original_text = "Raw deflate without gzip";
  6095. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6096. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6097. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6098. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6099. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6100. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6101. std::string decompressed_data;
  6102. {
  6103. httplib::detail::gzip_decompressor decompressor;
  6104. bool result = decompressor.decompress(
  6105. compressed_data.data(), compressed_data.size(),
  6106. [&](const char *decompressed_data_chunk,
  6107. size_t decompressed_data_chunk_size) {
  6108. decompressed_data.insert(decompressed_data.size(),
  6109. decompressed_data_chunk,
  6110. decompressed_data_chunk_size);
  6111. return true;
  6112. });
  6113. ASSERT_TRUE(result);
  6114. }
  6115. ASSERT_EQ(original_text, decompressed_data);
  6116. }
  6117. #endif
  6118. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6119. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6120. Headers headers;
  6121. headers.emplace("Accept-Encoding", "br");
  6122. auto res = cli_.Get("/streamed-chunked", headers);
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. EXPECT_EQ(StatusCode::OK_200, res->status);
  6125. EXPECT_EQ(std::string("123456789"), res->body);
  6126. }
  6127. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6128. Headers headers;
  6129. headers.emplace("Accept-Encoding", "br");
  6130. auto res = cli_.Get("/streamed-chunked2", headers);
  6131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6132. EXPECT_EQ(StatusCode::OK_200, res->status);
  6133. EXPECT_EQ(std::string("123456789"), res->body);
  6134. }
  6135. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6136. cli_.set_compress(true);
  6137. auto res = cli_.Put(
  6138. "/put", 3,
  6139. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6140. sink.os << "PUT";
  6141. return true;
  6142. },
  6143. "text/plain");
  6144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6145. EXPECT_EQ(StatusCode::OK_200, res->status);
  6146. EXPECT_EQ("PUT", res->body);
  6147. }
  6148. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6149. cli_.set_compress(true);
  6150. auto res = cli_.Put(
  6151. "/put",
  6152. [](size_t /*offset*/, DataSink &sink) {
  6153. sink.os << "PUT";
  6154. sink.done();
  6155. return true;
  6156. },
  6157. "text/plain");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::OK_200, res->status);
  6160. EXPECT_EQ("PUT", res->body);
  6161. }
  6162. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6163. cli_.set_compress(true);
  6164. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. EXPECT_EQ(LARGE_DATA, res->body);
  6168. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6169. }
  6170. #endif
  6171. TEST_F(ServerTest, Patch) {
  6172. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. EXPECT_EQ("PATCH", res->body);
  6176. }
  6177. TEST_F(ServerTest, Delete) {
  6178. auto res = cli_.Delete("/delete");
  6179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6180. EXPECT_EQ(StatusCode::OK_200, res->status);
  6181. EXPECT_EQ("DELETE", res->body);
  6182. }
  6183. TEST_F(ServerTest, DeleteContentReceiver) {
  6184. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::OK_200, res->status);
  6187. EXPECT_EQ("content", res->body);
  6188. }
  6189. TEST_F(ServerTest, Options) {
  6190. auto res = cli_.Options("*");
  6191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6192. EXPECT_EQ(StatusCode::OK_200, res->status);
  6193. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6194. EXPECT_TRUE(res->body.empty());
  6195. }
  6196. TEST_F(ServerTest, URL) {
  6197. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::OK_200, res->status);
  6200. }
  6201. TEST_F(ServerTest, ArrayParam) {
  6202. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. }
  6206. TEST_F(ServerTest, ArrayParamValues) {
  6207. auto res =
  6208. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. EXPECT_EQ(StatusCode::OK_200, res->status);
  6211. }
  6212. TEST_F(ServerTest, NoMultipleHeaders) {
  6213. Headers headers = {{"Content-Length", "5"}};
  6214. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6215. "text/plain");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. }
  6219. TEST_F(ServerTest, PostContentReceiver) {
  6220. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6222. ASSERT_EQ(StatusCode::OK_200, res->status);
  6223. ASSERT_EQ("content", res->body);
  6224. }
  6225. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6226. UploadFormDataItems items = {
  6227. {"text1", "text default", "", ""},
  6228. {"text2", "aωb", "", ""},
  6229. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6230. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6231. {"file3", "", "", "application/octet-stream"},
  6232. };
  6233. auto res = cli_.Post("/content_receiver", items);
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::OK_200, res->status);
  6236. }
  6237. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6238. UploadFormDataItems items = {
  6239. {"text1", "text default", "", ""},
  6240. {"text2", "aωb", "", ""},
  6241. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6242. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6243. {"file3", "", "", "application/octet-stream"},
  6244. };
  6245. auto boundary = std::string("+++++");
  6246. std::string body;
  6247. for (const auto &item : items) {
  6248. body += "--" + boundary + "\r\n";
  6249. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6250. if (!item.filename.empty()) {
  6251. body += "; filename=\"" + item.filename + "\"";
  6252. }
  6253. body += "\r\n";
  6254. if (!item.content_type.empty()) {
  6255. body += "Content-Type: " + item.content_type + "\r\n";
  6256. }
  6257. body += "\r\n";
  6258. body += item.content + "\r\n";
  6259. }
  6260. body += "--" + boundary + "--\r\n";
  6261. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6262. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::OK_200, res->status);
  6265. }
  6266. TEST(MultipartFormDataTest, FieldEscaping) {
  6267. Server svr;
  6268. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6269. const ContentReader &content_reader) {
  6270. ASSERT_TRUE(req.is_multipart_form_data());
  6271. std::vector<FormData> received;
  6272. content_reader(
  6273. [&](const FormData &file) {
  6274. received.push_back(file);
  6275. return true;
  6276. },
  6277. [&](const char *data, size_t data_length) {
  6278. received.back().content.append(data, data_length);
  6279. return true;
  6280. });
  6281. // '"', CR and LF in names and filenames are escaped following the
  6282. // WHATWG HTML standard, so each part still parses as a single part
  6283. // with no injected headers. Content types get CR/LF escaped too,
  6284. // while '"' (legal there, e.g. quoted charset) is preserved.
  6285. ASSERT_EQ(4U, received.size());
  6286. EXPECT_EQ("na%22me", received[0].name);
  6287. EXPECT_EQ("quoted name", received[0].content);
  6288. EXPECT_EQ("file", received[1].name);
  6289. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6290. received[1].filename);
  6291. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6292. EXPECT_EQ("injected", received[1].content);
  6293. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6294. EXPECT_EQ("my%22file.txt", received[2].filename);
  6295. EXPECT_EQ("cr lf name", received[2].content);
  6296. EXPECT_EQ("typed", received[3].name);
  6297. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6298. received[3].content_type);
  6299. EXPECT_EQ("typed content", received[3].content);
  6300. });
  6301. auto port = svr.bind_to_any_port("localhost");
  6302. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6303. auto se = detail::scope_exit([&] {
  6304. svr.stop();
  6305. t.join();
  6306. ASSERT_FALSE(svr.is_running());
  6307. });
  6308. svr.wait_until_ready();
  6309. Client cli("localhost", port);
  6310. UploadFormDataItems items = {
  6311. {"na\"me", "quoted name", "", ""},
  6312. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6313. "application/octet-stream"},
  6314. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6315. {"typed", "typed content", "",
  6316. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6317. };
  6318. auto res = cli.Post("/post", items);
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::OK_200, res->status);
  6321. }
  6322. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6323. const UploadFormDataItems items = {
  6324. {"name1", "Content 1", "", ""},
  6325. {"name2", "Content 2", "file2.txt", "text/plain"},
  6326. };
  6327. Server svr;
  6328. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6329. const ContentReader &content_reader) {
  6330. ASSERT_TRUE(req.is_multipart_form_data());
  6331. std::vector<FormData> received;
  6332. content_reader(
  6333. [&](const FormData &file) {
  6334. received.push_back(file);
  6335. return true;
  6336. },
  6337. [&](const char *data, size_t data_length) {
  6338. received.back().content.append(data, data_length);
  6339. return true;
  6340. });
  6341. ASSERT_EQ(2U, received.size());
  6342. EXPECT_EQ("name1", received[0].name);
  6343. EXPECT_EQ("Content 1", received[0].content);
  6344. EXPECT_EQ("name2", received[1].name);
  6345. EXPECT_EQ("Content 2", received[1].content);
  6346. EXPECT_EQ("file2.txt", received[1].filename);
  6347. EXPECT_EQ("text/plain", received[1].content_type);
  6348. });
  6349. auto port = svr.bind_to_any_port("localhost");
  6350. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6351. auto se = detail::scope_exit([&] {
  6352. svr.stop();
  6353. t.join();
  6354. ASSERT_FALSE(svr.is_running());
  6355. });
  6356. svr.wait_until_ready();
  6357. Client cli("localhost", port);
  6358. // Whole-body serialization with a generated boundary
  6359. {
  6360. MultipartFormDataWriter writer;
  6361. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6362. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6363. writer.content_type());
  6364. auto body = writer.serialize(items);
  6365. EXPECT_EQ(body.size(), writer.content_length(items));
  6366. auto res = cli.Post("/post", body, writer.content_type());
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. }
  6370. // Per-part framing with a custom boundary via a content provider
  6371. {
  6372. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6373. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6374. MultipartFormDataWriter writer("custom-boundary_123");
  6375. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6376. std::string body;
  6377. for (const auto &item : items) {
  6378. body += writer.item_begin(item);
  6379. body += item.content;
  6380. body += MultipartFormDataWriter::item_end();
  6381. }
  6382. body += writer.finish();
  6383. EXPECT_EQ(body.size(), writer.content_length(items));
  6384. auto res = cli.Post(
  6385. "/post", body.size(),
  6386. [&](size_t offset, size_t length, DataSink &sink) {
  6387. sink.write(body.data() + offset, length);
  6388. return true;
  6389. },
  6390. writer.content_type());
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. }
  6394. }
  6395. TEST_F(ServerTest, PostContentReceiverGzip) {
  6396. cli_.set_compress(true);
  6397. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. ASSERT_EQ("content", res->body);
  6401. }
  6402. TEST_F(ServerTest, PutContentReceiver) {
  6403. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("content", res->body);
  6407. }
  6408. TEST_F(ServerTest, PatchContentReceiver) {
  6409. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. ASSERT_EQ(StatusCode::OK_200, res->status);
  6412. ASSERT_EQ("content", res->body);
  6413. }
  6414. template <typename ClientType>
  6415. void TestWithHeadersAndContentReceiver(
  6416. ClientType &cli,
  6417. std::function<Result(ClientType &, const std::string &, const Headers &,
  6418. const std::string &, const std::string &,
  6419. ContentReceiver, DownloadProgress)>
  6420. request_func) {
  6421. Headers headers;
  6422. headers.emplace("X-Custom-Header", "test-value");
  6423. std::string received_body;
  6424. auto res = request_func(
  6425. cli, "/content_receiver", headers, "content", "application/json",
  6426. [&](const char *data, size_t data_length) {
  6427. received_body.append(data, data_length);
  6428. return true;
  6429. },
  6430. nullptr);
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::OK_200, res->status);
  6433. EXPECT_EQ("content", received_body);
  6434. }
  6435. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6436. #ifdef CPPHTTPLIB_SSL_ENABLED
  6437. using ClientT = SSLClient;
  6438. #else
  6439. using ClientT = Client;
  6440. #endif
  6441. TestWithHeadersAndContentReceiver<ClientT>(
  6442. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6443. const std::string &body, const std::string &content_type,
  6444. ContentReceiver receiver, DownloadProgress progress) {
  6445. return cli.Post(path, headers, body, content_type, receiver, progress);
  6446. });
  6447. }
  6448. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6449. #ifdef CPPHTTPLIB_SSL_ENABLED
  6450. using ClientT = SSLClient;
  6451. #else
  6452. using ClientT = Client;
  6453. #endif
  6454. TestWithHeadersAndContentReceiver<ClientT>(
  6455. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6456. const std::string &body, const std::string &content_type,
  6457. ContentReceiver receiver, DownloadProgress progress) {
  6458. return cli.Put(path, headers, body, content_type, receiver, progress);
  6459. });
  6460. }
  6461. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6462. #ifdef CPPHTTPLIB_SSL_ENABLED
  6463. using ClientT = SSLClient;
  6464. #else
  6465. using ClientT = Client;
  6466. #endif
  6467. TestWithHeadersAndContentReceiver<ClientT>(
  6468. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6469. const std::string &body, const std::string &content_type,
  6470. ContentReceiver receiver, DownloadProgress progress) {
  6471. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6472. });
  6473. }
  6474. template <typename ClientType>
  6475. void TestWithHeadersAndContentReceiverWithProgress(
  6476. ClientType &cli,
  6477. std::function<Result(ClientType &, const std::string &, const Headers &,
  6478. const std::string &, const std::string &,
  6479. ContentReceiver, DownloadProgress)>
  6480. request_func) {
  6481. Headers headers;
  6482. headers.emplace("X-Test-Header", "progress-test");
  6483. std::string received_body;
  6484. auto progress_called = false;
  6485. auto res = request_func(
  6486. cli, "/content_receiver", headers, "content", "text/plain",
  6487. [&](const char *data, size_t data_length) {
  6488. received_body.append(data, data_length);
  6489. return true;
  6490. },
  6491. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6492. progress_called = true;
  6493. return true;
  6494. });
  6495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6496. EXPECT_EQ(StatusCode::OK_200, res->status);
  6497. EXPECT_EQ("content", received_body);
  6498. EXPECT_TRUE(progress_called);
  6499. }
  6500. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6501. #ifdef CPPHTTPLIB_SSL_ENABLED
  6502. using ClientT = SSLClient;
  6503. #else
  6504. using ClientT = Client;
  6505. #endif
  6506. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6507. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6508. const std::string &body, const std::string &content_type,
  6509. ContentReceiver receiver, DownloadProgress progress) {
  6510. return cli.Post(path, headers, body, content_type, receiver, progress);
  6511. });
  6512. }
  6513. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6514. #ifdef CPPHTTPLIB_SSL_ENABLED
  6515. using ClientT = SSLClient;
  6516. #else
  6517. using ClientT = Client;
  6518. #endif
  6519. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6520. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6521. const std::string &body, const std::string &content_type,
  6522. ContentReceiver receiver, DownloadProgress progress) {
  6523. return cli.Put(path, headers, body, content_type, receiver, progress);
  6524. });
  6525. }
  6526. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6527. #ifdef CPPHTTPLIB_SSL_ENABLED
  6528. using ClientT = SSLClient;
  6529. #else
  6530. using ClientT = Client;
  6531. #endif
  6532. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6533. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6534. const std::string &body, const std::string &content_type,
  6535. ContentReceiver receiver, DownloadProgress progress) {
  6536. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6537. });
  6538. }
  6539. template <typename ClientType>
  6540. void TestWithHeadersAndContentReceiverError(
  6541. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6542. const Headers &, const std::string &,
  6543. const std::string &, ContentReceiver)>
  6544. request_func) {
  6545. Headers headers;
  6546. headers.emplace("X-Error-Test", "true");
  6547. std::string received_body;
  6548. auto receiver_failed = false;
  6549. auto res =
  6550. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6551. [&](const char *data, size_t data_length) {
  6552. received_body.append(data, data_length);
  6553. receiver_failed = true;
  6554. return false;
  6555. });
  6556. ASSERT_FALSE(res);
  6557. EXPECT_TRUE(receiver_failed);
  6558. }
  6559. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6560. #ifdef CPPHTTPLIB_SSL_ENABLED
  6561. using ClientT = SSLClient;
  6562. #else
  6563. using ClientT = Client;
  6564. #endif
  6565. TestWithHeadersAndContentReceiverError<ClientT>(
  6566. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6567. const std::string &body, const std::string &content_type,
  6568. ContentReceiver receiver) {
  6569. return cli.Post(path, headers, body, content_type, receiver);
  6570. });
  6571. }
  6572. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6573. #ifdef CPPHTTPLIB_SSL_ENABLED
  6574. using ClientT = SSLClient;
  6575. #else
  6576. using ClientT = Client;
  6577. #endif
  6578. TestWithHeadersAndContentReceiverError<ClientT>(
  6579. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6580. const std::string &body, const std::string &content_type,
  6581. ContentReceiver receiver) {
  6582. return cli.Put(path, headers, body, content_type, receiver);
  6583. });
  6584. }
  6585. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6586. #ifdef CPPHTTPLIB_SSL_ENABLED
  6587. using ClientT = SSLClient;
  6588. #else
  6589. using ClientT = Client;
  6590. #endif
  6591. TestWithHeadersAndContentReceiverError<ClientT>(
  6592. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6593. const std::string &body, const std::string &content_type,
  6594. ContentReceiver receiver) {
  6595. return cli.Patch(path, headers, body, content_type, receiver);
  6596. });
  6597. }
  6598. TEST_F(ServerTest, PostQueryStringAndBody) {
  6599. auto res =
  6600. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. ASSERT_EQ(StatusCode::OK_200, res->status);
  6603. }
  6604. TEST_F(ServerTest, HTTP2Magic) {
  6605. Request req;
  6606. req.method = "PRI";
  6607. req.path = "*";
  6608. req.body = "SM";
  6609. auto res = std::make_shared<Response>();
  6610. auto error = Error::Success;
  6611. auto ret = cli_.send(req, *res, error);
  6612. ASSERT_TRUE(ret);
  6613. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6614. }
  6615. TEST_F(ServerTest, KeepAlive) {
  6616. auto res = cli_.Get("/hi");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6620. EXPECT_EQ("Hello World!", res->body);
  6621. res = cli_.Get("/hi");
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::OK_200, res->status);
  6624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6625. EXPECT_EQ("Hello World!", res->body);
  6626. res = cli_.Get("/hi");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::OK_200, res->status);
  6629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6630. EXPECT_EQ("Hello World!", res->body);
  6631. res = cli_.Get("/not-exist");
  6632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6634. res = cli_.Post("/empty", "", "text/plain");
  6635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6636. EXPECT_EQ(StatusCode::OK_200, res->status);
  6637. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6638. EXPECT_EQ("empty", res->body);
  6639. EXPECT_EQ("close", res->get_header_value("Connection"));
  6640. res = cli_.Post(
  6641. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6642. "text/plain");
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::OK_200, res->status);
  6645. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6646. EXPECT_EQ("empty", res->body);
  6647. cli_.set_keep_alive(false);
  6648. res = cli_.Get("/last-request");
  6649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. EXPECT_EQ("close", res->get_header_value("Connection"));
  6652. }
  6653. TEST_F(ServerTest, TooManyRedirect) {
  6654. cli_.set_follow_location(true);
  6655. auto res = cli_.Get("/redirect/0");
  6656. ASSERT_TRUE(!res);
  6657. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6658. }
  6659. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6660. Request req;
  6661. req.method = "FOOBAR";
  6662. req.path = "/hi";
  6663. cli_.set_keep_alive(true);
  6664. auto res = cli_.send(req);
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6667. EXPECT_EQ("close", res->get_header_value("Connection"));
  6668. EXPECT_FALSE(cli_.is_socket_open());
  6669. }
  6670. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6671. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6672. TEST_F(ServerTest, Gzip) {
  6673. Headers headers;
  6674. headers.emplace("Accept-Encoding", "gzip, deflate");
  6675. auto res = cli_.Get("/compress", headers);
  6676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6677. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6678. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6679. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6680. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6681. "7890123456789012345678901234567890",
  6682. res->body);
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. }
  6685. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6686. Headers headers;
  6687. headers.emplace("Accept-Encoding", "gzip, deflate");
  6688. auto res = cli_.Get("/compress-with-charset", headers);
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6691. EXPECT_EQ("application/json; charset=utf-8",
  6692. res->get_header_value("Content-Type"));
  6693. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6694. "7890123456789012345678901234567890",
  6695. res->body);
  6696. EXPECT_EQ(StatusCode::OK_200, res->status);
  6697. }
  6698. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6699. Headers headers;
  6700. headers.emplace("Accept-Encoding", "");
  6701. auto res = cli_.Get("/compress", headers);
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6705. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6706. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6707. "7890123456789012345678901234567890",
  6708. res->body);
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. }
  6711. TEST_F(ServerTest, GzipWithContentReceiver) {
  6712. Headers headers;
  6713. headers.emplace("Accept-Encoding", "gzip, deflate");
  6714. std::string body;
  6715. auto res = cli_.Get("/compress", headers,
  6716. [&](const char *data, uint64_t data_length) {
  6717. EXPECT_EQ(100U, data_length);
  6718. body.append(data, data_length);
  6719. return true;
  6720. });
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6724. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6725. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6726. "7890123456789012345678901234567890",
  6727. body);
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. }
  6730. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6731. Headers headers;
  6732. headers.emplace("Accept-Encoding", "gzip, deflate");
  6733. cli_.set_decompress(false);
  6734. auto res = cli_.Get("/compress", headers);
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6738. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6739. EXPECT_EQ(33U, res->body.size());
  6740. EXPECT_EQ(StatusCode::OK_200, res->status);
  6741. }
  6742. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6743. Headers headers;
  6744. headers.emplace("Accept-Encoding", "");
  6745. std::string body;
  6746. auto res = cli_.Get("/compress", headers,
  6747. [&](const char *data, uint64_t data_length) {
  6748. EXPECT_EQ(100U, data_length);
  6749. body.append(data, data_length);
  6750. return true;
  6751. });
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6755. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6756. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6757. "7890123456789012345678901234567890",
  6758. body);
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. }
  6761. TEST_F(ServerTest, NoGzip) {
  6762. Headers headers;
  6763. headers.emplace("Accept-Encoding", "gzip, deflate");
  6764. auto res = cli_.Get("/nocompress", headers);
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6767. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6768. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6769. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6770. "7890123456789012345678901234567890",
  6771. res->body);
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. }
  6774. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6775. Headers headers;
  6776. headers.emplace("Accept-Encoding", "gzip, deflate");
  6777. std::string body;
  6778. auto res = cli_.Get("/nocompress", headers,
  6779. [&](const char *data, uint64_t data_length) {
  6780. EXPECT_EQ(100U, data_length);
  6781. body.append(data, data_length);
  6782. return true;
  6783. });
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6786. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6787. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6788. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6789. "7890123456789012345678901234567890",
  6790. body);
  6791. EXPECT_EQ(StatusCode::OK_200, res->status);
  6792. }
  6793. TEST_F(ServerTest, MultipartFormDataGzip) {
  6794. UploadFormDataItems items = {
  6795. {"key1", "test", "", ""},
  6796. {"key2", "--abcdefg123", "", ""},
  6797. };
  6798. cli_.set_compress(true);
  6799. auto res = cli_.Post("/compress-multipart", items);
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. #endif
  6804. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6805. TEST_F(ServerTest, Brotli) {
  6806. Headers headers;
  6807. headers.emplace("Accept-Encoding", "br");
  6808. auto res = cli_.Get("/compress", headers);
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6811. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6812. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6813. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6814. "7890123456789012345678901234567890",
  6815. res->body);
  6816. EXPECT_EQ(StatusCode::OK_200, res->status);
  6817. }
  6818. #endif
  6819. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6820. TEST_F(ServerTest, Zstd) {
  6821. Headers headers;
  6822. headers.emplace("Accept-Encoding", "zstd");
  6823. auto res = cli_.Get("/compress", headers);
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6826. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6827. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6828. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6829. "7890123456789012345678901234567890",
  6830. res->body);
  6831. EXPECT_EQ(StatusCode::OK_200, res->status);
  6832. }
  6833. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6834. Headers headers;
  6835. headers.emplace("Accept-Encoding", "");
  6836. auto res = cli_.Get("/compress", headers);
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6839. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6840. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6841. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6842. "7890123456789012345678901234567890",
  6843. res->body);
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. }
  6846. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6847. Headers headers;
  6848. headers.emplace("Accept-Encoding", "zstd");
  6849. std::string body;
  6850. auto res = cli_.Get("/compress", headers,
  6851. [&](const char *data, uint64_t data_length) {
  6852. EXPECT_EQ(100U, data_length);
  6853. body.append(data, data_length);
  6854. return true;
  6855. });
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6858. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6859. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6860. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6861. "7890123456789012345678901234567890",
  6862. body);
  6863. EXPECT_EQ(StatusCode::OK_200, res->status);
  6864. }
  6865. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6866. Headers headers;
  6867. headers.emplace("Accept-Encoding", "zstd");
  6868. cli_.set_decompress(false);
  6869. auto res = cli_.Get("/compress", headers);
  6870. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6871. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6872. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6873. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6877. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6878. EXPECT_EQ(StatusCode::OK_200, res->status);
  6879. ASSERT_EQ(26U, res->body.size());
  6880. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6881. 0);
  6882. }
  6883. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6884. Headers headers;
  6885. headers.emplace("Accept-Encoding", "");
  6886. std::string body;
  6887. auto res = cli_.Get("/compress", headers,
  6888. [&](const char *data, uint64_t data_length) {
  6889. EXPECT_EQ(100U, data_length);
  6890. body.append(data, data_length);
  6891. return true;
  6892. });
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6895. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6896. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6897. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6898. "7890123456789012345678901234567890",
  6899. body);
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. }
  6902. TEST_F(ServerTest, NoZstd) {
  6903. Headers headers;
  6904. headers.emplace("Accept-Encoding", "zstd");
  6905. auto res = cli_.Get("/nocompress", headers);
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6908. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6909. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6911. "7890123456789012345678901234567890",
  6912. res->body);
  6913. EXPECT_EQ(StatusCode::OK_200, res->status);
  6914. }
  6915. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6916. Headers headers;
  6917. headers.emplace("Accept-Encoding", "zstd");
  6918. std::string body;
  6919. auto res = cli_.Get("/nocompress", headers,
  6920. [&](const char *data, uint64_t data_length) {
  6921. EXPECT_EQ(100U, data_length);
  6922. body.append(data, data_length);
  6923. return true;
  6924. });
  6925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6926. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6927. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6928. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6929. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6930. "7890123456789012345678901234567890",
  6931. body);
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. }
  6934. // TODO: How to enable zstd ??
  6935. TEST_F(ServerTest, MultipartFormDataZstd) {
  6936. UploadFormDataItems items = {
  6937. {"key1", "test", "", ""},
  6938. {"key2", "--abcdefg123", "", ""},
  6939. };
  6940. Headers headers;
  6941. headers.emplace("Accept-Encoding", "zstd");
  6942. cli_.set_compress(true);
  6943. auto res = cli_.Post("/compress-multipart", headers, items);
  6944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6945. EXPECT_EQ(StatusCode::OK_200, res->status);
  6946. }
  6947. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6948. Headers headers;
  6949. headers.emplace("Accept-Encoding", "zstd");
  6950. cli_.set_compress(true);
  6951. auto res = cli_.Put(
  6952. "/put", headers, 3,
  6953. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6954. sink.os << "PUT";
  6955. return true;
  6956. },
  6957. "text/plain");
  6958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6959. EXPECT_EQ(StatusCode::OK_200, res->status);
  6960. EXPECT_EQ("PUT", res->body);
  6961. }
  6962. // Pre-compression logging tests
  6963. TEST_F(ServerTest, PreCompressionLogging) {
  6964. // Test data for compression (matches the actual /compress endpoint content)
  6965. const std::string test_content =
  6966. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6967. "3456789012345678901234567890";
  6968. // Variables to capture logging data
  6969. std::string pre_compression_body;
  6970. std::string pre_compression_content_type;
  6971. std::string pre_compression_content_encoding;
  6972. std::string post_compression_body;
  6973. std::string post_compression_content_type;
  6974. std::string post_compression_content_encoding;
  6975. // Set up pre-compression logger
  6976. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6977. const Response &res) {
  6978. pre_compression_body = res.body;
  6979. pre_compression_content_type = res.get_header_value("Content-Type");
  6980. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6981. });
  6982. // Set up post-compression logger
  6983. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6984. post_compression_body = res.body;
  6985. post_compression_content_type = res.get_header_value("Content-Type");
  6986. post_compression_content_encoding =
  6987. res.get_header_value("Content-Encoding");
  6988. });
  6989. // Test with gzip compression
  6990. Headers headers;
  6991. headers.emplace("Accept-Encoding", "gzip");
  6992. auto res = cli_.Get("/compress", headers);
  6993. // Verify response was compressed
  6994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6997. // Verify pre-compression logger captured uncompressed content
  6998. EXPECT_EQ(test_content, pre_compression_body);
  6999. EXPECT_EQ("text/plain", pre_compression_content_type);
  7000. EXPECT_TRUE(pre_compression_content_encoding
  7001. .empty()); // No encoding header before compression
  7002. // Verify post-compression logger captured compressed content
  7003. EXPECT_NE(test_content,
  7004. post_compression_body); // Should be different after compression
  7005. EXPECT_EQ("text/plain", post_compression_content_type);
  7006. EXPECT_EQ("gzip", post_compression_content_encoding);
  7007. // Verify compressed content is smaller
  7008. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7009. }
  7010. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7011. const std::string test_content =
  7012. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7013. "3456789012345678901234567890";
  7014. std::string pre_compression_body;
  7015. std::string post_compression_body;
  7016. svr_.set_pre_compression_logger(
  7017. [&](const Request & /*req*/, const Response &res) {
  7018. pre_compression_body = res.body;
  7019. });
  7020. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7021. post_compression_body = res.body;
  7022. });
  7023. Headers headers;
  7024. headers.emplace("Accept-Encoding", "br");
  7025. auto res = cli_.Get("/compress", headers);
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. EXPECT_EQ(StatusCode::OK_200, res->status);
  7028. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7029. // Verify pre-compression content is uncompressed
  7030. EXPECT_EQ(test_content, pre_compression_body);
  7031. // Verify post-compression content is compressed
  7032. EXPECT_NE(test_content, post_compression_body);
  7033. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7034. }
  7035. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7036. const std::string test_content =
  7037. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7038. "3456789012345678901234567890";
  7039. std::string pre_compression_body;
  7040. std::string post_compression_body;
  7041. svr_.set_pre_compression_logger(
  7042. [&](const Request & /*req*/, const Response &res) {
  7043. pre_compression_body = res.body;
  7044. });
  7045. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7046. post_compression_body = res.body;
  7047. });
  7048. // Request without compression (use /nocompress endpoint)
  7049. Headers headers;
  7050. auto res = cli_.Get("/nocompress", headers);
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7054. // Pre-compression logger should not be called when no compression is applied
  7055. EXPECT_TRUE(
  7056. pre_compression_body.empty()); // Pre-compression logger not called
  7057. EXPECT_EQ(
  7058. test_content,
  7059. post_compression_body); // Post-compression logger captures final content
  7060. }
  7061. TEST_F(ServerTest, LoggerSeesContentLength) {
  7062. size_t logged_content_length = 0;
  7063. std::string logged_content_length_header;
  7064. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7065. logged_content_length = res.content_length_;
  7066. logged_content_length_header = res.get_header_value("Content-Length");
  7067. });
  7068. auto res = cli_.Get("/nocompress");
  7069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7070. EXPECT_EQ(StatusCode::OK_200, res->status);
  7071. EXPECT_EQ(res->body.size(), logged_content_length);
  7072. EXPECT_EQ(std::to_string(logged_content_length),
  7073. logged_content_length_header);
  7074. }
  7075. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7076. const std::string test_content =
  7077. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7078. "3456789012345678901234567890";
  7079. std::string pre_compression_body;
  7080. bool pre_logger_called = false;
  7081. // Set only pre-compression logger
  7082. svr_.set_pre_compression_logger(
  7083. [&](const Request & /*req*/, const Response &res) {
  7084. pre_compression_body = res.body;
  7085. pre_logger_called = true;
  7086. });
  7087. Headers headers;
  7088. headers.emplace("Accept-Encoding", "gzip");
  7089. auto res = cli_.Get("/compress", headers);
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::OK_200, res->status);
  7092. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7093. // Verify pre-compression logger was called
  7094. EXPECT_TRUE(pre_logger_called);
  7095. EXPECT_EQ(test_content, pre_compression_body);
  7096. }
  7097. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7098. {
  7099. // Test with Expect: 100-continue header - success case
  7100. // Server returns 100 Continue, client sends body, server returns 200 OK
  7101. Request req;
  7102. req.method = "POST";
  7103. req.path = "/post-large";
  7104. req.set_header("Expect", "100-continue");
  7105. req.body = LARGE_DATA;
  7106. Response res;
  7107. auto error = Error::Success;
  7108. cli_.set_keep_alive(true);
  7109. auto ret = cli_.send(req, res, error);
  7110. EXPECT_TRUE(ret);
  7111. EXPECT_EQ(StatusCode::OK_200, res.status);
  7112. EXPECT_EQ(LARGE_DATA, res.body);
  7113. }
  7114. {
  7115. // Test with Expect: 100-continue header - error case
  7116. // Client should not send the body when server returns an error
  7117. Request req;
  7118. req.method = "POST";
  7119. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7120. req.set_header("Expect", "100-continue");
  7121. req.body = LARGE_DATA;
  7122. Response res;
  7123. auto error = Error::Success;
  7124. auto start = std::chrono::high_resolution_clock::now();
  7125. cli_.set_keep_alive(true);
  7126. auto ret = cli_.send(req, res, error);
  7127. auto end = std::chrono::high_resolution_clock::now();
  7128. auto elapsed =
  7129. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7130. .count();
  7131. // With Expect: 100-continue, request completes successfully but with error
  7132. EXPECT_TRUE(ret);
  7133. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7134. EXPECT_EQ("close", res.get_header_value("Connection"));
  7135. EXPECT_FALSE(cli_.is_socket_open());
  7136. EXPECT_LE(elapsed, 2000);
  7137. }
  7138. {
  7139. // Send an extra GET request to ensure error recovery without hanging
  7140. Request req;
  7141. req.method = "GET";
  7142. req.path = "/hi";
  7143. auto start = std::chrono::high_resolution_clock::now();
  7144. auto res = cli_.send(req);
  7145. auto end = std::chrono::high_resolution_clock::now();
  7146. auto elapsed =
  7147. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7148. .count();
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::OK_200, res->status);
  7151. EXPECT_EQ("Hello World!", res->body);
  7152. EXPECT_LE(elapsed, 500);
  7153. }
  7154. }
  7155. TEST(ZstdDecompressor, ChunkedDecompression) {
  7156. std::string data;
  7157. for (size_t i = 0; i < 32 * 1024; ++i) {
  7158. data.push_back(static_cast<char>('a' + i % 26));
  7159. }
  7160. std::string compressed_data;
  7161. {
  7162. httplib::detail::zstd_compressor compressor;
  7163. bool result = compressor.compress(
  7164. data.data(), data.size(),
  7165. /*last=*/true,
  7166. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7167. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7168. compressed_data_size);
  7169. return true;
  7170. });
  7171. ASSERT_TRUE(result);
  7172. }
  7173. std::string decompressed_data;
  7174. {
  7175. httplib::detail::zstd_decompressor decompressor;
  7176. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7177. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7178. size_t chunk_size = 130;
  7179. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7180. chunk_begin += chunk_size) {
  7181. size_t current_chunk_size =
  7182. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7183. bool result = decompressor.decompress(
  7184. compressed_data.data() + chunk_begin, current_chunk_size,
  7185. [&](const char *decompressed_data_chunk,
  7186. size_t decompressed_data_chunk_size) {
  7187. decompressed_data.insert(decompressed_data.size(),
  7188. decompressed_data_chunk,
  7189. decompressed_data_chunk_size);
  7190. return true;
  7191. });
  7192. ASSERT_TRUE(result);
  7193. }
  7194. }
  7195. ASSERT_EQ(data, decompressed_data);
  7196. }
  7197. TEST(ZstdDecompressor, Decompress) {
  7198. std::string original_text = "Compressed with ZSTD";
  7199. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7200. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7201. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7202. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7203. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7204. std::string decompressed_data;
  7205. {
  7206. httplib::detail::zstd_decompressor decompressor;
  7207. bool result = decompressor.decompress(
  7208. compressed_data.data(), compressed_data.size(),
  7209. [&](const char *decompressed_data_chunk,
  7210. size_t decompressed_data_chunk_size) {
  7211. decompressed_data.insert(decompressed_data.size(),
  7212. decompressed_data_chunk,
  7213. decompressed_data_chunk_size);
  7214. return true;
  7215. });
  7216. ASSERT_TRUE(result);
  7217. }
  7218. ASSERT_EQ(original_text, decompressed_data);
  7219. }
  7220. #endif
  7221. // Sends a raw request to a server listening at HOST:PORT.
  7222. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7223. std::string *resp = nullptr) {
  7224. auto error = Error::Success;
  7225. auto client_sock = detail::create_client_socket(
  7226. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  7227. /*connection_timeout_sec=*/5, 0,
  7228. /*read_timeout_sec=*/5, 0,
  7229. /*write_timeout_sec=*/5, 0, std::string(), error);
  7230. if (client_sock == INVALID_SOCKET) { return false; }
  7231. auto ret = detail::process_client_socket(
  7232. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7233. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7234. if (req.size() !=
  7235. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7236. return false;
  7237. }
  7238. char buf[512];
  7239. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7240. while (line_reader.getline()) {
  7241. if (resp) { *resp += line_reader.ptr(); }
  7242. }
  7243. return true;
  7244. });
  7245. detail::close_socket(client_sock);
  7246. return ret;
  7247. }
  7248. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7249. Server svr;
  7250. std::string header_value;
  7251. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7252. header_value = req.get_header_value("foo");
  7253. res.set_content("ok", "text/plain");
  7254. });
  7255. thread t = thread([&] { svr.listen(HOST, PORT); });
  7256. auto se = detail::scope_exit([&] {
  7257. svr.stop();
  7258. t.join();
  7259. ASSERT_FALSE(svr.is_running());
  7260. });
  7261. svr.wait_until_ready();
  7262. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7263. // like characters are not treated the same - use vertical tab and escape.
  7264. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7265. "foo: \t \v bar \x1B\t \r\n"
  7266. "Connection: close\r\n"
  7267. "\r\n";
  7268. std::string res;
  7269. ASSERT_TRUE(send_request(5, req, &res));
  7270. EXPECT_EQ(header_value, "");
  7271. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7272. }
  7273. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7274. Server svr;
  7275. std::string received;
  7276. svr.Get("/order", [&](const Request &req, Response &res) {
  7277. received = entries_to_string(req.headers);
  7278. res.set_content("ok", "text/plain");
  7279. });
  7280. thread t = thread([&] { svr.listen(HOST, PORT); });
  7281. auto se = detail::scope_exit([&] {
  7282. svr.stop();
  7283. t.join();
  7284. ASSERT_FALSE(svr.is_running());
  7285. });
  7286. svr.wait_until_ready();
  7287. const std::string req = "GET /order HTTP/1.1\r\n"
  7288. "X-First: 1\r\n"
  7289. "X-Dup: a\r\n"
  7290. "X-Second: 2\r\n"
  7291. "X-Dup: b\r\n"
  7292. "Connection: close\r\n"
  7293. "\r\n";
  7294. std::string res;
  7295. ASSERT_TRUE(send_request(5, req, &res));
  7296. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7297. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7298. }
  7299. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7300. Server svr;
  7301. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7302. res.set_header("Set-Cookie", "first=1");
  7303. res.set_header("X-Between", "y");
  7304. res.set_header("Set-Cookie", "second=2");
  7305. res.set_content("ok", "text/plain");
  7306. });
  7307. thread t = thread([&] { svr.listen(HOST, PORT); });
  7308. auto se = detail::scope_exit([&] {
  7309. svr.stop();
  7310. t.join();
  7311. ASSERT_FALSE(svr.is_running());
  7312. });
  7313. svr.wait_until_ready();
  7314. Client cli(HOST, PORT);
  7315. auto res = cli.Get("/cookies");
  7316. ASSERT_TRUE(res);
  7317. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7318. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7319. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7320. }
  7321. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7322. Server svr;
  7323. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7324. auto i = new int(0);
  7325. res.set_header("Trailer", "X-Safe, X-Reflected");
  7326. res.set_chunked_content_provider(
  7327. "text/plain",
  7328. [i](size_t /*offset*/, DataSink &sink) {
  7329. if (*i == 0) {
  7330. sink.os << "body";
  7331. } else {
  7332. Headers trailer;
  7333. // A valid trailer that must survive.
  7334. trailer.emplace("X-Safe", "safe");
  7335. // Attacker-controlled value carrying CR/LF (response splitting).
  7336. trailer.emplace("X-Reflected",
  7337. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7338. // Attacker-controlled name carrying CR/LF.
  7339. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7340. sink.done_with_trailer(trailer);
  7341. }
  7342. (*i)++;
  7343. return true;
  7344. },
  7345. [i](bool /*success*/) { delete i; });
  7346. });
  7347. thread t = thread([&] { svr.listen(HOST, PORT); });
  7348. auto se = detail::scope_exit([&] {
  7349. svr.stop();
  7350. t.join();
  7351. ASSERT_FALSE(svr.is_running());
  7352. });
  7353. svr.wait_until_ready();
  7354. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7355. "Host: " + HOST +
  7356. "\r\n"
  7357. "Connection: close\r\n"
  7358. "\r\n";
  7359. std::string res;
  7360. ASSERT_TRUE(send_request(5, req, &res));
  7361. // The injected fields must not appear anywhere in the raw response.
  7362. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7363. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7364. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7365. // Invalid trailers are dropped entirely, matching set_header().
  7366. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7367. // The valid trailer still passes through.
  7368. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7369. }
  7370. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7371. Server svr;
  7372. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7373. // res.headers is a public field an application can populate directly,
  7374. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7375. // A valid header that must survive.
  7376. res.headers.emplace("X-Safe", "safe");
  7377. // Attacker-controlled value carrying CR/LF (response splitting).
  7378. res.headers.emplace("X-Reflected",
  7379. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7380. // Attacker-controlled name carrying CR/LF.
  7381. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7382. res.set_content("body", "text/plain");
  7383. });
  7384. thread t = thread([&] { svr.listen(HOST, PORT); });
  7385. auto se = detail::scope_exit([&] {
  7386. svr.stop();
  7387. t.join();
  7388. ASSERT_FALSE(svr.is_running());
  7389. });
  7390. svr.wait_until_ready();
  7391. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7392. "Host: " + HOST +
  7393. "\r\n"
  7394. "Connection: close\r\n"
  7395. "\r\n";
  7396. std::string res;
  7397. ASSERT_TRUE(send_request(5, req, &res));
  7398. // The injected fields must not appear anywhere in the raw response.
  7399. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7400. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7401. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7402. // Invalid headers are dropped entirely, matching set_header().
  7403. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7404. // The valid header still passes through.
  7405. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7406. }
  7407. // Forward declaration: in split builds split.py strips `inline` and moves the
  7408. // definition into httplib.cc, so detail::write_request_line is not visible from
  7409. // the public httplib.h. Re-declaring it here lets the tests link against the
  7410. // symbol in both header-only and split builds.
  7411. namespace httplib {
  7412. namespace detail {
  7413. ssize_t write_request_line(Stream &strm, const std::string &method,
  7414. const std::string &path);
  7415. } // namespace detail
  7416. } // namespace httplib
  7417. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7418. // A well-formed target is written verbatim.
  7419. {
  7420. detail::BufferStream strm;
  7421. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7422. EXPECT_GT(n, 0);
  7423. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7424. }
  7425. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7426. // otherwise it splits the request line and injects a header or a whole
  7427. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7428. // when path encoding is disabled.
  7429. const std::string evil_targets[] = {
  7430. "/a\r\nInjected: pwned",
  7431. "/a\rInjected",
  7432. "/a\nInjected",
  7433. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7434. };
  7435. for (const auto &evil : evil_targets) {
  7436. detail::BufferStream strm;
  7437. auto n = detail::write_request_line(strm, "GET", evil);
  7438. EXPECT_LT(n, 0);
  7439. EXPECT_TRUE(strm.get_buffer().empty());
  7440. }
  7441. }
  7442. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7443. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7444. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7445. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7446. // client must fail cleanly with Error::Write instead of putting a
  7447. // request-line-less, header-injecting request on the wire.
  7448. Server svr;
  7449. svr.Get("/a", [](const Request &, Response &res) {
  7450. res.set_content("ok", "text/plain");
  7451. });
  7452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7453. auto se = detail::scope_exit([&] {
  7454. svr.stop();
  7455. thread.join();
  7456. ASSERT_FALSE(svr.is_running());
  7457. });
  7458. svr.wait_until_ready();
  7459. {
  7460. Client cli(HOST, PORT);
  7461. cli.set_path_encode(false);
  7462. // The request is rejected before anything is written, so the connection
  7463. // stays silent and the subsequent response read would otherwise block for
  7464. // the full default read timeout. Shorten it -- the assertion is on the
  7465. // error, not the timeout.
  7466. cli.set_read_timeout(1, 0);
  7467. auto res = cli.Get("/a\r\nInjected: pwned");
  7468. EXPECT_FALSE(res);
  7469. EXPECT_EQ(Error::Write, res.error());
  7470. }
  7471. }
  7472. // Sends a raw request and verifies that there isn't a crash or exception.
  7473. static void test_raw_request(const std::string &req,
  7474. std::string *out = nullptr) {
  7475. Server svr;
  7476. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7477. res.set_content("ok", "text/plain");
  7478. });
  7479. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7480. res.set_content("ok", "text/plain");
  7481. });
  7482. svr.Get("/header_field_value_check",
  7483. [&](const Request & /*req*/, Response &res) {
  7484. res.set_content("ok", "text/plain");
  7485. });
  7486. // Server read timeout must be longer than the client read timeout for the
  7487. // bug to reproduce, probably to force the server to process a request
  7488. // without a trailing blank line.
  7489. const time_t client_read_timeout_sec = 1;
  7490. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7491. bool listen_thread_ok = false;
  7492. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7493. auto se = detail::scope_exit([&] {
  7494. svr.stop();
  7495. t.join();
  7496. ASSERT_FALSE(svr.is_running());
  7497. EXPECT_TRUE(listen_thread_ok);
  7498. });
  7499. svr.wait_until_ready();
  7500. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7501. }
  7502. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7503. // A certain header line causes an exception if the header property is parsed
  7504. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7505. test_raw_request(
  7506. "GET /hi HTTP/1.1\r\n"
  7507. " : "
  7508. " "
  7509. " ");
  7510. }
  7511. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7512. // A certain header line causes an exception if the header property *name* is
  7513. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7514. // greedy matcher and requires backtracking when there are a lot of ":"
  7515. // characters.
  7516. // This occurs with libc++ but not libstdc++.
  7517. test_raw_request(
  7518. "GET /hi HTTP/1.1\r\n"
  7519. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7520. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7521. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7522. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7523. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7524. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7525. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7526. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7527. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7528. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7529. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7530. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7531. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7532. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7533. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7534. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7535. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7536. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7537. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7538. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7539. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7540. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7541. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7542. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7543. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7544. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7545. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7546. "&&&%%%");
  7547. }
  7548. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7549. // Make sure this doesn't crash the server.
  7550. // In a previous version of the header line regex, the "\r" rendered the line
  7551. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7552. // a new position where the leading white space ended and the field value
  7553. // began.
  7554. // The crash occurs with libc++ but not libstdc++.
  7555. test_raw_request("GET /hi HTTP/1.1\r\n"
  7556. "a:" +
  7557. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7558. "\r\n"
  7559. "\r\n");
  7560. }
  7561. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7562. std::string out;
  7563. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7564. "Content-Type: text/plain\r\n"
  7565. "Transfer-Encoding: chunked\r\n"
  7566. "\r\n"
  7567. "nothex\r\n",
  7568. &out);
  7569. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7570. }
  7571. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7572. std::string out;
  7573. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7574. "Content-Type: text/plain\r\n"
  7575. "Transfer-Encoding: chunked\r\n"
  7576. "\r\n"
  7577. "3\r\n"
  7578. "xyz\r\n"
  7579. "NaN\r\n",
  7580. &out);
  7581. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7582. }
  7583. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7584. std::string out;
  7585. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7586. "Content-Type: text/plain\r\n"
  7587. "Transfer-Encoding: chunked\r\n"
  7588. "\r\n"
  7589. // Length is too large for 64 bits.
  7590. "1ffffffffffffffff\r\n"
  7591. "xyz\r\n",
  7592. &out);
  7593. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7594. }
  7595. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7596. test_raw_request("GET /hi HTTP/1.1\r\n"
  7597. "Content-Type: text/plain\r\n\r");
  7598. }
  7599. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7600. std::string out;
  7601. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7602. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7603. }
  7604. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7605. Server svr;
  7606. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7607. EXPECT_TRUE(!req.remote_addr.empty());
  7608. });
  7609. thread t = thread([&] { svr.listen(HOST, PORT); });
  7610. auto se = detail::scope_exit([&] {
  7611. svr.stop();
  7612. t.join();
  7613. ASSERT_FALSE(svr.is_running());
  7614. });
  7615. svr.wait_until_ready();
  7616. // Send an invalid request line to trigger Bad Request
  7617. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7618. std::string out;
  7619. ASSERT_TRUE(send_request(5, bad_req, &out));
  7620. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7621. }
  7622. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7623. std::string out;
  7624. std::string request(
  7625. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7626. test_raw_request(request, &out);
  7627. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7628. }
  7629. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7630. std::string out;
  7631. std::string request(
  7632. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7633. test_raw_request(request, &out);
  7634. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7635. }
  7636. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7637. std::string out;
  7638. std::string request(
  7639. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7640. test_raw_request(request, &out);
  7641. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7642. }
  7643. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7644. std::string out;
  7645. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7646. "Test: \r\n\r\n",
  7647. &out);
  7648. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7649. }
  7650. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7651. Server svr;
  7652. std::string x_custom;
  7653. std::string cookie;
  7654. std::string xff;
  7655. std::string x_unicode;
  7656. std::string x_iis;
  7657. svr.Get("/check", [&](const Request &req, Response &res) {
  7658. x_custom = req.get_header_value("X-Custom");
  7659. cookie = req.get_header_value("Cookie");
  7660. xff = req.get_header_value("X-Forwarded-For");
  7661. x_unicode = req.get_header_value("X-Unicode");
  7662. x_iis = req.get_header_value("X-IIS");
  7663. res.set_content("ok", "text/plain");
  7664. });
  7665. thread t = thread([&] { svr.listen(HOST, PORT); });
  7666. auto se = detail::scope_exit([&] {
  7667. svr.stop();
  7668. t.join();
  7669. ASSERT_FALSE(svr.is_running());
  7670. });
  7671. svr.wait_until_ready();
  7672. const std::string req = "GET /check HTTP/1.1\r\n"
  7673. "Host: localhost\r\n"
  7674. "X-Custom: a%0D%0AInjected: b\r\n"
  7675. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7676. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7677. "X-Unicode: %E3%81%82\r\n"
  7678. "X-IIS: %u00E9\r\n"
  7679. "Connection: close\r\n"
  7680. "\r\n";
  7681. std::string res;
  7682. ASSERT_TRUE(send_request(5, req, &res));
  7683. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7684. // Every value must be returned verbatim (wire form), with no decoding.
  7685. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7686. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7687. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7688. EXPECT_EQ("%E3%81%82", x_unicode);
  7689. EXPECT_EQ("%u00E9", x_iis);
  7690. }
  7691. // Applications that previously relied on automatic percent-decoding can
  7692. // reproduce the old behavior by explicitly calling decode_path_component()
  7693. // or, for RFC 3986 conformance, decode_uri_component().
  7694. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7695. Server svr;
  7696. std::string decoded;
  7697. svr.Get("/check", [&](const Request &req, Response &res) {
  7698. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7699. res.set_content("ok", "text/plain");
  7700. });
  7701. thread t = thread([&] { svr.listen(HOST, PORT); });
  7702. auto se = detail::scope_exit([&] {
  7703. svr.stop();
  7704. t.join();
  7705. ASSERT_FALSE(svr.is_running());
  7706. });
  7707. svr.wait_until_ready();
  7708. const std::string req = "GET /check HTTP/1.1\r\n"
  7709. "Host: localhost\r\n"
  7710. "X-Custom: hello%20world\r\n"
  7711. "Connection: close\r\n"
  7712. "\r\n";
  7713. std::string res;
  7714. ASSERT_TRUE(send_request(5, req, &res));
  7715. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7716. EXPECT_EQ("hello world", decoded);
  7717. }
  7718. // Regression test for #2033. Browsers send Referer values that include
  7719. // percent-encoded characters such as %0A inside the URL. Decoding the
  7720. // header value would either trip the post-decode CR/LF/NUL guard (the
  7721. // original bug, returning 400) or, after that guard was relaxed, silently
  7722. // store a literal LF — both unacceptable. The wire form must round-trip.
  7723. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7724. Server svr;
  7725. std::string referer;
  7726. svr.Get("/check", [&](const Request &req, Response &res) {
  7727. referer = req.get_header_value("Referer");
  7728. res.set_content("ok", "text/plain");
  7729. });
  7730. thread t = thread([&] { svr.listen(HOST, PORT); });
  7731. auto se = detail::scope_exit([&] {
  7732. svr.stop();
  7733. t.join();
  7734. ASSERT_FALSE(svr.is_running());
  7735. });
  7736. svr.wait_until_ready();
  7737. const std::string req = "GET /check HTTP/1.1\r\n"
  7738. "Host: localhost\r\n"
  7739. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7740. "Connection: close\r\n"
  7741. "\r\n";
  7742. std::string res;
  7743. ASSERT_TRUE(send_request(5, req, &res));
  7744. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7745. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7746. }
  7747. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7748. Server svr;
  7749. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7750. res.set_header("Cache-Control", "no-cache");
  7751. res.set_chunked_content_provider(
  7752. "text/event-stream", [](size_t offset, DataSink &sink) {
  7753. std::string s = "data:";
  7754. s += std::to_string(offset);
  7755. s += "\n\n";
  7756. auto ret = sink.write(s.data(), s.size());
  7757. EXPECT_TRUE(ret);
  7758. std::this_thread::sleep_for(std::chrono::seconds(1));
  7759. return true;
  7760. });
  7761. });
  7762. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7763. svr.wait_until_ready();
  7764. Client client(HOST, PORT);
  7765. const Headers headers = {{"Accept", "text/event-stream"}};
  7766. auto get_thread = std::thread([&client, &headers]() {
  7767. auto res = client.Get(
  7768. "/events", headers,
  7769. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7770. });
  7771. auto se = detail::scope_exit([&] {
  7772. svr.stop();
  7773. get_thread.join();
  7774. listen_thread.join();
  7775. ASSERT_FALSE(svr.is_running());
  7776. });
  7777. // Give GET time to get a few messages.
  7778. std::this_thread::sleep_for(std::chrono::seconds(2));
  7779. }
  7780. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7781. httplib::Server svr;
  7782. svr.Post("/hi",
  7783. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7784. res.status = StatusCode::OK_200;
  7785. });
  7786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7787. svr.wait_until_ready();
  7788. Client cli(HOST, PORT);
  7789. auto res = cli.Post("/hi", "data", "text/plain");
  7790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7791. EXPECT_EQ(StatusCode::OK_200, res->status);
  7792. svr.stop();
  7793. thread.join();
  7794. ASSERT_FALSE(svr.is_running());
  7795. res = cli.Post("/hi", "data", "text/plain");
  7796. ASSERT_FALSE(res);
  7797. }
  7798. TEST(ServerStopTest, ListenFailure) {
  7799. Server svr;
  7800. auto t = thread([&]() {
  7801. auto ret = svr.listen("????", PORT);
  7802. EXPECT_FALSE(ret);
  7803. });
  7804. svr.wait_until_ready();
  7805. svr.stop();
  7806. t.join();
  7807. }
  7808. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7809. TEST(ServerStopTest, Decommision) {
  7810. Server svr;
  7811. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7812. for (int i = 0; i < 4; i++) {
  7813. auto is_even = !(i % 2);
  7814. std::thread t{[&] {
  7815. try {
  7816. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7817. if (is_even) {
  7818. throw std::runtime_error("Some thing that happens to go wrong.");
  7819. }
  7820. svr.listen(HOST, PORT);
  7821. } catch (...) { svr.decommission(); }
  7822. }};
  7823. svr.wait_until_ready();
  7824. // Server is up
  7825. {
  7826. Client cli(HOST, PORT);
  7827. auto res = cli.Get("/hi");
  7828. if (is_even) {
  7829. EXPECT_FALSE(res);
  7830. } else {
  7831. EXPECT_TRUE(res);
  7832. EXPECT_EQ("hi...", res->body);
  7833. }
  7834. }
  7835. svr.stop();
  7836. t.join();
  7837. // Server is down...
  7838. {
  7839. Client cli(HOST, PORT);
  7840. auto res = cli.Get("/hi");
  7841. EXPECT_FALSE(res);
  7842. }
  7843. }
  7844. }
  7845. #endif
  7846. // Helper function for string body upload progress tests
  7847. template <typename SetupHandler, typename ClientCall>
  7848. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7849. ClientCall &&client_call,
  7850. const string &body) {
  7851. Server svr;
  7852. setup_handler(svr);
  7853. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7854. auto se = detail::scope_exit([&] {
  7855. svr.stop();
  7856. t.join();
  7857. });
  7858. svr.wait_until_ready();
  7859. Client cli(HOST, PORT);
  7860. vector<uint64_t> progress_values;
  7861. bool progress_called = false;
  7862. auto res =
  7863. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7864. progress_values.push_back(current);
  7865. progress_called = true;
  7866. return true;
  7867. });
  7868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7869. EXPECT_EQ(200, res->status);
  7870. EXPECT_TRUE(progress_called);
  7871. }
  7872. TEST(UploadProgressTest, PostStringBodyBasic) {
  7873. TestStringBodyUploadProgress(
  7874. [](Server &svr) {
  7875. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7876. res.set_content("received", "text/plain");
  7877. });
  7878. },
  7879. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7880. return cli.Post("/test", body, "text/plain", progress_callback);
  7881. },
  7882. "test data for upload progress");
  7883. }
  7884. TEST(UploadProgressTest, PutStringBodyBasic) {
  7885. TestStringBodyUploadProgress(
  7886. [](Server &svr) {
  7887. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7888. res.set_content("put received", "text/plain");
  7889. });
  7890. },
  7891. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7892. return cli.Put("/test", body, "text/plain", progress_callback);
  7893. },
  7894. "put test data for upload progress");
  7895. }
  7896. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7897. TestStringBodyUploadProgress(
  7898. [](Server &svr) {
  7899. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7900. res.set_content("patch received", "text/plain");
  7901. });
  7902. },
  7903. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7904. return cli.Patch("/test", body, "text/plain", progress_callback);
  7905. },
  7906. "patch test data for upload progress");
  7907. }
  7908. // Helper function for content provider upload progress tests
  7909. template <typename SetupHandler, typename ClientCall>
  7910. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7911. ClientCall &&client_call) {
  7912. Server svr;
  7913. setup_handler(svr);
  7914. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7915. auto se = detail::scope_exit([&] {
  7916. svr.stop();
  7917. t.join();
  7918. });
  7919. svr.wait_until_ready();
  7920. Client cli(HOST, PORT);
  7921. vector<uint64_t> progress_values;
  7922. auto res =
  7923. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7924. progress_values.push_back(current);
  7925. return true;
  7926. });
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(200, res->status);
  7929. EXPECT_FALSE(progress_values.empty());
  7930. }
  7931. TEST(UploadProgressTest, PostContentProviderProgress) {
  7932. TestContentProviderUploadProgress(
  7933. [](Server &svr) {
  7934. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7935. res.set_content("provider received", "text/plain");
  7936. });
  7937. },
  7938. [](Client &cli, UploadProgress progress_callback) {
  7939. return cli.Post(
  7940. "/test", 10,
  7941. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7942. sink.os << "test data";
  7943. return true;
  7944. },
  7945. "text/plain", progress_callback);
  7946. });
  7947. }
  7948. // Helper function for multipart upload progress tests
  7949. template <typename SetupHandler, typename ClientCall>
  7950. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7951. ClientCall &&client_call,
  7952. const string &endpoint) {
  7953. Server svr;
  7954. setup_handler(svr);
  7955. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7956. auto se = detail::scope_exit([&] {
  7957. svr.stop();
  7958. t.join();
  7959. });
  7960. svr.wait_until_ready();
  7961. Client cli(HOST, PORT);
  7962. vector<uint64_t> progress_values;
  7963. UploadFormDataItems items = {
  7964. {"field1", "value1", "", ""},
  7965. {"field2", "longer value for progress tracking test", "", ""},
  7966. {"file1", "file content data for upload progress", "test.txt",
  7967. "text/plain"}};
  7968. auto res = client_call(cli, endpoint, items,
  7969. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7970. progress_values.push_back(current);
  7971. return true;
  7972. });
  7973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7974. EXPECT_EQ(200, res->status);
  7975. EXPECT_FALSE(progress_values.empty());
  7976. }
  7977. TEST(UploadProgressTest, PostMultipartProgress) {
  7978. TestMultipartUploadProgress(
  7979. [](Server &svr) {
  7980. svr.Post("/multipart", [](const Request &req, Response &res) {
  7981. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7982. res.set_content("multipart received", "text/plain");
  7983. });
  7984. },
  7985. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7986. UploadProgress progress_callback) {
  7987. return cli.Post(endpoint, items, progress_callback);
  7988. },
  7989. "/multipart");
  7990. }
  7991. // Helper function for basic download progress tests
  7992. template <typename SetupHandler, typename ClientCall>
  7993. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7994. ClientCall &&client_call, const string &endpoint,
  7995. size_t expected_content_size) {
  7996. Server svr;
  7997. setup_handler(svr);
  7998. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7999. auto se = detail::scope_exit([&] {
  8000. svr.stop();
  8001. t.join();
  8002. });
  8003. svr.wait_until_ready();
  8004. Client cli(HOST, PORT);
  8005. vector<uint64_t> progress_values;
  8006. auto res = client_call(cli, endpoint,
  8007. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8008. progress_values.push_back(current);
  8009. return true;
  8010. });
  8011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8012. EXPECT_EQ(200, res->status);
  8013. EXPECT_FALSE(progress_values.empty());
  8014. EXPECT_EQ(expected_content_size, res->body.size());
  8015. }
  8016. TEST(DownloadProgressTest, GetBasic) {
  8017. TestBasicDownloadProgress(
  8018. [](Server &svr) {
  8019. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8020. string content(1000, 'D');
  8021. res.set_content(content, "text/plain");
  8022. });
  8023. },
  8024. [](Client &cli, const string &endpoint,
  8025. DownloadProgress progress_callback) {
  8026. return cli.Get(endpoint, progress_callback);
  8027. },
  8028. "/download", 1000u);
  8029. }
  8030. // Helper function for content receiver download progress tests
  8031. template <typename SetupHandler, typename ClientCall>
  8032. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8033. ClientCall &&client_call,
  8034. const string &endpoint,
  8035. size_t expected_content_size) {
  8036. Server svr;
  8037. setup_handler(svr);
  8038. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8039. auto se = detail::scope_exit([&] {
  8040. svr.stop();
  8041. t.join();
  8042. });
  8043. svr.wait_until_ready();
  8044. Client cli(HOST, PORT);
  8045. vector<uint64_t> progress_values;
  8046. string received_body;
  8047. auto res = client_call(
  8048. cli, endpoint,
  8049. [&](const char *data, size_t data_length) -> bool {
  8050. received_body.append(data, data_length);
  8051. return true;
  8052. },
  8053. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8054. progress_values.push_back(current);
  8055. return true;
  8056. });
  8057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8058. EXPECT_EQ(200, res->status);
  8059. EXPECT_FALSE(progress_values.empty());
  8060. EXPECT_EQ(expected_content_size, received_body.size());
  8061. EXPECT_TRUE(res->body.empty());
  8062. }
  8063. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8064. TestContentReceiverDownloadProgress(
  8065. [](Server &svr) {
  8066. svr.Get("/download-receiver",
  8067. [](const Request & /*req*/, Response &res) {
  8068. string content(2000, 'R');
  8069. res.set_content(content, "text/plain");
  8070. });
  8071. },
  8072. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8073. DownloadProgress progress_callback) {
  8074. return cli.Get(endpoint, content_receiver, progress_callback);
  8075. },
  8076. "/download-receiver", 2000u);
  8077. }
  8078. TEST(StreamingTest, NoContentLengthStreaming) {
  8079. Server svr;
  8080. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8081. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8082. if (offset < 6) {
  8083. sink.os << (offset < 3 ? "a" : "b");
  8084. } else {
  8085. sink.done();
  8086. }
  8087. return true;
  8088. });
  8089. });
  8090. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8091. auto listen_se = detail::scope_exit([&] {
  8092. svr.stop();
  8093. listen_thread.join();
  8094. ASSERT_FALSE(svr.is_running());
  8095. });
  8096. svr.wait_until_ready();
  8097. Client client(HOST, PORT);
  8098. auto get_thread = std::thread([&client]() {
  8099. std::string s;
  8100. auto res =
  8101. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8102. s += std::string(data, len);
  8103. return true;
  8104. });
  8105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8106. EXPECT_EQ(StatusCode::OK_200, res->status);
  8107. EXPECT_EQ("aaabbb", s);
  8108. });
  8109. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8110. // Give GET time to get a few messages.
  8111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8112. }
  8113. TEST(MountTest, Unmount) {
  8114. Server svr;
  8115. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8116. auto se = detail::scope_exit([&] {
  8117. svr.stop();
  8118. listen_thread.join();
  8119. ASSERT_FALSE(svr.is_running());
  8120. });
  8121. svr.wait_until_ready();
  8122. Client cli("localhost", PORT);
  8123. svr.set_mount_point("/mount2", "./www2");
  8124. auto res = cli.Get("/");
  8125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8126. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8127. res = cli.Get("/mount2/dir/test.html");
  8128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8129. EXPECT_EQ(StatusCode::OK_200, res->status);
  8130. svr.set_mount_point("/", "./www");
  8131. res = cli.Get("/dir/");
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. svr.remove_mount_point("/");
  8135. res = cli.Get("/dir/");
  8136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8137. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8138. svr.remove_mount_point("/mount2");
  8139. res = cli.Get("/mount2/dir/test.html");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8142. }
  8143. TEST(MountTest, Redicect) {
  8144. Server svr;
  8145. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8146. auto se = detail::scope_exit([&] {
  8147. svr.stop();
  8148. listen_thread.join();
  8149. ASSERT_FALSE(svr.is_running());
  8150. });
  8151. svr.set_mount_point("/", "./www");
  8152. svr.wait_until_ready();
  8153. Client cli("localhost", PORT);
  8154. auto res = cli.Get("/dir/");
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. EXPECT_EQ(StatusCode::OK_200, res->status);
  8157. res = cli.Get("/dir");
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8160. res = cli.Get("/file");
  8161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8162. EXPECT_EQ(StatusCode::OK_200, res->status);
  8163. res = cli.Get("/file/");
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8166. cli.set_follow_location(true);
  8167. res = cli.Get("/dir");
  8168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. TEST(MountTest, MultibytesPathName) {
  8172. Server svr;
  8173. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8174. auto se = detail::scope_exit([&] {
  8175. svr.stop();
  8176. listen_thread.join();
  8177. ASSERT_FALSE(svr.is_running());
  8178. });
  8179. svr.set_mount_point("/", "./www");
  8180. svr.wait_until_ready();
  8181. Client cli("localhost", PORT);
  8182. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8184. EXPECT_EQ(StatusCode::OK_200, res->status);
  8185. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8186. }
  8187. #ifdef _WIN32
  8188. // Issue #2435: mmap::open() must succeed even when another handle holds
  8189. // the file open for writing (e.g. an active log file).
  8190. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8191. const char *path = "mmap_concurrent_writer_test.txt";
  8192. const char *content = "hello";
  8193. {
  8194. std::ofstream f(path, std::ios::binary);
  8195. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8196. }
  8197. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8198. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8199. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8200. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8201. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8202. detail::mmap m(path);
  8203. ASSERT_TRUE(m.is_open());
  8204. EXPECT_EQ(strlen(content), m.size());
  8205. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8206. }
  8207. #endif
  8208. #ifndef _WIN32
  8209. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8210. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8211. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8212. TEST(MmapTest, FailedMappingIsNotOpen) {
  8213. const char *path = "./mmap_failed_mapping_test_dir";
  8214. ASSERT_EQ(0, ::mkdir(path, 0755));
  8215. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8216. detail::mmap m(path);
  8217. EXPECT_FALSE(m.is_open());
  8218. EXPECT_EQ(0U, m.size());
  8219. EXPECT_NE(static_cast<const void *>(m.data()),
  8220. static_cast<const void *>(MAP_FAILED));
  8221. }
  8222. #endif
  8223. TEST(KeepAliveTest, ReadTimeout) {
  8224. Server svr;
  8225. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8226. std::this_thread::sleep_for(std::chrono::seconds(2));
  8227. res.set_content("a", "text/plain");
  8228. });
  8229. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8230. res.set_content("b", "text/plain");
  8231. });
  8232. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8233. auto se = detail::scope_exit([&] {
  8234. svr.stop();
  8235. listen_thread.join();
  8236. ASSERT_FALSE(svr.is_running());
  8237. });
  8238. svr.wait_until_ready();
  8239. Client cli("localhost", PORT);
  8240. cli.set_keep_alive(true);
  8241. cli.set_read_timeout(std::chrono::seconds(1));
  8242. auto resa = cli.Get("/a");
  8243. ASSERT_FALSE(resa);
  8244. EXPECT_EQ(Error::Read, resa.error());
  8245. auto resb = cli.Get("/b");
  8246. ASSERT_TRUE(resb);
  8247. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8248. EXPECT_EQ("b", resb->body);
  8249. }
  8250. TEST(KeepAliveTest, MaxCount) {
  8251. size_t keep_alive_max_count = 3;
  8252. Server svr;
  8253. svr.set_keep_alive_max_count(keep_alive_max_count);
  8254. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8255. res.set_content("Hello World!", "text/plain");
  8256. });
  8257. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8258. auto se = detail::scope_exit([&] {
  8259. svr.stop();
  8260. listen_thread.join();
  8261. ASSERT_FALSE(svr.is_running());
  8262. });
  8263. svr.wait_until_ready();
  8264. Client cli(HOST, PORT);
  8265. cli.set_keep_alive(true);
  8266. for (size_t i = 0; i < 5; i++) {
  8267. auto result = cli.Get("/hi");
  8268. ASSERT_TRUE(result);
  8269. EXPECT_EQ(StatusCode::OK_200, result->status);
  8270. if (i == keep_alive_max_count - 1) {
  8271. EXPECT_EQ("close", result->get_header_value("Connection"));
  8272. } else {
  8273. EXPECT_FALSE(result->has_header("Connection"));
  8274. }
  8275. }
  8276. }
  8277. TEST(KeepAliveTest, Issue1041) {
  8278. Server svr;
  8279. svr.set_keep_alive_timeout(3);
  8280. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8281. res.set_content("Hello World!", "text/plain");
  8282. });
  8283. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8284. auto se = detail::scope_exit([&] {
  8285. svr.stop();
  8286. listen_thread.join();
  8287. ASSERT_FALSE(svr.is_running());
  8288. });
  8289. svr.wait_until_ready();
  8290. Client cli(HOST, PORT);
  8291. cli.set_keep_alive(true);
  8292. auto result = cli.Get("/hi");
  8293. ASSERT_TRUE(result);
  8294. EXPECT_EQ(StatusCode::OK_200, result->status);
  8295. std::this_thread::sleep_for(std::chrono::seconds(5));
  8296. result = cli.Get("/hi");
  8297. ASSERT_TRUE(result);
  8298. EXPECT_EQ(StatusCode::OK_200, result->status);
  8299. }
  8300. TEST(KeepAliveTest, Issue1959) {
  8301. Server svr;
  8302. svr.set_keep_alive_timeout(5);
  8303. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8304. res.set_content("a", "text/plain");
  8305. });
  8306. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8307. auto se = detail::scope_exit([&] {
  8308. if (!svr.is_running()) return;
  8309. svr.stop();
  8310. listen_thread.join();
  8311. ASSERT_FALSE(svr.is_running());
  8312. });
  8313. svr.wait_until_ready();
  8314. Client cli("localhost", PORT);
  8315. cli.set_keep_alive(true);
  8316. using namespace std::chrono;
  8317. auto start = steady_clock::now();
  8318. cli.Get("/a");
  8319. svr.stop();
  8320. listen_thread.join();
  8321. auto end = steady_clock::now();
  8322. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8323. EXPECT_LT(elapsed, 5000);
  8324. }
  8325. #ifdef CPPHTTPLIB_SSL_ENABLED
  8326. TEST(KeepAliveTest, SSLClientReconnection) {
  8327. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8328. ASSERT_TRUE(svr.is_valid());
  8329. svr.set_keep_alive_timeout(1);
  8330. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8331. res.set_content("Hello World!", "text/plain");
  8332. });
  8333. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8334. auto se = detail::scope_exit([&] {
  8335. svr.stop();
  8336. listen_thread.join();
  8337. ASSERT_FALSE(svr.is_running());
  8338. });
  8339. svr.wait_until_ready();
  8340. SSLClient cli(HOST, PORT);
  8341. cli.enable_server_certificate_verification(false);
  8342. cli.set_keep_alive(true);
  8343. auto result = cli.Get("/hi");
  8344. ASSERT_TRUE(result);
  8345. EXPECT_EQ(StatusCode::OK_200, result->status);
  8346. result = cli.Get("/hi");
  8347. ASSERT_TRUE(result);
  8348. EXPECT_EQ(StatusCode::OK_200, result->status);
  8349. std::this_thread::sleep_for(std::chrono::seconds(2));
  8350. // Recoonect
  8351. result = cli.Get("/hi");
  8352. ASSERT_TRUE(result);
  8353. EXPECT_EQ(StatusCode::OK_200, result->status);
  8354. result = cli.Get("/hi");
  8355. ASSERT_TRUE(result);
  8356. EXPECT_EQ(StatusCode::OK_200, result->status);
  8357. }
  8358. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8360. ASSERT_TRUE(svr.is_valid());
  8361. svr.set_keep_alive_timeout(1);
  8362. std::string content = "reconnect";
  8363. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8364. res.set_content("Hello World!", "text/plain");
  8365. });
  8366. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8367. auto se = detail::scope_exit([&] {
  8368. svr.stop();
  8369. listen_thread.join();
  8370. ASSERT_FALSE(svr.is_running());
  8371. });
  8372. svr.wait_until_ready();
  8373. SSLClient cli(HOST, PORT);
  8374. cli.enable_server_certificate_verification(false);
  8375. cli.set_keep_alive(true);
  8376. auto result = cli.Post(
  8377. "/hi", content.size(),
  8378. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8379. sink.write(content.c_str(), content.size());
  8380. return true;
  8381. },
  8382. "text/plain");
  8383. ASSERT_TRUE(result);
  8384. EXPECT_EQ(200, result->status);
  8385. std::this_thread::sleep_for(std::chrono::seconds(2));
  8386. // Recoonect
  8387. result = cli.Post(
  8388. "/hi", content.size(),
  8389. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8390. sink.write(content.c_str(), content.size());
  8391. return true;
  8392. },
  8393. "text/plain");
  8394. ASSERT_TRUE(result);
  8395. EXPECT_EQ(200, result->status);
  8396. result = cli.Post(
  8397. "/hi", content.size(),
  8398. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8399. sink.write(content.c_str(), content.size());
  8400. return true;
  8401. },
  8402. "text/plain");
  8403. ASSERT_TRUE(result);
  8404. EXPECT_EQ(200, result->status);
  8405. }
  8406. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8407. using namespace httplib::tls;
  8408. {
  8409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8410. ASSERT_TRUE(svr.is_valid());
  8411. svr.Get("/sni", [&](const Request &req, Response &res) {
  8412. std::string expected = req.sni();
  8413. EXPECT_EQ(expected, req.get_param_value("expected"));
  8414. res.set_content("ok", "text/plain");
  8415. });
  8416. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8417. auto se = detail::scope_exit([&] {
  8418. svr.stop();
  8419. listen_thread.join();
  8420. ASSERT_FALSE(svr.is_running());
  8421. });
  8422. svr.wait_until_ready();
  8423. {
  8424. SSLClient cli("localhost", PORT);
  8425. cli.enable_server_certificate_verification(false);
  8426. auto res = cli.Get("/sni?expected=localhost");
  8427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8428. }
  8429. {
  8430. SSLClient cli("::1", PORT);
  8431. cli.enable_server_certificate_verification(false);
  8432. auto res = cli.Get("/sni?expected=");
  8433. // NOTE: This may fail if the server is listening on IPv4 only
  8434. // (e.g., when localhost resolves to 127.0.0.1 only)
  8435. if (res) {
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. } else {
  8438. EXPECT_EQ(Error::Connection, res.error());
  8439. }
  8440. }
  8441. }
  8442. }
  8443. #endif
  8444. TEST(ClientProblemDetectionTest, ContentProvider) {
  8445. Server svr;
  8446. size_t content_length = 1024 * 1024;
  8447. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8448. res.set_content_provider(
  8449. content_length, "text/plain",
  8450. [&](size_t offset, size_t length, DataSink &sink) {
  8451. auto out_len = std::min(length, static_cast<size_t>(1024));
  8452. std::string out(out_len, '@');
  8453. sink.write(out.data(), out_len);
  8454. return offset < 4096;
  8455. },
  8456. [](bool success) { ASSERT_FALSE(success); });
  8457. });
  8458. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8459. res.set_content_provider(
  8460. 0, "text/plain",
  8461. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8462. EXPECT_TRUE(false);
  8463. return true;
  8464. },
  8465. [](bool success) { ASSERT_FALSE(success); });
  8466. });
  8467. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8468. auto se = detail::scope_exit([&] {
  8469. svr.stop();
  8470. listen_thread.join();
  8471. ASSERT_FALSE(svr.is_running());
  8472. });
  8473. svr.wait_until_ready();
  8474. Client cli("localhost", PORT);
  8475. {
  8476. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8477. size_t /*data_length*/) { return false; });
  8478. ASSERT_FALSE(res);
  8479. }
  8480. {
  8481. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8482. size_t /*data_length*/) { return false; });
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. }
  8485. }
  8486. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8487. Server svr;
  8488. svr.set_error_handler([](Request const &, Response &res) -> void {
  8489. res.set_chunked_content_provider(
  8490. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8491. sink.os << "hello";
  8492. sink.os << "world";
  8493. sink.done();
  8494. return true;
  8495. });
  8496. });
  8497. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8498. auto se = detail::scope_exit([&] {
  8499. svr.stop();
  8500. listen_thread.join();
  8501. ASSERT_FALSE(svr.is_running());
  8502. });
  8503. svr.wait_until_ready();
  8504. Client cli("localhost", PORT);
  8505. auto res = cli.Get("/");
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8508. EXPECT_EQ("helloworld", res->body);
  8509. }
  8510. TEST(LongPollingTest, ClientCloseDetection) {
  8511. Server svr;
  8512. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8513. res.set_chunked_content_provider(
  8514. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8515. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8516. sink.os << "hello";
  8517. auto count = 10;
  8518. while (count > 0 && sink.is_writable()) {
  8519. this_thread::sleep_for(chrono::milliseconds(10));
  8520. count--;
  8521. }
  8522. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8523. return true;
  8524. });
  8525. });
  8526. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8527. auto se = detail::scope_exit([&] {
  8528. svr.stop();
  8529. listen_thread.join();
  8530. ASSERT_FALSE(svr.is_running());
  8531. });
  8532. svr.wait_until_ready();
  8533. Client cli("localhost", PORT);
  8534. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8535. EXPECT_EQ("hello", string(data, data_length));
  8536. return false; // close the socket immediately.
  8537. });
  8538. ASSERT_FALSE(res);
  8539. }
  8540. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8541. Server svr;
  8542. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8543. res.set_chunked_content_provider(
  8544. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8545. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8546. sink.os << "hello";
  8547. EXPECT_TRUE(sink.os.good());
  8548. // Wait for the client to close the connection
  8549. auto count = 10;
  8550. while (count > 0 && sink.is_writable()) {
  8551. this_thread::sleep_for(chrono::milliseconds(10));
  8552. count--;
  8553. }
  8554. // After client disconnect, write repeatedly until the socket
  8555. // write actually fails (small writes may be absorbed by the
  8556. // kernel buffer)
  8557. std::string chunk(1024, 'x');
  8558. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8559. sink.os << chunk;
  8560. }
  8561. EXPECT_TRUE(sink.os.fail());
  8562. return true;
  8563. });
  8564. });
  8565. auto port = svr.bind_to_any_port("localhost");
  8566. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8567. auto se = detail::scope_exit([&] {
  8568. svr.stop();
  8569. listen_thread.join();
  8570. ASSERT_FALSE(svr.is_running());
  8571. });
  8572. svr.wait_until_ready();
  8573. Client cli("localhost", port);
  8574. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8575. EXPECT_EQ("hello", string(data, data_length));
  8576. return false; // close the socket immediately.
  8577. });
  8578. ASSERT_FALSE(res);
  8579. }
  8580. TEST(GetWithParametersTest, GetWithParameters) {
  8581. Server svr;
  8582. svr.Get("/", [&](const Request &req, Response &) {
  8583. EXPECT_EQ("world", req.get_param_value("hello"));
  8584. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8585. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8586. });
  8587. svr.Get("/params", [&](const Request &req, Response &) {
  8588. EXPECT_EQ("world", req.get_param_value("hello"));
  8589. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8590. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8591. });
  8592. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8593. EXPECT_EQ("resource-id", req.matches[1]);
  8594. EXPECT_EQ("foo", req.get_param_value("param1"));
  8595. EXPECT_EQ("bar", req.get_param_value("param2"));
  8596. });
  8597. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8598. EXPECT_EQ("user-id", req.path_params.at("id"));
  8599. EXPECT_EQ("foo", req.get_param_value("param1"));
  8600. EXPECT_EQ("bar", req.get_param_value("param2"));
  8601. });
  8602. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8603. auto se = detail::scope_exit([&] {
  8604. svr.stop();
  8605. listen_thread.join();
  8606. ASSERT_FALSE(svr.is_running());
  8607. });
  8608. svr.wait_until_ready();
  8609. {
  8610. Client cli(HOST, PORT);
  8611. Params params;
  8612. params.emplace("hello", "world");
  8613. params.emplace("hello2", "world2");
  8614. params.emplace("hello3", "world3");
  8615. auto res = cli.Get("/", params, Headers{});
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(StatusCode::OK_200, res->status);
  8618. }
  8619. {
  8620. Client cli(HOST, PORT);
  8621. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. }
  8625. {
  8626. Client cli(HOST, PORT);
  8627. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8629. EXPECT_EQ(StatusCode::OK_200, res->status);
  8630. }
  8631. {
  8632. Client cli(HOST, PORT);
  8633. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8635. EXPECT_EQ(StatusCode::OK_200, res->status);
  8636. }
  8637. }
  8638. TEST(GetWithParametersTest, GetWithParameters2) {
  8639. Server svr;
  8640. svr.Get("/", [&](const Request &req, Response &res) {
  8641. auto text = req.get_param_value("hello");
  8642. res.set_content(text, "text/plain");
  8643. });
  8644. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8645. auto se = detail::scope_exit([&] {
  8646. svr.stop();
  8647. listen_thread.join();
  8648. ASSERT_FALSE(svr.is_running());
  8649. });
  8650. svr.wait_until_ready();
  8651. Client cli("localhost", PORT);
  8652. Params params;
  8653. params.emplace("hello", "world");
  8654. std::string body;
  8655. auto res = cli.Get("/", params, Headers{},
  8656. [&](const char *data, size_t data_length) {
  8657. body.append(data, data_length);
  8658. return true;
  8659. });
  8660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8661. EXPECT_EQ(StatusCode::OK_200, res->status);
  8662. EXPECT_EQ("world", body);
  8663. }
  8664. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8665. Server svr;
  8666. svr.Get("/search", [&](const Request &req, Response &res) {
  8667. auto q = req.get_param_value("q");
  8668. res.set_content(q, "text/plain");
  8669. });
  8670. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8671. auto se = detail::scope_exit([&] {
  8672. svr.stop();
  8673. listen_thread.join();
  8674. ASSERT_FALSE(svr.is_running());
  8675. });
  8676. svr.wait_until_ready();
  8677. Client cli("localhost", PORT);
  8678. // Verify that Get(path, params) works without requiring Headers argument
  8679. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. EXPECT_EQ("cpp-httplib", res->body);
  8683. }
  8684. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8685. auto host = "httpbingo.org";
  8686. auto path = std::string{"/range/32"};
  8687. #ifdef CPPHTTPLIB_SSL_ENABLED
  8688. SSLClient cli(host);
  8689. #else
  8690. Client cli(host);
  8691. #endif
  8692. cli.set_default_headers({make_range_header({{1, 10}})});
  8693. cli.set_connection_timeout(5);
  8694. {
  8695. auto res = cli.Get(path);
  8696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8697. EXPECT_EQ("bcdefghijk", res->body);
  8698. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8699. }
  8700. {
  8701. auto res = cli.Get(path);
  8702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8703. EXPECT_EQ("bcdefghijk", res->body);
  8704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8705. }
  8706. }
  8707. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8708. Server svr;
  8709. svr.set_default_headers({{"Hello", "World"}});
  8710. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8711. res.set_content("ok", "text/plain");
  8712. });
  8713. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8714. auto se = detail::scope_exit([&] {
  8715. svr.stop();
  8716. listen_thread.join();
  8717. ASSERT_FALSE(svr.is_running());
  8718. });
  8719. svr.wait_until_ready();
  8720. Client cli("localhost", PORT);
  8721. auto res = cli.Get("/");
  8722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8723. EXPECT_EQ(StatusCode::OK_200, res->status);
  8724. EXPECT_EQ("ok", res->body);
  8725. EXPECT_EQ("World", res->get_header_value("Hello"));
  8726. }
  8727. #ifdef CPPHTTPLIB_SSL_ENABLED
  8728. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8730. ASSERT_TRUE(svr.is_valid());
  8731. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8732. std::this_thread::sleep_for(std::chrono::seconds(2));
  8733. res.set_content("a", "text/plain");
  8734. });
  8735. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8736. res.set_content("b", "text/plain");
  8737. });
  8738. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8739. auto se = detail::scope_exit([&] {
  8740. svr.stop();
  8741. listen_thread.join();
  8742. ASSERT_FALSE(svr.is_running());
  8743. });
  8744. svr.wait_until_ready();
  8745. SSLClient cli("localhost", PORT);
  8746. cli.enable_server_certificate_verification(false);
  8747. cli.set_keep_alive(true);
  8748. cli.set_read_timeout(std::chrono::seconds(1));
  8749. auto resa = cli.Get("/a");
  8750. ASSERT_TRUE(!resa);
  8751. EXPECT_EQ(Error::Read, resa.error());
  8752. auto resb = cli.Get("/b");
  8753. ASSERT_TRUE(resb);
  8754. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8755. EXPECT_EQ("b", resb->body);
  8756. }
  8757. #endif
  8758. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8759. protected:
  8760. ServerTestWithAI_PASSIVE()
  8761. : cli_(HOST, PORT)
  8762. #ifdef CPPHTTPLIB_SSL_ENABLED
  8763. ,
  8764. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8765. #endif
  8766. {
  8767. #ifdef CPPHTTPLIB_SSL_ENABLED
  8768. cli_.enable_server_certificate_verification(false);
  8769. #endif
  8770. }
  8771. virtual void SetUp() {
  8772. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8773. res.set_content("Hello World!", "text/plain");
  8774. });
  8775. t_ = thread(
  8776. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8777. svr_.wait_until_ready();
  8778. }
  8779. virtual void TearDown() {
  8780. svr_.stop();
  8781. t_.join();
  8782. }
  8783. #ifdef CPPHTTPLIB_SSL_ENABLED
  8784. SSLClient cli_;
  8785. SSLServer svr_;
  8786. #else
  8787. Client cli_;
  8788. Server svr_;
  8789. #endif
  8790. thread t_;
  8791. };
  8792. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8793. auto res = cli_.Get("/hi");
  8794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8795. EXPECT_EQ(StatusCode::OK_200, res->status);
  8796. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8797. EXPECT_EQ("Hello World!", res->body);
  8798. }
  8799. class ServerUpDownTest : public ::testing::Test {
  8800. protected:
  8801. ServerUpDownTest() : cli_(HOST, PORT) {}
  8802. virtual void SetUp() {
  8803. t_ = thread([&]() {
  8804. svr_.bind_to_any_port(HOST);
  8805. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8806. ASSERT_TRUE(svr_.listen_after_bind());
  8807. });
  8808. svr_.wait_until_ready();
  8809. }
  8810. virtual void TearDown() {
  8811. svr_.stop();
  8812. t_.join();
  8813. }
  8814. Client cli_;
  8815. Server svr_;
  8816. thread t_;
  8817. };
  8818. TEST_F(ServerUpDownTest, QuickStartStop) {
  8819. // Should not crash, especially when run with
  8820. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8821. }
  8822. class PayloadMaxLengthTest : public ::testing::Test {
  8823. protected:
  8824. PayloadMaxLengthTest()
  8825. : cli_(HOST, PORT)
  8826. #ifdef CPPHTTPLIB_SSL_ENABLED
  8827. ,
  8828. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8829. #endif
  8830. {
  8831. #ifdef CPPHTTPLIB_SSL_ENABLED
  8832. cli_.enable_server_certificate_verification(false);
  8833. #endif
  8834. }
  8835. virtual void SetUp() {
  8836. svr_.set_payload_max_length(8);
  8837. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8838. res.set_content("test", "text/plain");
  8839. });
  8840. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8841. svr_.wait_until_ready();
  8842. }
  8843. virtual void TearDown() {
  8844. svr_.stop();
  8845. t_.join();
  8846. }
  8847. #ifdef CPPHTTPLIB_SSL_ENABLED
  8848. SSLClient cli_;
  8849. SSLServer svr_;
  8850. #else
  8851. Client cli_;
  8852. Server svr_;
  8853. #endif
  8854. thread t_;
  8855. };
  8856. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8857. auto res = cli_.Post("/test", "123456789", "text/plain");
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8860. res = cli_.Post("/test", "12345678", "text/plain");
  8861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8862. EXPECT_EQ(StatusCode::OK_200, res->status);
  8863. }
  8864. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8865. // Test chunked encoding with payload exceeding the 8-byte limit
  8866. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8867. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8869. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8870. }
  8871. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8872. // Test chunked encoding with payload within the 8-byte limit
  8873. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8874. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. }
  8878. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8879. // Test using send_request to send chunked data exceeding payload limit
  8880. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8881. "Host: " +
  8882. std::string(HOST) + ":" + std::to_string(PORT) +
  8883. "\r\n"
  8884. "Transfer-Encoding: chunked\r\n"
  8885. "Connection: close\r\n"
  8886. "\r\n"
  8887. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8888. "0123456789\r\n"
  8889. "0\r\n" // End chunk
  8890. "\r\n";
  8891. std::string response;
  8892. bool result = send_request(1, chunked_request, &response);
  8893. if (!result) {
  8894. // If send_request fails, it might be because the server closed the
  8895. // connection due to payload limit enforcement, which is acceptable
  8896. SUCCEED()
  8897. << "Server rejected oversized chunked request (connection closed)";
  8898. } else {
  8899. // If we got a response, check if it's an error response or connection was
  8900. // closed early Short response length indicates connection was closed due to
  8901. // payload limit
  8902. if (response.length() <= 10) {
  8903. SUCCEED() << "Server closed connection for oversized chunked request";
  8904. } else {
  8905. // Check for error status codes
  8906. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8907. response.find("Payload Too Large") != std::string::npos ||
  8908. response.find("400") != std::string::npos);
  8909. }
  8910. }
  8911. }
  8912. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8913. // Test request without Content-Length header exceeding payload limit
  8914. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8915. "Host: " +
  8916. std::string(HOST) + ":" +
  8917. std::to_string(PORT) +
  8918. "\r\n"
  8919. "Connection: close\r\n"
  8920. "\r\n";
  8921. // Add payload exceeding the 8-byte limit
  8922. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8923. request_without_content_length += large_payload;
  8924. std::string response;
  8925. bool result = send_request(1, request_without_content_length, &response);
  8926. if (!result) {
  8927. // If send_request fails, server likely closed connection due to payload
  8928. // limit
  8929. SUCCEED() << "Server rejected oversized request without Content-Length "
  8930. "(connection closed)";
  8931. } else {
  8932. // Check if server responded with error or closed connection early
  8933. if (response.length() <= 10) {
  8934. SUCCEED() << "Server closed connection for oversized request without "
  8935. "Content-Length";
  8936. } else {
  8937. // Check for error status codes
  8938. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8939. response.find("Payload Too Large") != std::string::npos ||
  8940. response.find("400") != std::string::npos);
  8941. }
  8942. }
  8943. }
  8944. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8945. // Test request without Content-Length header within payload limit
  8946. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8947. "Host: " +
  8948. std::string(HOST) + ":" +
  8949. std::to_string(PORT) +
  8950. "\r\n"
  8951. "Connection: close\r\n"
  8952. "\r\n";
  8953. // Add payload within the 8-byte limit
  8954. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8955. request_without_content_length += small_payload;
  8956. std::string response;
  8957. bool result = send_request(1, request_without_content_length, &response);
  8958. // For requests without Content-Length, the server may have different behavior
  8959. // The key is that it should not reject due to payload limit for small
  8960. // payloads
  8961. if (result) {
  8962. // Check for any HTTP response (success or error, but not connection closed)
  8963. if (response.length() > 10) {
  8964. SUCCEED()
  8965. << "Server processed request without Content-Length within limit";
  8966. } else {
  8967. // Short response might indicate connection closed, which is acceptable
  8968. SUCCEED() << "Server closed connection for request without "
  8969. "Content-Length (acceptable behavior)";
  8970. }
  8971. } else {
  8972. // Connection failure might be due to protocol requirements
  8973. SUCCEED() << "Connection issue with request without Content-Length "
  8974. "(environment-specific)";
  8975. }
  8976. }
  8977. class LargePayloadMaxLengthTest : public ::testing::Test {
  8978. protected:
  8979. LargePayloadMaxLengthTest()
  8980. : cli_(HOST, PORT)
  8981. #ifdef CPPHTTPLIB_SSL_ENABLED
  8982. ,
  8983. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8984. #endif
  8985. {
  8986. #ifdef CPPHTTPLIB_SSL_ENABLED
  8987. cli_.enable_server_certificate_verification(false);
  8988. #endif
  8989. }
  8990. virtual void SetUp() {
  8991. // Set 10MB payload limit
  8992. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8993. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8994. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8995. res.set_content("Large payload test", "text/plain");
  8996. });
  8997. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8998. svr_.wait_until_ready();
  8999. }
  9000. virtual void TearDown() {
  9001. svr_.stop();
  9002. t_.join();
  9003. }
  9004. #ifdef CPPHTTPLIB_SSL_ENABLED
  9005. SSLClient cli_;
  9006. SSLServer svr_;
  9007. #else
  9008. Client cli_;
  9009. Server svr_;
  9010. #endif
  9011. thread t_;
  9012. };
  9013. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9014. // Test chunked encoding with payload within 10MB limit
  9015. std::string medium_payload(5 * 1024 * 1024,
  9016. 'A'); // 5MB payload, within 10MB limit
  9017. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9019. EXPECT_EQ(StatusCode::OK_200, res->status);
  9020. }
  9021. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9022. // Test chunked encoding with payload exceeding 10MB limit
  9023. std::string large_payload(12 * 1024 * 1024,
  9024. 'B'); // 12MB payload, exceeds 10MB limit
  9025. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9026. // Server may either return 413 or close the connection
  9027. if (res) {
  9028. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9029. } else {
  9030. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9031. }
  9032. }
  9033. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9034. // Test request without Content-Length header within 10MB limit
  9035. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9036. "Host: " +
  9037. std::string(HOST) + ":" +
  9038. std::to_string(PORT) +
  9039. "\r\n"
  9040. "Connection: close\r\n"
  9041. "\r\n";
  9042. // Add 1MB payload (within 10MB limit)
  9043. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9044. request_without_content_length += medium_payload;
  9045. std::string response;
  9046. bool result = send_request(5, request_without_content_length, &response);
  9047. if (result) {
  9048. // Should get a proper HTTP response for payloads within limit
  9049. if (response.length() > 10) {
  9050. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9051. "10MB limit";
  9052. } else {
  9053. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9054. "Content-Length)";
  9055. }
  9056. } else {
  9057. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9058. }
  9059. }
  9060. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9061. // Test request without Content-Length header exceeding 10MB limit
  9062. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9063. "Host: " +
  9064. std::string(HOST) + ":" +
  9065. std::to_string(PORT) +
  9066. "\r\n"
  9067. "Connection: close\r\n"
  9068. "\r\n";
  9069. // Add 12MB payload (exceeds 10MB limit)
  9070. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9071. request_without_content_length += large_payload;
  9072. std::string response;
  9073. bool result = send_request(10, request_without_content_length, &response);
  9074. if (!result) {
  9075. // Server should close connection due to payload limit
  9076. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9077. "(connection closed)";
  9078. } else {
  9079. // Check for error response
  9080. if (response.length() <= 10) {
  9081. SUCCEED()
  9082. << "Server closed connection for 12MB request exceeding 10MB limit";
  9083. } else {
  9084. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9085. response.find("Payload Too Large") != std::string::npos ||
  9086. response.find("400") != std::string::npos);
  9087. }
  9088. }
  9089. }
  9090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9091. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9092. // path.
  9093. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9094. Server svr;
  9095. const size_t LIMIT = 64 * 1024; // 64KB
  9096. svr.set_payload_max_length(LIMIT);
  9097. size_t total = 0;
  9098. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9099. const ContentReader &content_reader) {
  9100. content_reader([&](const char * /*data*/, size_t len) {
  9101. total += len;
  9102. return true;
  9103. });
  9104. res.status = 200;
  9105. res.set_content("stream_ok", "text/plain");
  9106. });
  9107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9108. auto se = detail::scope_exit([&] {
  9109. svr.stop();
  9110. thread.join();
  9111. ASSERT_FALSE(svr.is_running());
  9112. });
  9113. svr.wait_until_ready();
  9114. // Prepare 256KB raw data and gzip-compress it
  9115. std::string raw(256 * 1024, 'A');
  9116. std::string gz;
  9117. {
  9118. z_stream zs{};
  9119. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9120. Z_DEFAULT_STRATEGY);
  9121. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9122. zs.avail_in = static_cast<uInt>(raw.size());
  9123. char outbuf[4096];
  9124. int ret;
  9125. do {
  9126. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9127. zs.avail_out = sizeof(outbuf);
  9128. ret = deflate(&zs, Z_FINISH);
  9129. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9130. } while (ret != Z_STREAM_END);
  9131. deflateEnd(&zs);
  9132. }
  9133. Client cli(HOST, PORT);
  9134. cli.set_connection_timeout(std::chrono::seconds(5));
  9135. Headers headers = {{"Content-Encoding", "gzip"}};
  9136. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9137. "application/octet-stream");
  9138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9139. // Server must reject oversized decompressed payloads with 413.
  9140. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9141. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9142. EXPECT_LE(total, LIMIT);
  9143. }
  9144. #endif
  9145. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9146. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9147. // the payload must be passed through untouched instead of being rejected.
  9148. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9149. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9150. Server svr;
  9151. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9152. res.set_content(body, "image/jpeg");
  9153. res.set_header("Content-Encoding", "UTF-8");
  9154. });
  9155. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9156. res.set_content(body, "image/jpeg");
  9157. res.set_header("Content-Encoding", "identity");
  9158. });
  9159. svr.Post("/echo", [](const Request &req, Response &res) {
  9160. res.set_content(req.body, "image/jpeg");
  9161. });
  9162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9163. auto se = detail::scope_exit([&] {
  9164. svr.stop();
  9165. t.join();
  9166. ASSERT_FALSE(svr.is_running());
  9167. });
  9168. svr.wait_until_ready();
  9169. Client cli(HOST, PORT);
  9170. {
  9171. auto res = cli.Get("/image");
  9172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9173. EXPECT_EQ(StatusCode::OK_200, res->status);
  9174. EXPECT_EQ(body, res->body);
  9175. }
  9176. {
  9177. auto res = cli.Get("/identity");
  9178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. EXPECT_EQ(body, res->body);
  9181. }
  9182. {
  9183. // The same applies to a request body reaching the server.
  9184. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9185. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9187. EXPECT_EQ(StatusCode::OK_200, res->status);
  9188. EXPECT_EQ(body, res->body);
  9189. }
  9190. }
  9191. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9192. // gzip-encoded response even when the build has no zlib support.
  9193. static const char GZIPPED_HELLO_WORLD[] = {
  9194. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9195. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9196. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9197. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9198. // A content coding cpp-httplib recognizes but was not built with must be
  9199. // reported as such. Handing the still-compressed payload back to the caller
  9200. // would silently corrupt it.
  9201. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9202. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9203. Server svr;
  9204. // "image/jpeg" keeps the server from applying a content coding of its own,
  9205. // so the hand-crafted Content-Encoding below survives.
  9206. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9207. res.set_content(gzipped, "image/jpeg");
  9208. res.set_header("Content-Encoding", "gzip");
  9209. });
  9210. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9211. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9212. res.set_content(gzipped, "image/jpeg");
  9213. res.set_header("Content-Encoding", "GZIP");
  9214. });
  9215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9216. auto se = detail::scope_exit([&] {
  9217. svr.stop();
  9218. t.join();
  9219. ASSERT_FALSE(svr.is_running());
  9220. });
  9221. svr.wait_until_ready();
  9222. Client cli(HOST, PORT);
  9223. {
  9224. auto res = cli.Get("/gzipped");
  9225. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9227. EXPECT_EQ("Hello World!", res->body);
  9228. #else
  9229. ASSERT_FALSE(res);
  9230. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9231. #endif
  9232. }
  9233. {
  9234. // open_stream() must behave the same way.
  9235. auto handle = cli.open_stream("GET", "/gzipped");
  9236. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9237. ASSERT_TRUE(handle.is_valid());
  9238. std::string received;
  9239. char buf[256];
  9240. ssize_t n;
  9241. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9242. received.append(buf, static_cast<size_t>(n));
  9243. }
  9244. EXPECT_EQ("Hello World!", received);
  9245. #else
  9246. EXPECT_FALSE(handle.is_valid());
  9247. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9248. #endif
  9249. }
  9250. {
  9251. // A differently-cased coding must not be mistaken for an unknown one, or
  9252. // the body would be handed back still compressed.
  9253. auto res = cli.Get("/gzipped-uppercase");
  9254. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9256. EXPECT_EQ("Hello World!", res->body);
  9257. #else
  9258. ASSERT_FALSE(res);
  9259. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9260. #endif
  9261. }
  9262. }
  9263. // Regression test for DoS vulnerability: a malicious server sending a response
  9264. // without Content-Length header must not cause unbounded memory consumption on
  9265. // the client side. The client should stop reading after a reasonable limit,
  9266. // similar to the server-side set_payload_max_length protection.
  9267. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9268. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9269. #ifndef _WIN32
  9270. signal(SIGPIPE, SIG_IGN);
  9271. #endif
  9272. auto server_thread = std::thread([] {
  9273. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9274. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9275. default_socket_options(srv);
  9276. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9277. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9278. sockaddr_in addr{};
  9279. addr.sin_family = AF_INET;
  9280. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9281. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9282. int opt = 1;
  9283. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9284. #ifdef _WIN32
  9285. reinterpret_cast<const char *>(&opt),
  9286. #else
  9287. &opt,
  9288. #endif
  9289. sizeof(opt));
  9290. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9291. ::listen(srv, 1);
  9292. sockaddr_in cli_addr{};
  9293. socklen_t cli_len = sizeof(cli_addr);
  9294. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9295. if (cli != INVALID_SOCKET) {
  9296. char buf[4096];
  9297. ::recv(cli, buf, sizeof(buf), 0);
  9298. // Malicious response: no Content-Length, no chunked encoding
  9299. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9300. "Connection: close\r\n"
  9301. "\r\n";
  9302. ::send(cli,
  9303. #ifdef _WIN32
  9304. static_cast<const char *>(response_header.c_str()),
  9305. static_cast<int>(response_header.size()),
  9306. #else
  9307. response_header.c_str(), response_header.size(),
  9308. #endif
  9309. 0);
  9310. // Send 10MB of data
  9311. std::string chunk(64 * 1024, 'A');
  9312. size_t total_sent = 0;
  9313. while (total_sent < MALICIOUS_DATA_SIZE) {
  9314. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9315. auto sent = ::send(cli,
  9316. #ifdef _WIN32
  9317. static_cast<const char *>(chunk.c_str()),
  9318. static_cast<int>(to_send),
  9319. #else
  9320. chunk.c_str(), to_send,
  9321. #endif
  9322. 0);
  9323. if (sent <= 0) break;
  9324. total_sent += static_cast<size_t>(sent);
  9325. }
  9326. detail::close_socket(cli);
  9327. }
  9328. detail::close_socket(srv);
  9329. });
  9330. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9331. size_t total_read = 0;
  9332. {
  9333. Client cli("127.0.0.1", PORT + 2);
  9334. cli.set_read_timeout(5, 0);
  9335. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9336. auto stream = cli.open_stream("GET", "/malicious");
  9337. ASSERT_TRUE(stream.is_valid());
  9338. char buffer[64 * 1024];
  9339. ssize_t n;
  9340. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9341. total_read += static_cast<size_t>(n);
  9342. }
  9343. } // StreamHandle and Client destroyed here, closing the socket
  9344. server_thread.join();
  9345. // With set_payload_max_length, the client must stop reading before consuming
  9346. // all 10MB. The read loop should be cut off at or near the configured limit.
  9347. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9348. << "Client read " << total_read << " bytes, exceeding the configured "
  9349. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9350. }
  9351. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9352. // the entire response body without truncation.
  9353. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9354. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9355. #ifndef _WIN32
  9356. signal(SIGPIPE, SIG_IGN);
  9357. #endif
  9358. auto server_thread = std::thread([] {
  9359. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9360. default_socket_options(srv);
  9361. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9362. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9363. sockaddr_in addr{};
  9364. addr.sin_family = AF_INET;
  9365. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9366. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9367. int opt = 1;
  9368. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9369. #ifdef _WIN32
  9370. reinterpret_cast<const char *>(&opt),
  9371. #else
  9372. &opt,
  9373. #endif
  9374. sizeof(opt));
  9375. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9376. ::listen(srv, 1);
  9377. sockaddr_in cli_addr{};
  9378. socklen_t cli_len = sizeof(cli_addr);
  9379. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9380. if (cli != INVALID_SOCKET) {
  9381. char buf[4096];
  9382. ::recv(cli, buf, sizeof(buf), 0);
  9383. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9384. "Connection: close\r\n"
  9385. "\r\n";
  9386. ::send(cli,
  9387. #ifdef _WIN32
  9388. static_cast<const char *>(response_header.c_str()),
  9389. static_cast<int>(response_header.size()),
  9390. #else
  9391. response_header.c_str(), response_header.size(),
  9392. #endif
  9393. 0);
  9394. std::string chunk(64 * 1024, 'A');
  9395. size_t total_sent = 0;
  9396. while (total_sent < DATA_SIZE) {
  9397. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9398. auto sent = ::send(cli,
  9399. #ifdef _WIN32
  9400. static_cast<const char *>(chunk.c_str()),
  9401. static_cast<int>(to_send),
  9402. #else
  9403. chunk.c_str(), to_send,
  9404. #endif
  9405. 0);
  9406. if (sent <= 0) break;
  9407. total_sent += static_cast<size_t>(sent);
  9408. }
  9409. #ifdef _WIN32
  9410. ::shutdown(cli, SD_SEND);
  9411. #else
  9412. ::shutdown(cli, SHUT_WR);
  9413. #endif
  9414. // Drain until the client closes its end, ensuring all data is delivered
  9415. char drain[1024];
  9416. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9417. detail::close_socket(cli);
  9418. }
  9419. detail::close_socket(srv);
  9420. });
  9421. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9422. size_t total_read = 0;
  9423. {
  9424. Client cli("127.0.0.1", PORT + 2);
  9425. cli.set_read_timeout(5, 0);
  9426. cli.set_payload_max_length(0); // 0 means no limit
  9427. auto stream = cli.open_stream("GET", "/data");
  9428. ASSERT_TRUE(stream.is_valid());
  9429. char buffer[64 * 1024];
  9430. ssize_t n;
  9431. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9432. total_read += static_cast<size_t>(n);
  9433. }
  9434. }
  9435. server_thread.join();
  9436. EXPECT_EQ(total_read, DATA_SIZE)
  9437. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9438. << " bytes without truncation, but only read " << total_read << " bytes.";
  9439. }
  9440. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9441. // enormous Content-Length must not cause the client to pre-allocate a huge
  9442. // response body buffer. The reservation is capped at payload_max_length_, and
  9443. // the read itself fails when the body exceeds the limit.
  9444. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9445. #ifndef _WIN32
  9446. signal(SIGPIPE, SIG_IGN);
  9447. #endif
  9448. auto server_thread = std::thread([] {
  9449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9450. default_socket_options(srv);
  9451. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9452. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9453. sockaddr_in addr{};
  9454. addr.sin_family = AF_INET;
  9455. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9456. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9457. int opt = 1;
  9458. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9459. #ifdef _WIN32
  9460. reinterpret_cast<const char *>(&opt),
  9461. #else
  9462. &opt,
  9463. #endif
  9464. sizeof(opt));
  9465. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9466. ::listen(srv, 1);
  9467. sockaddr_in cli_addr{};
  9468. socklen_t cli_len = sizeof(cli_addr);
  9469. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9470. if (cli != INVALID_SOCKET) {
  9471. char buf[4096];
  9472. ::recv(cli, buf, sizeof(buf), 0);
  9473. // Malicious response: claim a 20GB body but send only a tiny payload.
  9474. std::string response = "HTTP/1.1 200 OK\r\n"
  9475. "Content-Length: 20000000000\r\n"
  9476. "\r\n"
  9477. "abc";
  9478. ::send(cli,
  9479. #ifdef _WIN32
  9480. static_cast<const char *>(response.c_str()),
  9481. static_cast<int>(response.size()),
  9482. #else
  9483. response.c_str(), response.size(),
  9484. #endif
  9485. 0);
  9486. detail::close_socket(cli);
  9487. }
  9488. detail::close_socket(srv);
  9489. });
  9490. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9491. {
  9492. Client cli("127.0.0.1", PORT + 2);
  9493. cli.set_read_timeout(5, 0);
  9494. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9495. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9496. // (server claims more bytes than payload_max_length permits), but it must
  9497. // not exhaust memory before getting there.
  9498. auto res = cli.Get("/malicious");
  9499. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9500. }
  9501. server_thread.join();
  9502. }
  9503. // Verify that content_receiver bypasses the default payload_max_length,
  9504. // allowing streaming downloads larger than 100MB without requiring an explicit
  9505. // set_payload_max_length call.
  9506. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9507. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9508. #ifndef _WIN32
  9509. signal(SIGPIPE, SIG_IGN);
  9510. #endif
  9511. auto server_thread = std::thread([] {
  9512. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9513. default_socket_options(srv);
  9514. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9515. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9516. sockaddr_in addr{};
  9517. addr.sin_family = AF_INET;
  9518. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9519. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9520. int opt = 1;
  9521. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9522. #ifdef _WIN32
  9523. reinterpret_cast<const char *>(&opt),
  9524. #else
  9525. &opt,
  9526. #endif
  9527. sizeof(opt));
  9528. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9529. ::listen(srv, 1);
  9530. sockaddr_in cli_addr{};
  9531. socklen_t cli_len = sizeof(cli_addr);
  9532. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9533. if (cli != INVALID_SOCKET) {
  9534. char buf[4096];
  9535. ::recv(cli, buf, sizeof(buf), 0);
  9536. // Response with Content-Length larger than default 100MB limit
  9537. auto content_length = std::to_string(DATA_SIZE);
  9538. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9539. "Content-Length: " +
  9540. content_length +
  9541. "\r\n"
  9542. "Connection: close\r\n"
  9543. "\r\n";
  9544. ::send(cli,
  9545. #ifdef _WIN32
  9546. static_cast<const char *>(response_header.c_str()),
  9547. static_cast<int>(response_header.size()),
  9548. #else
  9549. response_header.c_str(), response_header.size(),
  9550. #endif
  9551. 0);
  9552. std::string chunk(64 * 1024, 'A');
  9553. size_t total_sent = 0;
  9554. while (total_sent < DATA_SIZE) {
  9555. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9556. auto sent = ::send(cli,
  9557. #ifdef _WIN32
  9558. static_cast<const char *>(chunk.c_str()),
  9559. static_cast<int>(to_send),
  9560. #else
  9561. chunk.c_str(), to_send,
  9562. #endif
  9563. 0);
  9564. if (sent <= 0) break;
  9565. total_sent += static_cast<size_t>(sent);
  9566. }
  9567. detail::close_socket(cli);
  9568. }
  9569. detail::close_socket(srv);
  9570. });
  9571. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9572. size_t total_received = 0;
  9573. {
  9574. Client cli("127.0.0.1", PORT + 2);
  9575. cli.set_read_timeout(10, 0);
  9576. // Do NOT call set_payload_max_length — use the default 100MB limit
  9577. auto res =
  9578. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9579. total_received += data_length;
  9580. return true;
  9581. });
  9582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9583. EXPECT_EQ(StatusCode::OK_200, res->status);
  9584. }
  9585. server_thread.join();
  9586. EXPECT_EQ(total_received, DATA_SIZE)
  9587. << "With content_receiver, the client should read all " << DATA_SIZE
  9588. << " bytes despite the default 100MB payload_max_length, but only read "
  9589. << total_received << " bytes.";
  9590. }
  9591. // Verify that an explicit set_payload_max_length smaller than the response is
  9592. // enforced even when a content_receiver is used.
  9593. TEST(ClientVulnerabilityTest,
  9594. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9595. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9596. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9597. #ifndef _WIN32
  9598. signal(SIGPIPE, SIG_IGN);
  9599. #endif
  9600. auto server_thread = std::thread([] {
  9601. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9602. default_socket_options(srv);
  9603. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9604. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9605. sockaddr_in addr{};
  9606. addr.sin_family = AF_INET;
  9607. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9608. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9609. int opt = 1;
  9610. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9611. #ifdef _WIN32
  9612. reinterpret_cast<const char *>(&opt),
  9613. #else
  9614. &opt,
  9615. #endif
  9616. sizeof(opt));
  9617. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9618. ::listen(srv, 1);
  9619. sockaddr_in cli_addr{};
  9620. socklen_t cli_len = sizeof(cli_addr);
  9621. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9622. if (cli != INVALID_SOCKET) {
  9623. char buf[4096];
  9624. ::recv(cli, buf, sizeof(buf), 0);
  9625. auto content_length = std::to_string(DATA_SIZE);
  9626. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9627. "Content-Length: " +
  9628. content_length +
  9629. "\r\n"
  9630. "Connection: close\r\n"
  9631. "\r\n";
  9632. ::send(cli,
  9633. #ifdef _WIN32
  9634. static_cast<const char *>(response_header.c_str()),
  9635. static_cast<int>(response_header.size()),
  9636. #else
  9637. response_header.c_str(), response_header.size(),
  9638. #endif
  9639. 0);
  9640. std::string chunk(64 * 1024, 'A');
  9641. size_t total_sent = 0;
  9642. while (total_sent < DATA_SIZE) {
  9643. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9644. auto sent = ::send(cli,
  9645. #ifdef _WIN32
  9646. static_cast<const char *>(chunk.c_str()),
  9647. static_cast<int>(to_send),
  9648. #else
  9649. chunk.c_str(), to_send,
  9650. #endif
  9651. 0);
  9652. if (sent <= 0) break;
  9653. total_sent += static_cast<size_t>(sent);
  9654. }
  9655. detail::close_socket(cli);
  9656. }
  9657. detail::close_socket(srv);
  9658. });
  9659. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9660. size_t total_received = 0;
  9661. {
  9662. Client cli("127.0.0.1", PORT + 2);
  9663. cli.set_read_timeout(10, 0);
  9664. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9665. auto res =
  9666. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9667. total_received += data_length;
  9668. return true;
  9669. });
  9670. // Should fail because 200MB exceeds the explicit 150MB limit
  9671. EXPECT_FALSE(res);
  9672. }
  9673. server_thread.join();
  9674. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9675. << "Client with content_receiver should respect the explicit "
  9676. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9677. << total_received << " bytes.";
  9678. }
  9679. // Verify that an explicit set_payload_max_length larger than the response
  9680. // allows the content_receiver to read all data successfully.
  9681. TEST(ClientVulnerabilityTest,
  9682. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9683. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9684. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9685. #ifndef _WIN32
  9686. signal(SIGPIPE, SIG_IGN);
  9687. #endif
  9688. auto server_thread = std::thread([] {
  9689. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9690. default_socket_options(srv);
  9691. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9692. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9693. sockaddr_in addr{};
  9694. addr.sin_family = AF_INET;
  9695. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9696. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9697. int opt = 1;
  9698. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9699. #ifdef _WIN32
  9700. reinterpret_cast<const char *>(&opt),
  9701. #else
  9702. &opt,
  9703. #endif
  9704. sizeof(opt));
  9705. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9706. ::listen(srv, 1);
  9707. sockaddr_in cli_addr{};
  9708. socklen_t cli_len = sizeof(cli_addr);
  9709. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9710. if (cli != INVALID_SOCKET) {
  9711. char buf[4096];
  9712. ::recv(cli, buf, sizeof(buf), 0);
  9713. auto content_length = std::to_string(DATA_SIZE);
  9714. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9715. "Content-Length: " +
  9716. content_length +
  9717. "\r\n"
  9718. "Connection: close\r\n"
  9719. "\r\n";
  9720. ::send(cli,
  9721. #ifdef _WIN32
  9722. static_cast<const char *>(response_header.c_str()),
  9723. static_cast<int>(response_header.size()),
  9724. #else
  9725. response_header.c_str(), response_header.size(),
  9726. #endif
  9727. 0);
  9728. std::string chunk(64 * 1024, 'A');
  9729. size_t total_sent = 0;
  9730. while (total_sent < DATA_SIZE) {
  9731. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9732. auto sent = ::send(cli,
  9733. #ifdef _WIN32
  9734. static_cast<const char *>(chunk.c_str()),
  9735. static_cast<int>(to_send),
  9736. #else
  9737. chunk.c_str(), to_send,
  9738. #endif
  9739. 0);
  9740. if (sent <= 0) break;
  9741. total_sent += static_cast<size_t>(sent);
  9742. }
  9743. #ifdef _WIN32
  9744. ::shutdown(cli, SD_SEND);
  9745. #else
  9746. ::shutdown(cli, SHUT_WR);
  9747. #endif
  9748. char drain[1024];
  9749. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9750. detail::close_socket(cli);
  9751. }
  9752. detail::close_socket(srv);
  9753. });
  9754. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9755. size_t total_received = 0;
  9756. {
  9757. Client cli("127.0.0.1", PORT + 2);
  9758. cli.set_read_timeout(10, 0);
  9759. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9760. auto res =
  9761. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9762. total_received += data_length;
  9763. return true;
  9764. });
  9765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9766. EXPECT_EQ(StatusCode::OK_200, res->status);
  9767. }
  9768. server_thread.join();
  9769. EXPECT_EQ(total_received, DATA_SIZE)
  9770. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9771. << " bytes (larger than " << DATA_SIZE
  9772. << " bytes response), content_receiver should read all data, but only "
  9773. "read "
  9774. << total_received << " bytes.";
  9775. }
  9776. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9777. // Regression test for "zip bomb" attack on the client side: a malicious server
  9778. // sends a small gzip-compressed response that decompresses to a huge payload.
  9779. // The client must enforce payload_max_length on the decompressed size.
  9780. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9781. constexpr size_t DECOMPRESSED_SIZE =
  9782. 10 * 1024 * 1024; // 10MB after decompression
  9783. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9784. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9785. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9786. std::string compressed;
  9787. {
  9788. httplib::detail::gzip_compressor compressor;
  9789. bool ok =
  9790. compressor.compress(uncompressed.data(), uncompressed.size(),
  9791. /*last=*/true, [&](const char *buf, size_t len) {
  9792. compressed.append(buf, len);
  9793. return true;
  9794. });
  9795. ASSERT_TRUE(ok);
  9796. }
  9797. // Sanity: compressed data should be much smaller than the decompressed size
  9798. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9799. #ifndef _WIN32
  9800. signal(SIGPIPE, SIG_IGN);
  9801. #endif
  9802. // Set up the listening socket in the main thread so the server is guaranteed
  9803. // to be ready before the client connects (eliminates race condition).
  9804. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9805. default_socket_options(srv);
  9806. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9807. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9808. sockaddr_in addr{};
  9809. addr.sin_family = AF_INET;
  9810. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9811. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9812. int opt = 1;
  9813. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9814. #ifdef _WIN32
  9815. reinterpret_cast<const char *>(&opt),
  9816. #else
  9817. &opt,
  9818. #endif
  9819. sizeof(opt));
  9820. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9821. ASSERT_EQ(0, ::listen(srv, 1));
  9822. auto server_thread = std::thread([&compressed, srv] {
  9823. sockaddr_in cli_addr{};
  9824. socklen_t cli_len = sizeof(cli_addr);
  9825. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9826. if (cli != INVALID_SOCKET) {
  9827. // Read the full HTTP request (until \r\n\r\n)
  9828. char buf[4096];
  9829. size_t total = 0;
  9830. while (total < sizeof(buf)) {
  9831. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9832. if (n <= 0) break;
  9833. total += static_cast<size_t>(n);
  9834. // Check for end of headers
  9835. if (total >= 4) {
  9836. std::string req(buf, total);
  9837. if (req.find("\r\n\r\n") != std::string::npos) break;
  9838. }
  9839. }
  9840. // Malicious response: gzip-compressed body, no Content-Length
  9841. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9842. "Content-Encoding: gzip\r\n"
  9843. "Connection: close\r\n"
  9844. "\r\n";
  9845. ::send(cli,
  9846. #ifdef _WIN32
  9847. static_cast<const char *>(response_header.c_str()),
  9848. static_cast<int>(response_header.size()),
  9849. #else
  9850. response_header.c_str(), response_header.size(),
  9851. #endif
  9852. 0);
  9853. // Send the compressed payload (small on the wire, huge when decompressed)
  9854. size_t total_sent = 0;
  9855. while (total_sent < compressed.size()) {
  9856. auto to_send = std::min(compressed.size() - total_sent,
  9857. static_cast<size_t>(64 * 1024));
  9858. auto sent =
  9859. ::send(cli,
  9860. #ifdef _WIN32
  9861. static_cast<const char *>(compressed.c_str() + total_sent),
  9862. static_cast<int>(to_send),
  9863. #else
  9864. compressed.c_str() + total_sent, to_send,
  9865. #endif
  9866. 0);
  9867. if (sent <= 0) break;
  9868. total_sent += static_cast<size_t>(sent);
  9869. }
  9870. detail::close_socket(cli);
  9871. }
  9872. });
  9873. auto se = detail::scope_exit([&] {
  9874. detail::close_socket(srv);
  9875. server_thread.join();
  9876. });
  9877. size_t total_decompressed = 0;
  9878. {
  9879. Client cli("127.0.0.1", PORT + 3);
  9880. cli.set_read_timeout(5, 0);
  9881. cli.set_decompress(true);
  9882. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9883. auto stream = cli.open_stream("GET", "/zipbomb");
  9884. ASSERT_TRUE(stream.is_valid());
  9885. char buffer[64 * 1024];
  9886. ssize_t n;
  9887. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9888. total_decompressed += static_cast<size_t>(n);
  9889. }
  9890. }
  9891. // The decompressed size must be capped by payload_max_length. Without
  9892. // protection, the client would decompress the full 10MB from a tiny
  9893. // compressed payload, enabling a zip bomb DoS attack.
  9894. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9895. << "Client decompressed " << total_decompressed
  9896. << " bytes from a gzip response. The decompressed size should be "
  9897. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9898. }
  9899. #endif
  9900. TEST(HostAndPortPropertiesTest, NoSSL) {
  9901. httplib::Client cli("www.google.com", 1234);
  9902. ASSERT_EQ("www.google.com", cli.host());
  9903. ASSERT_EQ(1234, cli.port());
  9904. }
  9905. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9906. httplib::Client cli("www.google.com:1234");
  9907. ASSERT_EQ("www.google.com", cli.host());
  9908. ASSERT_EQ(1234, cli.port());
  9909. }
  9910. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9911. // Port number that overflows int — should not crash, client becomes invalid
  9912. httplib::Client cli("http://www.google.com:99999999999999999999");
  9913. ASSERT_FALSE(cli.is_valid());
  9914. }
  9915. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9916. // Port 99999 exceeds valid range (1-65535) — should not crash
  9917. httplib::Client cli("http://www.google.com:99999");
  9918. ASSERT_FALSE(cli.is_valid());
  9919. }
  9920. #ifdef CPPHTTPLIB_SSL_ENABLED
  9921. TEST(HostAndPortPropertiesTest, SSL) {
  9922. httplib::SSLClient cli("www.google.com");
  9923. ASSERT_EQ("www.google.com", cli.host());
  9924. ASSERT_EQ(443, cli.port());
  9925. }
  9926. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9927. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9928. std::string cert;
  9929. read_file(CA_CERT_FILE, cert);
  9930. httplib::SSLClient httplib_client("www.google.com");
  9931. // Load CA store first time
  9932. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9933. // Load CA store second time (update)
  9934. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9935. // Verify client is still valid and can make connections
  9936. httplib_client.enable_server_certificate_verification(true);
  9937. auto res = httplib_client.Get("/");
  9938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9939. // Google may return 200 or 301 depending on various factors
  9940. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9941. res->status == StatusCode::MovedPermanently_301);
  9942. }
  9943. TEST(SSLClientTest, ServerNameIndication_Online) {
  9944. auto host = "httpbingo.org";
  9945. auto path = std::string{"/get"};
  9946. SSLClient cli(host, 443);
  9947. auto res = cli.Get(path);
  9948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9949. ASSERT_EQ(StatusCode::OK_200, res->status);
  9950. }
  9951. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9952. // Use a site that will cause SSL verification failure due to self-signed cert
  9953. SSLClient cli("self-signed.badssl.com", 443);
  9954. cli.enable_server_certificate_verification(true);
  9955. auto res = cli.Get("/");
  9956. ASSERT_TRUE(!res);
  9957. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9958. // Verify backend error is captured for SSLServerVerification
  9959. // This occurs when certificate verification fails
  9960. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9961. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9962. EXPECT_NE(0UL, res.ssl_backend_error());
  9963. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9964. // For OpenSSL, ssl_error is 0 for verification errors
  9965. EXPECT_EQ(0, res.ssl_error());
  9966. #if !defined(_WIN32) || \
  9967. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9968. // On non-Windows or when Windows Schannel is disabled, the error comes
  9969. // from OpenSSL's verification
  9970. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9971. res.ssl_backend_error());
  9972. #endif
  9973. #endif
  9974. }
  9975. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9976. // Use a site where hostname doesn't match the certificate
  9977. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9978. SSLClient cli("wrong.host.badssl.com", 443);
  9979. cli.enable_server_certificate_verification(true);
  9980. cli.enable_server_hostname_verification(true);
  9981. auto res = cli.Get("/");
  9982. ASSERT_TRUE(!res);
  9983. // The error type depends on when hostname verification occurs:
  9984. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9985. // - Mbed TLS: SSLServerVerification (during handshake)
  9986. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9987. res.error() == Error::SSLServerVerification);
  9988. // Verify backend error is captured for hostname verification failure
  9989. EXPECT_NE(0UL, res.ssl_backend_error());
  9990. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9991. // For OpenSSL, ssl_error is 0 for verification errors
  9992. EXPECT_EQ(0, res.ssl_error());
  9993. #if !defined(_WIN32) || \
  9994. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9995. // On non-Windows or when Windows Schannel is disabled, the error comes
  9996. // from OpenSSL's hostname verification
  9997. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9998. res.ssl_backend_error());
  9999. #endif
  10000. #endif
  10001. }
  10002. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10003. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10004. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10005. SSLClient cli("www.google.com", 443);
  10006. cli.enable_server_certificate_verification(true);
  10007. auto res = cli.Get("/");
  10008. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10009. }
  10010. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10011. SSLClient cli("www.google.com", 443);
  10012. cli.enable_server_certificate_verification(true);
  10013. cli.enable_windows_certificate_verification(false);
  10014. auto res = cli.Get("/");
  10015. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10016. }
  10017. #endif
  10018. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10019. Client cli("https://google.com");
  10020. auto res = cli.Get("/");
  10021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10022. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10023. }
  10024. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10025. SSLClient cli("google.com");
  10026. cli.set_ca_cert_path(CA_CERT_FILE);
  10027. auto res = cli.Get("/");
  10028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10029. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10030. }
  10031. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10032. SSLClient cli("google.com");
  10033. cli.enable_server_certificate_verification(true);
  10034. cli.set_ca_cert_path("hello");
  10035. auto res = cli.Get("/");
  10036. ASSERT_TRUE(!res);
  10037. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10038. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10039. // should be set
  10040. EXPECT_EQ(0, res.ssl_error());
  10041. // Verify backend error is captured for SSLLoadingCerts
  10042. // This error occurs when loading CA certificates fails
  10043. EXPECT_NE(0UL, res.ssl_backend_error());
  10044. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10045. // OpenSSL specific error codes:
  10046. // > openssl errstr 0x80000002
  10047. // error:80000002:system library::No such file or directory
  10048. // > openssl errstr 0xA000126
  10049. // error:0A000126:SSL routines::unexpected eof while reading
  10050. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10051. res.ssl_backend_error() == 0xA000126);
  10052. #endif
  10053. }
  10054. TEST(SSLClientTest, ServerCertificateVerification4) {
  10055. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10056. ASSERT_TRUE(svr.is_valid());
  10057. svr.Get("/test", [&](const Request &, Response &res) {
  10058. res.set_content("test", "text/plain");
  10059. svr.stop();
  10060. ASSERT_TRUE(true);
  10061. });
  10062. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10063. auto se = detail::scope_exit([&] {
  10064. t.join();
  10065. ASSERT_FALSE(svr.is_running());
  10066. });
  10067. svr.wait_until_ready();
  10068. SSLClient cli("127.0.0.1", PORT);
  10069. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10070. cli.enable_server_certificate_verification(true);
  10071. cli.set_connection_timeout(30);
  10072. auto res = cli.Get("/test");
  10073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10074. ASSERT_EQ(StatusCode::OK_200, res->status);
  10075. }
  10076. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10077. std::string cert;
  10078. read_file(CA_CERT_FILE, cert);
  10079. SSLClient cli("google.com");
  10080. cli.load_ca_cert_store(cert.data(), cert.size());
  10081. const auto res = cli.Get("/");
  10082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10083. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10084. }
  10085. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10086. // clang-format off
  10087. static constexpr char cert[] =
  10088. "GlobalSign Root CA\n"
  10089. "==================\n"
  10090. "-----BEGIN CERTIFICATE-----\n"
  10091. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10092. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10093. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10094. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10095. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10096. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10097. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10098. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10099. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10100. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10101. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10102. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10103. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10104. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10105. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10106. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10107. "-----END CERTIFICATE-----\n";
  10108. // clang-format on
  10109. SSLClient cli("google.com");
  10110. cli.load_ca_cert_store(cert, sizeof(cert));
  10111. const auto res = cli.Get("/");
  10112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10113. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10114. }
  10115. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10116. SSLClient cli("www.youtube.com");
  10117. cli.set_ca_cert_path(CA_CERT_FILE);
  10118. cli.enable_server_certificate_verification(true);
  10119. cli.set_follow_location(true);
  10120. auto res = cli.Get("/");
  10121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10122. ASSERT_EQ(StatusCode::OK_200, res->status);
  10123. }
  10124. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10125. SSLClient cli("wWw.YouTube.Com");
  10126. cli.set_ca_cert_path(CA_CERT_FILE);
  10127. cli.enable_server_certificate_verification(true);
  10128. cli.enable_server_hostname_verification(true);
  10129. cli.set_follow_location(true);
  10130. auto res = cli.Get("/");
  10131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10132. ASSERT_EQ(StatusCode::OK_200, res->status);
  10133. }
  10134. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10135. SSLClient cli("gOoGlE.COm");
  10136. cli.enable_server_certificate_verification(true);
  10137. cli.enable_server_hostname_verification(true);
  10138. cli.set_follow_location(true);
  10139. auto res = cli.Get("/");
  10140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10141. ASSERT_EQ(StatusCode::OK_200, res->status);
  10142. }
  10143. TEST(SSLClientTest, Issue2004_Online) {
  10144. Client client("https://google.com");
  10145. client.set_follow_location(true);
  10146. auto res = client.Get("/");
  10147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10148. ASSERT_EQ(StatusCode::OK_200, res->status);
  10149. auto body = res->body;
  10150. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10151. }
  10152. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10153. // Create SSLClient with invalid cert/key to make is_valid() return false
  10154. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10155. "nonexistent_key.pem");
  10156. // is_valid() should be false due to cert loading failure
  10157. ASSERT_FALSE(cli.is_valid());
  10158. auto res = cli.Get("/");
  10159. ASSERT_FALSE(res);
  10160. EXPECT_EQ(Error::SSLConnection, res.error());
  10161. }
  10162. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10163. // Test for Issue #2251: SSL error not properly reported when client cert
  10164. // and key paths are swapped or mismatched
  10165. // This simulates the scenario where user accidentally swaps the cert and key
  10166. // files
  10167. // Using client cert file as private key and vice versa (completely wrong)
  10168. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10169. // Should fail validation due to cert/key mismatch
  10170. ASSERT_FALSE(cli.is_valid());
  10171. // Attempt to make a request should fail with proper error
  10172. auto res = cli.Get("/");
  10173. ASSERT_FALSE(res);
  10174. EXPECT_EQ(Error::SSLConnection, res.error());
  10175. // SSL error should be recorded in the Result object (this is the key fix for
  10176. // Issue #2251)
  10177. auto backend_error = res.ssl_backend_error();
  10178. EXPECT_NE(0u, backend_error);
  10179. }
  10180. // Tests cert/key mismatch detection at the TLS context level
  10181. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10182. // Test that using mismatched cert/key causes connection failure.
  10183. // We verify this at the SSLClient level rather than through internal
  10184. // TLS API functions.
  10185. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10186. cli.enable_server_certificate_verification(false);
  10187. cli.set_connection_timeout(2);
  10188. // The mismatch should cause a connection or handshake error
  10189. auto res = cli.Get("/test");
  10190. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10191. // Either way, the request should fail
  10192. EXPECT_FALSE(res);
  10193. }
  10194. #endif
  10195. #if 0
  10196. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10197. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10198. ASSERT_TRUE(cli != nullptr);
  10199. cli->set_address_family(AF_INET6);
  10200. cli->set_interface("en0");
  10201. auto res = cli->Get("/get");
  10202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10203. ASSERT_EQ(StatusCode::OK_200, res->status);
  10204. }
  10205. #endif
  10206. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10207. #ifdef CPPHTTPLIB_SSL_ENABLED
  10208. void ClientCertPresent(
  10209. const std::string &client_cert_file,
  10210. const std::string &client_private_key_file,
  10211. const std::string &client_encrypted_private_key_pass = std::string()) {
  10212. using namespace httplib::tls;
  10213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10214. CLIENT_CA_CERT_DIR);
  10215. ASSERT_TRUE(svr.is_valid());
  10216. svr.Get("/test", [&](const Request &req, Response &res) {
  10217. res.set_content("test", "text/plain");
  10218. auto cert = req.peer_cert();
  10219. ASSERT_TRUE(static_cast<bool>(cert));
  10220. std::string common_name = cert.subject_cn();
  10221. EXPECT_EQ("Common Name", common_name);
  10222. });
  10223. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. ASSERT_FALSE(svr.is_running());
  10228. });
  10229. svr.wait_until_ready();
  10230. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10231. client_encrypted_private_key_pass);
  10232. cli.enable_server_certificate_verification(false);
  10233. cli.set_connection_timeout(30);
  10234. auto res = cli.Get("/test");
  10235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10236. ASSERT_EQ(StatusCode::OK_200, res->status);
  10237. }
  10238. TEST(SSLClientServerTest, ClientCertPresent) {
  10239. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10240. }
  10241. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10242. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10243. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10244. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10245. }
  10246. // PEM memory-based constructor tests (works with all TLS backends)
  10247. void PemMemoryClientCertPresent(
  10248. const std::string &client_cert_file,
  10249. const std::string &client_private_key_file,
  10250. const std::string &client_encrypted_private_key_pass = std::string()) {
  10251. // Read PEM files into memory
  10252. std::string server_cert_pem, server_key_pem;
  10253. std::string client_ca_pem;
  10254. std::string client_cert_pem, client_key_pem;
  10255. read_file(SERVER_CERT_FILE, server_cert_pem);
  10256. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10257. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10258. read_file(client_cert_file, client_cert_pem);
  10259. read_file(client_private_key_file, client_key_pem);
  10260. // Create server with PEM memory
  10261. SSLServer::PemMemory server_pem = {
  10262. server_cert_pem.c_str(),
  10263. server_cert_pem.size(),
  10264. server_key_pem.c_str(),
  10265. server_key_pem.size(),
  10266. client_ca_pem.c_str(),
  10267. client_ca_pem.size(),
  10268. nullptr // no password for server key
  10269. };
  10270. SSLServer svr(server_pem);
  10271. ASSERT_TRUE(svr.is_valid());
  10272. svr.Get("/test", [&](const Request &, Response &res) {
  10273. res.set_content("test", "text/plain");
  10274. });
  10275. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10276. auto se = detail::scope_exit([&] {
  10277. svr.stop();
  10278. t.join();
  10279. ASSERT_FALSE(svr.is_running());
  10280. });
  10281. svr.wait_until_ready();
  10282. // Create client with PEM memory
  10283. const char *password = client_encrypted_private_key_pass.empty()
  10284. ? nullptr
  10285. : client_encrypted_private_key_pass.c_str();
  10286. SSLClient::PemMemory client_pem = {
  10287. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10288. client_key_pem.size(), password};
  10289. SSLClient cli(HOST, PORT, client_pem);
  10290. cli.enable_server_certificate_verification(false);
  10291. cli.set_connection_timeout(30);
  10292. auto res = cli.Get("/test");
  10293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10294. ASSERT_EQ(StatusCode::OK_200, res->status);
  10295. }
  10296. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10297. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10298. }
  10299. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10300. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10301. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10302. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10303. }
  10304. TEST(SSLClientServerTest, ClientCertMissing) {
  10305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10306. CLIENT_CA_CERT_DIR);
  10307. ASSERT_TRUE(svr.is_valid());
  10308. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10310. auto se = detail::scope_exit([&] {
  10311. svr.stop();
  10312. t.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. SSLClient cli(HOST, PORT);
  10317. cli.set_connection_timeout(30);
  10318. auto res = cli.Get("/test");
  10319. ASSERT_TRUE(!res);
  10320. // When client cert is missing and server requires it, connection fails
  10321. // Error type depends on backend implementation
  10322. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10323. res.error() == Error::SSLConnection);
  10324. // Verify backend error is captured
  10325. // Note: This test may have different error codes depending on the exact
  10326. // verification failure
  10327. EXPECT_NE(0UL, res.ssl_backend_error());
  10328. }
  10329. TEST(SSLClientServerTest, TrustDirOptional) {
  10330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10331. ASSERT_TRUE(svr.is_valid());
  10332. svr.Get("/test", [&](const Request &, Response &res) {
  10333. res.set_content("test", "text/plain");
  10334. });
  10335. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. t.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10343. cli.enable_server_certificate_verification(false);
  10344. cli.set_connection_timeout(30);
  10345. auto res = cli.Get("/test");
  10346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10347. ASSERT_EQ(StatusCode::OK_200, res->status);
  10348. }
  10349. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10350. class NoListenSSLServer : public SSLServer {
  10351. public:
  10352. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10353. const char *client_ca_cert_file_path,
  10354. const char *client_ca_cert_dir_path = nullptr)
  10355. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10356. client_ca_cert_dir_path),
  10357. stop_(false) {}
  10358. std::atomic_bool stop_;
  10359. private:
  10360. bool process_and_close_socket(socket_t /*sock*/) override {
  10361. // Don't create SSL context
  10362. while (!stop_.load()) {
  10363. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10364. }
  10365. return true;
  10366. }
  10367. };
  10368. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10369. CLIENT_CA_CERT_FILE);
  10370. ASSERT_TRUE(svr.is_valid());
  10371. svr.Get("/test", [&](const Request &, Response &res) {
  10372. res.set_content("test", "text/plain");
  10373. });
  10374. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10375. auto se = detail::scope_exit([&] {
  10376. svr.stop_ = true;
  10377. svr.stop();
  10378. t.join();
  10379. ASSERT_FALSE(svr.is_running());
  10380. });
  10381. svr.wait_until_ready();
  10382. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10383. cli.enable_server_certificate_verification(false);
  10384. cli.set_connection_timeout(1);
  10385. auto res = cli.Get("/test");
  10386. ASSERT_TRUE(!res);
  10387. EXPECT_EQ(Error::SSLConnection, res.error());
  10388. // Timeout results in WantRead error code (maps to backend-specific value)
  10389. EXPECT_NE(0, res.ssl_error());
  10390. }
  10391. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10392. // Test SSLServer with client certificate verification using the standard
  10393. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10395. CLIENT_CA_CERT_DIR);
  10396. ASSERT_TRUE(svr.is_valid());
  10397. svr.Get("/test", [&](const Request &req, Response &res) {
  10398. res.set_content("test", "text/plain");
  10399. auto cert = req.peer_cert();
  10400. ASSERT_TRUE(static_cast<bool>(cert));
  10401. auto common_name = cert.subject_cn();
  10402. EXPECT_EQ("Common Name", common_name);
  10403. });
  10404. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10405. auto se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. t.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10412. cli.enable_server_certificate_verification(false);
  10413. cli.set_connection_timeout(30);
  10414. auto res = cli.Get("/test");
  10415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10416. ASSERT_EQ(StatusCode::OK_200, res->status);
  10417. }
  10418. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10419. // Verifies that wildcard matching and exact matching work consistently
  10420. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10421. using namespace httplib::tls;
  10422. // We need a running server to test against
  10423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10424. ASSERT_TRUE(svr.is_valid());
  10425. svr.Get("/test", [](const Request &, Response &res) {
  10426. res.set_content("ok", "text/plain");
  10427. });
  10428. thread t([&]() { svr.listen(HOST, PORT); });
  10429. auto se = detail::scope_exit([&] {
  10430. svr.stop();
  10431. t.join();
  10432. });
  10433. svr.wait_until_ready();
  10434. bool verify_callback_called = false;
  10435. bool verify_result_wrong = false;
  10436. SSLClient cli(HOST, PORT);
  10437. cli.enable_server_certificate_verification(true);
  10438. cli.set_ca_cert_path(CA_CERT_FILE);
  10439. cli.set_connection_timeout(5);
  10440. // Note: Test certificate has CN="Common Name", not "localhost"
  10441. bool verify_result_cn = false;
  10442. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10443. verify_callback_called = true;
  10444. if (!ctx.cert) return false;
  10445. // Test 1: "Common Name" should match (our test server cert CN)
  10446. verify_result_cn = ctx.check_hostname("Common Name");
  10447. // Test 2: wrong hostname should not match
  10448. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10449. return true; // Accept for the purpose of this test
  10450. });
  10451. auto res = cli.Get("/test");
  10452. // The request may succeed or fail depending on cert configuration
  10453. // but the callback should have been called
  10454. ASSERT_TRUE(verify_callback_called)
  10455. << "Verify callback should have been called";
  10456. // CN="Common Name" should match our test certificate
  10457. //
  10458. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10459. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10460. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10461. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10462. // <openssl/base.h>, which is included transitively when
  10463. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10464. #if defined(OPENSSL_IS_BORINGSSL)
  10465. EXPECT_FALSE(verify_result_cn)
  10466. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10467. #else
  10468. EXPECT_TRUE(verify_result_cn)
  10469. << "verify_hostname should match 'Common Name' (certificate CN)";
  10470. #endif
  10471. // Wrong hostname should not match
  10472. EXPECT_FALSE(verify_result_wrong)
  10473. << "verify_hostname should not match 'wronghost.example.com'";
  10474. }
  10475. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10476. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10477. // X509_check_ip behavior and must hold for every backend.
  10478. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10479. using namespace httplib::tls;
  10480. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10481. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10482. ASSERT_TRUE(svr.is_valid());
  10483. svr.Get("/test", [](const Request &, Response &res) {
  10484. res.set_content("ok", "text/plain");
  10485. });
  10486. thread t([&]() { svr.listen(HOST, PORT); });
  10487. auto se = detail::scope_exit([&] {
  10488. svr.stop();
  10489. t.join();
  10490. });
  10491. svr.wait_until_ready();
  10492. bool verify_callback_called = false;
  10493. bool ip_matched_via_cn = true;
  10494. SSLClient cli(HOST, PORT);
  10495. cli.enable_server_certificate_verification(true);
  10496. cli.set_ca_cert_path(CA_CERT_FILE);
  10497. cli.set_connection_timeout(5);
  10498. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10499. verify_callback_called = true;
  10500. if (!ctx.cert) return false;
  10501. // The IP appears only in the CN, so it must NOT be accepted.
  10502. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10503. return true; // Accept for the purpose of this test
  10504. });
  10505. cli.Get("/test");
  10506. ASSERT_TRUE(verify_callback_called)
  10507. << "Verify callback should have been called";
  10508. EXPECT_FALSE(ip_matched_via_cn)
  10509. << "An IP host must not be authenticated via the certificate CN";
  10510. }
  10511. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10512. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10513. using namespace httplib::tls;
  10514. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10515. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10516. ASSERT_TRUE(svr.is_valid());
  10517. svr.Get("/test", [](const Request &, Response &res) {
  10518. res.set_content("ok", "text/plain");
  10519. });
  10520. thread t([&]() { svr.listen(HOST, PORT); });
  10521. auto se = detail::scope_exit([&] {
  10522. svr.stop();
  10523. t.join();
  10524. });
  10525. svr.wait_until_ready();
  10526. bool verify_callback_called = false;
  10527. bool san_matched = false;
  10528. bool wrong_ipv6_matched = true;
  10529. bool cn_ipv6_matched = true;
  10530. SSLClient cli(HOST, PORT);
  10531. cli.enable_server_certificate_verification(true);
  10532. cli.set_ca_cert_path(CA_CERT_FILE);
  10533. cli.set_connection_timeout(5);
  10534. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10535. verify_callback_called = true;
  10536. if (!ctx.cert) return false;
  10537. // Matches the IPv6 iPAddress SAN.
  10538. san_matched = ctx.check_hostname("2001:db8::1");
  10539. // A different IPv6 address must not match.
  10540. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10541. // "::1" lives only in the CN, so it must not be accepted.
  10542. cn_ipv6_matched = ctx.check_hostname("::1");
  10543. return true; // Accept for the purpose of this test
  10544. });
  10545. cli.Get("/test");
  10546. ASSERT_TRUE(verify_callback_called)
  10547. << "Verify callback should have been called";
  10548. EXPECT_TRUE(san_matched)
  10549. << "verify_hostname should match an IPv6 iPAddress SAN";
  10550. EXPECT_FALSE(wrong_ipv6_matched)
  10551. << "verify_hostname should not match a non-matching IPv6 address";
  10552. EXPECT_FALSE(cn_ipv6_matched)
  10553. << "An IPv6 host must not be authenticated via the certificate CN";
  10554. }
  10555. #endif
  10556. // mbedTLS-specific callback constructor test
  10557. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10558. #ifdef CPPHTTPLIB_SSL_ENABLED
  10559. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10561. ASSERT_TRUE(svr.is_valid());
  10562. // Set up a handler to verify client certificate is present
  10563. bool client_cert_verified = false;
  10564. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10565. // Verify that client certificate was provided
  10566. client_cert_verified = true;
  10567. res.set_content("success", "text/plain");
  10568. });
  10569. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10570. auto se = detail::scope_exit([&] {
  10571. svr.stop();
  10572. t.join();
  10573. ASSERT_FALSE(svr.is_running());
  10574. });
  10575. svr.wait_until_ready();
  10576. // Client with certificate
  10577. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10578. cli.enable_server_certificate_verification(false);
  10579. cli.set_connection_timeout(30);
  10580. auto res = cli.Get("/test");
  10581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10582. ASSERT_EQ(StatusCode::OK_200, res->status);
  10583. ASSERT_TRUE(client_cert_verified);
  10584. EXPECT_EQ("success", res->body);
  10585. }
  10586. #endif
  10587. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10588. // backends
  10589. #ifdef CPPHTTPLIB_SSL_ENABLED
  10590. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10591. using namespace httplib::tls;
  10592. // Test that when client CA cert file is provided,
  10593. // the server properly requests and validates client certificates
  10594. // Create a server with client authentication
  10595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10596. ASSERT_TRUE(svr.is_valid());
  10597. bool handler_called = false;
  10598. svr.Get("/test", [&](const Request &req, Response &res) {
  10599. handler_called = true;
  10600. // Verify that a client certificate was provided
  10601. auto cert = req.peer_cert();
  10602. ASSERT_TRUE(static_cast<bool>(cert));
  10603. // Get the issuer name
  10604. std::string issuer_str = cert.issuer_name();
  10605. ASSERT_FALSE(issuer_str.empty());
  10606. // The client certificate should be issued by our test CA
  10607. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10608. res.set_content("authenticated", "text/plain");
  10609. });
  10610. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10611. auto se = detail::scope_exit([&] {
  10612. svr.stop();
  10613. t.join();
  10614. ASSERT_FALSE(svr.is_running());
  10615. });
  10616. svr.wait_until_ready();
  10617. // Connect with a client certificate issued by the CA
  10618. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10619. cli.enable_server_certificate_verification(false);
  10620. cli.set_connection_timeout(30);
  10621. auto res = cli.Get("/test");
  10622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10623. ASSERT_EQ(StatusCode::OK_200, res->status);
  10624. ASSERT_TRUE(handler_called);
  10625. EXPECT_EQ("authenticated", res->body);
  10626. }
  10627. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10628. using namespace httplib::tls;
  10629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10630. ASSERT_TRUE(svr.is_valid());
  10631. svr.Get("/test", [](const Request &, Response &res) {
  10632. res.set_content("ok", "text/plain");
  10633. });
  10634. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10635. auto se = detail::scope_exit([&] {
  10636. svr.stop();
  10637. t.join();
  10638. });
  10639. svr.wait_until_ready();
  10640. SSLClient cli(HOST, PORT);
  10641. cli.enable_server_certificate_verification(false);
  10642. cli.set_connection_timeout(30);
  10643. bool cert_checked = false;
  10644. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10645. if (ctx.cert) {
  10646. auto sans = ctx.sans();
  10647. // Test certificate may or may not have SANs - just verify the API
  10648. // works If SANs exist, verify the types are valid
  10649. for (const auto &san : sans) {
  10650. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10651. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10652. san.type == SanType::OTHER);
  10653. EXPECT_FALSE(san.value.empty());
  10654. }
  10655. cert_checked = true;
  10656. }
  10657. return true;
  10658. });
  10659. auto res = cli.Get("/test");
  10660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10661. EXPECT_TRUE(cert_checked);
  10662. }
  10663. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10664. using namespace httplib::tls;
  10665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10666. ASSERT_TRUE(svr.is_valid());
  10667. svr.Get("/test", [](const Request &, Response &res) {
  10668. res.set_content("ok", "text/plain");
  10669. });
  10670. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10671. auto se = detail::scope_exit([&] {
  10672. svr.stop();
  10673. t.join();
  10674. });
  10675. svr.wait_until_ready();
  10676. SSLClient cli(HOST, PORT);
  10677. cli.enable_server_certificate_verification(false);
  10678. cli.set_connection_timeout(30);
  10679. bool validity_checked = false;
  10680. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10681. if (ctx.cert) {
  10682. time_t not_before = 0, not_after = 0;
  10683. bool result = ctx.validity(not_before, not_after);
  10684. EXPECT_TRUE(result);
  10685. // Verify that not_before < now < not_after for a valid cert
  10686. time_t now = time(nullptr);
  10687. EXPECT_LT(not_before, now);
  10688. EXPECT_GT(not_after, now);
  10689. validity_checked = true;
  10690. }
  10691. return true;
  10692. });
  10693. auto res = cli.Get("/test");
  10694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10695. EXPECT_TRUE(validity_checked);
  10696. }
  10697. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10698. using namespace httplib::tls;
  10699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10700. ASSERT_TRUE(svr.is_valid());
  10701. svr.Get("/test", [](const Request &, Response &res) {
  10702. res.set_content("ok", "text/plain");
  10703. });
  10704. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10705. auto se = detail::scope_exit([&] {
  10706. svr.stop();
  10707. t.join();
  10708. });
  10709. svr.wait_until_ready();
  10710. SSLClient cli(HOST, PORT);
  10711. cli.enable_server_certificate_verification(false);
  10712. cli.set_connection_timeout(30);
  10713. bool serial_checked = false;
  10714. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10715. if (ctx.cert) {
  10716. std::string serial = ctx.serial();
  10717. EXPECT_FALSE(serial.empty());
  10718. // Serial should be a hex string
  10719. for (char c : serial) {
  10720. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10721. (c >= 'a' && c <= 'f'));
  10722. }
  10723. serial_checked = true;
  10724. }
  10725. return true;
  10726. });
  10727. auto res = cli.Get("/test");
  10728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10729. EXPECT_TRUE(serial_checked);
  10730. }
  10731. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10732. // Test 1: Valid CA file - no error should be recorded
  10733. {
  10734. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10735. CLIENT_CA_CERT_FILE);
  10736. ASSERT_TRUE(svr.is_valid());
  10737. // With valid setup, last_ssl_error should be 0
  10738. EXPECT_EQ(0, svr.ssl_last_error());
  10739. }
  10740. // Test 2: Invalid CA file content
  10741. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10742. {
  10743. // Create a temporary file with completely invalid content
  10744. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10745. {
  10746. std::ofstream ofs(temp_invalid_ca);
  10747. ofs << "This is not a certificate file at all\n";
  10748. ofs << "Just plain text content\n";
  10749. }
  10750. // Create server with invalid CA file
  10751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10752. // Clean up temporary file
  10753. std::remove(temp_invalid_ca);
  10754. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10755. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10756. // Note: SSL_CTX_load_verify_locations typically fails first,
  10757. // but our error handling code path is still exercised
  10758. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10759. }
  10760. }
  10761. TEST(VerifyCallbackTest, VerifyContextFields) {
  10762. using namespace httplib::tls;
  10763. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10764. ASSERT_TRUE(svr.is_valid());
  10765. svr.Get("/test", [](const Request &, Response &res) {
  10766. res.set_content("ok", "text/plain");
  10767. });
  10768. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10769. auto se = detail::scope_exit([&] {
  10770. svr.stop();
  10771. t.join();
  10772. });
  10773. svr.wait_until_ready();
  10774. SSLClient cli(HOST, PORT);
  10775. cli.enable_server_certificate_verification(false);
  10776. cli.set_connection_timeout(30);
  10777. int callback_count = 0;
  10778. bool saw_leaf_cert = false;
  10779. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10780. if (ctx.cert) {
  10781. callback_count++;
  10782. // We should see at least one certificate (the leaf)
  10783. std::string cn = ctx.subject_cn();
  10784. if (!cn.empty()) { saw_leaf_cert = true; }
  10785. // Verify context fields are populated
  10786. EXPECT_NE(ctx.session, nullptr);
  10787. EXPECT_GE(ctx.depth, 0);
  10788. }
  10789. return true;
  10790. });
  10791. auto res = cli.Get("/test");
  10792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10793. EXPECT_GT(callback_count, 0);
  10794. EXPECT_TRUE(saw_leaf_cert);
  10795. }
  10796. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10797. using httplib::tls::TlsError;
  10798. // Test that verify_error_to_string returns empty for success
  10799. std::string success_str = TlsError::verify_error_to_string(0);
  10800. EXPECT_TRUE(success_str.empty());
  10801. // Test that verify_error_to_string returns non-empty for error codes
  10802. // Using a common error code (certificate expired)
  10803. std::string error_str =
  10804. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10805. EXPECT_FALSE(error_str.empty());
  10806. }
  10807. TEST(SessionVerifierTest, CertificateAccepted) {
  10808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10809. ASSERT_TRUE(svr.is_valid());
  10810. svr.Get("/test", [](const Request &, Response &res) {
  10811. res.set_content("ok", "text/plain");
  10812. });
  10813. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10814. auto se = detail::scope_exit([&] {
  10815. svr.stop();
  10816. t.join();
  10817. });
  10818. svr.wait_until_ready();
  10819. SSLClient cli(HOST, PORT);
  10820. cli.enable_server_certificate_verification(false);
  10821. cli.set_connection_timeout(30);
  10822. bool callback_called = false;
  10823. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10824. EXPECT_NE(session, nullptr);
  10825. callback_called = true;
  10826. return SSLVerifierResponse::CertificateAccepted;
  10827. });
  10828. auto res = cli.Get("/test");
  10829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10830. EXPECT_EQ(200, res->status);
  10831. EXPECT_TRUE(callback_called);
  10832. }
  10833. TEST(SessionVerifierTest, CertificateRejected) {
  10834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10835. ASSERT_TRUE(svr.is_valid());
  10836. svr.Get("/test", [](const Request &, Response &res) {
  10837. res.set_content("ok", "text/plain");
  10838. });
  10839. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. t.join();
  10843. });
  10844. svr.wait_until_ready();
  10845. SSLClient cli(HOST, PORT);
  10846. cli.enable_server_certificate_verification(false);
  10847. cli.set_connection_timeout(30);
  10848. bool callback_called = false;
  10849. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10850. EXPECT_NE(session, nullptr);
  10851. callback_called = true;
  10852. return SSLVerifierResponse::CertificateRejected;
  10853. });
  10854. auto res = cli.Get("/test");
  10855. EXPECT_FALSE(res);
  10856. EXPECT_TRUE(callback_called);
  10857. }
  10858. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10860. ASSERT_TRUE(svr.is_valid());
  10861. svr.Get("/test", [](const Request &, Response &res) {
  10862. res.set_content("ok", "text/plain");
  10863. });
  10864. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop();
  10867. t.join();
  10868. });
  10869. svr.wait_until_ready();
  10870. // NoDecisionMade with verification disabled should succeed (no default check)
  10871. SSLClient cli(HOST, PORT);
  10872. cli.enable_server_certificate_verification(false);
  10873. cli.set_connection_timeout(30);
  10874. bool callback_called = false;
  10875. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10876. EXPECT_NE(session, nullptr);
  10877. callback_called = true;
  10878. return SSLVerifierResponse::NoDecisionMade;
  10879. });
  10880. auto res = cli.Get("/test");
  10881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10882. EXPECT_EQ(200, res->status);
  10883. EXPECT_TRUE(callback_called);
  10884. }
  10885. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10887. ASSERT_TRUE(svr.is_valid());
  10888. svr.Get("/test", [](const Request &, Response &res) {
  10889. res.set_content("ok", "text/plain");
  10890. });
  10891. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. t.join();
  10895. });
  10896. svr.wait_until_ready();
  10897. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10898. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10899. // so we only check that the request fails, not whether the callback was
  10900. // called.
  10901. SSLClient cli(HOST, PORT);
  10902. cli.enable_server_certificate_verification(true);
  10903. cli.set_connection_timeout(30);
  10904. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10905. EXPECT_NE(session, nullptr);
  10906. return SSLVerifierResponse::NoDecisionMade;
  10907. });
  10908. auto res = cli.Get("/test");
  10909. EXPECT_FALSE(res);
  10910. }
  10911. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10912. // Test SSL server using PemMemory constructor with client CA certificates
  10913. // Read PEM files
  10914. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10915. read_file(SERVER_CERT_FILE, server_cert_pem);
  10916. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10917. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10918. // Create SSLServer with PemMemory constructor including client CA
  10919. SSLServer::PemMemory server_pem = {
  10920. server_cert_pem.c_str(),
  10921. server_cert_pem.size(),
  10922. server_key_pem.c_str(),
  10923. server_key_pem.size(),
  10924. client_ca_pem.c_str(),
  10925. client_ca_pem.size(),
  10926. nullptr // no password for server key
  10927. };
  10928. SSLServer svr(server_pem);
  10929. ASSERT_TRUE(svr.is_valid());
  10930. // No SSL error should be recorded for valid setup
  10931. EXPECT_EQ(0, svr.ssl_last_error());
  10932. // Set up server endpoints
  10933. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10934. res.set_content("ok", "text/plain");
  10935. });
  10936. // Start server in a thread
  10937. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10938. svr.wait_until_ready();
  10939. // Connect with client certificate (using constructor with paths)
  10940. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10941. cli.enable_server_certificate_verification(false);
  10942. auto res = cli.Get("/test-pem-ca");
  10943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10944. EXPECT_EQ(200, res->status);
  10945. EXPECT_EQ("ok", res->body);
  10946. svr.stop();
  10947. server_thread.join();
  10948. }
  10949. #endif
  10950. #ifdef _WIN32
  10951. TEST(CleanupTest, WSACleanup) {
  10952. int ret = WSACleanup();
  10953. ASSERT_EQ(0, ret);
  10954. }
  10955. #endif
  10956. #ifndef CPPHTTPLIB_SSL_ENABLED
  10957. TEST(NoSSLSupport, SimpleInterface) {
  10958. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10959. }
  10960. #endif
  10961. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10962. TEST(InvalidScheme, SimpleInterface) {
  10963. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10964. }
  10965. #endif
  10966. TEST(NoScheme, SimpleInterface) {
  10967. Client cli("yahoo.com:80");
  10968. ASSERT_TRUE(cli.is_valid());
  10969. }
  10970. TEST(SendAPI, SimpleInterface_Online) {
  10971. Client cli("http://yahoo.com");
  10972. Request req;
  10973. req.method = "GET";
  10974. req.path = "/";
  10975. auto res = cli.send(req);
  10976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10977. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10978. }
  10979. TEST(SendAPI, WithParamsInRequest) {
  10980. Server svr;
  10981. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10982. EXPECT_TRUE(req.has_param("test"));
  10983. EXPECT_EQ("test_value", req.get_param_value("test"));
  10984. });
  10985. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10986. auto se = detail::scope_exit([&] {
  10987. svr.stop();
  10988. t.join();
  10989. ASSERT_FALSE(svr.is_running());
  10990. });
  10991. svr.wait_until_ready();
  10992. Client cli(HOST, PORT);
  10993. {
  10994. Request req;
  10995. req.method = "GET";
  10996. req.path = "/";
  10997. req.params.emplace("test", "test_value");
  10998. auto res = cli.send(req);
  10999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11000. }
  11001. {
  11002. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11004. }
  11005. }
  11006. TEST(ClientImplMethods, GetSocketTest) {
  11007. httplib::Server svr;
  11008. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11009. res.status = StatusCode::OK_200;
  11010. });
  11011. auto port = svr.bind_to_any_port("127.0.0.1");
  11012. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11013. auto se = detail::scope_exit([&] {
  11014. svr.stop();
  11015. thread.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. });
  11018. svr.wait_until_ready();
  11019. {
  11020. httplib::Client cli("127.0.0.1", port);
  11021. cli.set_keep_alive(true);
  11022. // Use the behavior of cpp-httplib of opening the connection
  11023. // only when the first request happens. If that changes,
  11024. // this test would be obsolete.
  11025. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11026. // This also implicitly tests the server. But other tests would fail much
  11027. // earlier than this one to be considered.
  11028. auto res = cli.Get("/");
  11029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11030. EXPECT_EQ(StatusCode::OK_200, res->status);
  11031. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11032. }
  11033. }
  11034. #ifdef CPPHTTPLIB_SSL_ENABLED
  11035. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11036. Client cli("http://yahoo.com");
  11037. auto res = cli.Get("/");
  11038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11039. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11040. cli.set_follow_location(true);
  11041. res = cli.Get("/");
  11042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11043. EXPECT_EQ(StatusCode::OK_200, res->status);
  11044. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11045. }
  11046. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11047. Client cli("https://yahoo.com");
  11048. auto res = cli.Get("/");
  11049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11050. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11051. cli.set_follow_location(true);
  11052. res = cli.Get("/");
  11053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11054. EXPECT_EQ(StatusCode::OK_200, res->status);
  11055. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11056. }
  11057. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11058. Client cli("https://yahoo.com");
  11059. auto res = cli.Get("/");
  11060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11061. ASSERT_FALSE(!res);
  11062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11063. ASSERT_FALSE(res == nullptr);
  11064. ASSERT_TRUE(res != nullptr);
  11065. EXPECT_EQ(Error::Success, res.error());
  11066. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11067. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11068. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11069. cli.set_follow_location(true);
  11070. res = cli.Get("/");
  11071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11072. EXPECT_EQ(Error::Success, res.error());
  11073. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11074. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11075. EXPECT_EQ(StatusCode::OK_200, res->status);
  11076. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11077. }
  11078. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11079. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11080. Client cli("https://cdnjs.cloudflare.com");
  11081. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11082. Headers{{"Accept-Encoding", "br"}});
  11083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11084. EXPECT_EQ(StatusCode::OK_200, res->status);
  11085. EXPECT_EQ(287630U, res->body.size());
  11086. EXPECT_EQ("application/javascript; charset=utf-8",
  11087. res->get_header_value("Content-Type"));
  11088. }
  11089. #endif
  11090. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11091. #undef REDIR_HOST // Silence compiler warning
  11092. #define REDIR_HOST "https://httpbingo.org"
  11093. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11094. Client cli(REDIR_HOST);
  11095. cli.set_follow_location(true);
  11096. auto res =
  11097. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11099. EXPECT_EQ(StatusCode::OK_200, res->status);
  11100. }
  11101. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11102. Client cli(REDIR_HOST);
  11103. cli.set_follow_location(true);
  11104. Params params;
  11105. params.emplace("url", "http://example.com");
  11106. params.emplace("status_code", "302");
  11107. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11109. EXPECT_EQ(StatusCode::OK_200, res->status);
  11110. }
  11111. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11112. Client cli(REDIR_HOST);
  11113. cli.set_follow_location(true);
  11114. Params params;
  11115. params.emplace("url", "http://example.com");
  11116. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11118. EXPECT_EQ(StatusCode::OK_200, res->status);
  11119. }
  11120. TEST(HttpToHttpsRedirectTest, CertFile) {
  11121. auto ssl_port = PORT + 1;
  11122. Server svr;
  11123. ASSERT_TRUE(svr.is_valid());
  11124. svr.Get("/index", [&](const Request &, Response &res) {
  11125. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11126. "/index");
  11127. svr.stop();
  11128. });
  11129. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11130. ASSERT_TRUE(ssl_svr.is_valid());
  11131. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11132. res.set_content("test", "text/plain");
  11133. ssl_svr.stop();
  11134. });
  11135. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11136. thread t2 =
  11137. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11138. auto se = detail::scope_exit([&] {
  11139. t2.join();
  11140. t.join();
  11141. ASSERT_FALSE(svr.is_running());
  11142. });
  11143. svr.wait_until_ready();
  11144. ssl_svr.wait_until_ready();
  11145. Client cli("127.0.0.1", PORT);
  11146. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11147. cli.enable_server_certificate_verification(true);
  11148. cli.set_follow_location(true);
  11149. cli.set_connection_timeout(30);
  11150. auto res = cli.Get("/index");
  11151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11152. ASSERT_EQ(StatusCode::OK_200, res->status);
  11153. }
  11154. TEST(SSLClientRedirectTest, CertFile) {
  11155. auto ssl_port = PORT + 1;
  11156. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11157. ASSERT_TRUE(ssl_svr1.is_valid());
  11158. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11159. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11160. "/index");
  11161. ssl_svr1.stop();
  11162. });
  11163. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11164. ASSERT_TRUE(ssl_svr2.is_valid());
  11165. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11166. res.set_content("test", "text/plain");
  11167. ssl_svr2.stop();
  11168. });
  11169. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11170. thread t2 =
  11171. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11172. auto se = detail::scope_exit([&] {
  11173. t2.join();
  11174. t.join();
  11175. ASSERT_FALSE(ssl_svr1.is_running());
  11176. });
  11177. ssl_svr1.wait_until_ready();
  11178. ssl_svr2.wait_until_ready();
  11179. SSLClient cli("127.0.0.1", PORT);
  11180. std::string cert;
  11181. read_file(SERVER_CERT2_FILE, cert);
  11182. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11183. cli.enable_server_certificate_verification(true);
  11184. cli.set_follow_location(true);
  11185. cli.set_connection_timeout(30);
  11186. auto res = cli.Get("/index");
  11187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11188. ASSERT_EQ(StatusCode::OK_200, res->status);
  11189. }
  11190. #endif
  11191. #ifdef CPPHTTPLIB_SSL_ENABLED
  11192. // Test that set_ca_cert_store() skips system certs (consistent with
  11193. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11194. // should be trusted - system certs should NOT be loaded.
  11195. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11196. // Load a specific cert that is NOT a system CA cert
  11197. std::string cert;
  11198. read_file(SERVER_CERT2_FILE, cert);
  11199. SSLClient cli("google.com");
  11200. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11201. cli.enable_server_certificate_verification(true);
  11202. // This should FAIL because:
  11203. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11204. // 2. System certs should NOT be loaded when custom store is set
  11205. // If system certs WERE loaded, this would succeed
  11206. auto res = cli.Get("/");
  11207. ASSERT_FALSE(res);
  11208. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11209. }
  11210. // Same as above, but through the native store handle path. Regression test:
  11211. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11212. // merged system certs into the user-provided store.
  11213. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11214. std::string cert;
  11215. read_file(SERVER_CERT2_FILE, cert);
  11216. SSLClient cli("google.com");
  11217. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11218. cli.enable_server_certificate_verification(true);
  11219. auto res = cli.Get("/");
  11220. ASSERT_FALSE(res);
  11221. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11222. }
  11223. // A custom store set via the native handle must still verify a server whose
  11224. // cert it does contain.
  11225. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11226. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11227. ASSERT_TRUE(svr.is_valid());
  11228. svr.Get("/test", [&](const Request &, Response &res) {
  11229. res.set_content("test", "text/plain");
  11230. });
  11231. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11232. auto se = detail::scope_exit([&] {
  11233. svr.stop();
  11234. t.join();
  11235. ASSERT_FALSE(svr.is_running());
  11236. });
  11237. svr.wait_until_ready();
  11238. SSLClient cli("127.0.0.1", PORT);
  11239. std::string cert;
  11240. read_file(SERVER_CERT2_FILE, cert);
  11241. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11242. cli.enable_server_certificate_verification(true);
  11243. cli.set_connection_timeout(30);
  11244. auto res = cli.Get("/test");
  11245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11246. ASSERT_EQ(StatusCode::OK_200, res->status);
  11247. }
  11248. // CA certs loaded through the universal Client must be transferred to the
  11249. // client created internally for following an HTTPS redirect. Regression test:
  11250. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11251. // the CA data for redirect transfer.
  11252. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11253. auto ssl_port = PORT + 1;
  11254. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11255. ASSERT_TRUE(ssl_svr1.is_valid());
  11256. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11257. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11258. "/index");
  11259. });
  11260. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11261. ASSERT_TRUE(ssl_svr2.is_valid());
  11262. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11263. res.set_content("test", "text/plain");
  11264. });
  11265. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11266. thread t2 =
  11267. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11268. auto se = detail::scope_exit([&] {
  11269. ssl_svr2.stop();
  11270. ssl_svr1.stop();
  11271. t2.join();
  11272. t.join();
  11273. ASSERT_FALSE(ssl_svr1.is_running());
  11274. });
  11275. ssl_svr1.wait_until_ready();
  11276. ssl_svr2.wait_until_ready();
  11277. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11278. std::string cert;
  11279. read_file(SERVER_CERT2_FILE, cert);
  11280. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11281. cli.enable_server_certificate_verification(true);
  11282. cli.set_follow_location(true);
  11283. cli.set_connection_timeout(30);
  11284. auto res = cli.Get("/index");
  11285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11286. ASSERT_EQ(StatusCode::OK_200, res->status);
  11287. }
  11288. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11289. // so a host signed by a system CA verifies even though a custom CA is set
  11290. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11291. std::string cert;
  11292. read_file(SERVER_CERT2_FILE, cert);
  11293. SSLClient cli("google.com");
  11294. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11295. cli.enable_system_ca(true);
  11296. cli.enable_server_certificate_verification(true);
  11297. auto res = cli.Get("/");
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11300. }
  11301. // The custom CA remains effective when combined with the system CA
  11302. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11303. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11304. ASSERT_TRUE(svr.is_valid());
  11305. svr.Get("/test", [&](const Request &, Response &res) {
  11306. res.set_content("test", "text/plain");
  11307. });
  11308. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11309. auto se = detail::scope_exit([&] {
  11310. svr.stop();
  11311. t.join();
  11312. ASSERT_FALSE(svr.is_running());
  11313. });
  11314. svr.wait_until_ready();
  11315. SSLClient cli("127.0.0.1", PORT);
  11316. std::string cert;
  11317. read_file(SERVER_CERT2_FILE, cert);
  11318. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11319. cli.enable_system_ca(true);
  11320. cli.enable_server_certificate_verification(true);
  11321. cli.set_connection_timeout(30);
  11322. auto res = cli.Get("/test");
  11323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11324. ASSERT_EQ(StatusCode::OK_200, res->status);
  11325. }
  11326. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11327. // skip chain verification entirely (only the certificate identity was
  11328. // checked), so a server presenting an untrusted certificate with a matching
  11329. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11330. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11331. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11332. ASSERT_TRUE(svr.is_valid());
  11333. svr.Get("/test", [&](const Request &, Response &res) {
  11334. res.set_content("test", "text/plain");
  11335. });
  11336. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11337. auto se = detail::scope_exit([&] {
  11338. svr.stop();
  11339. t.join();
  11340. ASSERT_FALSE(svr.is_running());
  11341. });
  11342. svr.wait_until_ready();
  11343. SSLClient cli("127.0.0.1", PORT);
  11344. std::string cert;
  11345. // A trusted CA that did not sign the server certificate. The server cert
  11346. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11347. // this connection.
  11348. read_file(CLIENT_CA_CERT_FILE, cert);
  11349. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11350. cli.enable_server_certificate_verification(true);
  11351. cli.set_connection_timeout(30);
  11352. auto res = cli.Get("/test");
  11353. ASSERT_FALSE(res);
  11354. }
  11355. // enable_system_ca(false) prevents system CA loading entirely
  11356. TEST(SSLClientTest, DisableSystemCa_Online) {
  11357. SSLClient cli("google.com");
  11358. cli.enable_system_ca(false);
  11359. cli.enable_server_certificate_verification(true);
  11360. auto res = cli.Get("/");
  11361. ASSERT_FALSE(res);
  11362. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11363. // itself when the CA chain is empty
  11364. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11365. res.error() == Error::SSLConnection);
  11366. }
  11367. // The universal Client forwards enable_system_ca()
  11368. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11369. std::string cert;
  11370. read_file(SERVER_CERT2_FILE, cert);
  11371. Client cli("https://google.com");
  11372. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11373. cli.enable_system_ca(true);
  11374. cli.enable_server_certificate_verification(true);
  11375. auto res = cli.Get("/");
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11378. }
  11379. // The system CA policy must carry over to the client created internally for
  11380. // following a cross-host HTTPS redirect
  11381. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11382. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11383. ASSERT_TRUE(svr.is_valid());
  11384. svr.Get("/index", [&](const Request &, Response &res) {
  11385. res.set_redirect("https://www.google.com/");
  11386. });
  11387. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11388. auto se = detail::scope_exit([&] {
  11389. svr.stop();
  11390. t.join();
  11391. ASSERT_FALSE(svr.is_running());
  11392. });
  11393. svr.wait_until_ready();
  11394. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11395. std::string cert;
  11396. read_file(SERVER_CERT2_FILE, cert);
  11397. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11398. cli.enable_system_ca(true);
  11399. cli.enable_server_certificate_verification(true);
  11400. cli.set_follow_location(true);
  11401. cli.set_connection_timeout(30);
  11402. // Receiving any response proves the redirect client completed the TLS
  11403. // handshake with a system-CA-signed host
  11404. auto res = cli.Get("/index");
  11405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11406. }
  11407. TEST(MultipartFormDataTest, LargeData) {
  11408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11409. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11410. const ContentReader &content_reader) {
  11411. if (req.is_multipart_form_data()) {
  11412. std::vector<FormData> items;
  11413. content_reader(
  11414. [&](const FormData &file) {
  11415. items.push_back(file);
  11416. return true;
  11417. },
  11418. [&](const char *data, size_t data_length) {
  11419. items.back().content.append(data, data_length);
  11420. return true;
  11421. });
  11422. EXPECT_TRUE(std::string(items[0].name) == "document");
  11423. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11424. EXPECT_TRUE(items[0].filename == "2MB_data");
  11425. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11426. EXPECT_TRUE(items[1].name == "hello");
  11427. EXPECT_TRUE(items[1].content == "world");
  11428. EXPECT_TRUE(items[1].filename == "");
  11429. EXPECT_TRUE(items[1].content_type == "");
  11430. } else {
  11431. std::string body;
  11432. content_reader([&](const char *data, size_t data_length) {
  11433. body.append(data, data_length);
  11434. return true;
  11435. });
  11436. }
  11437. });
  11438. auto port = svr.bind_to_any_port(HOST);
  11439. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11440. auto se = detail::scope_exit([&] {
  11441. svr.stop();
  11442. t.join();
  11443. ASSERT_FALSE(svr.is_running());
  11444. });
  11445. svr.wait_until_ready();
  11446. {
  11447. std::string data(1024 * 1024 * 2, '.');
  11448. std::stringstream buffer;
  11449. buffer << data;
  11450. SSLClient cli(HOST, port);
  11451. cli.enable_server_certificate_verification(false);
  11452. UploadFormDataItems items{
  11453. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11454. {"hello", "world", "", ""},
  11455. };
  11456. auto res = cli.Post("/post", items);
  11457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11458. ASSERT_EQ(StatusCode::OK_200, res->status);
  11459. }
  11460. }
  11461. TEST(MultipartFormDataTest, DataProviderItems) {
  11462. std::random_device seed_gen;
  11463. std::mt19937 random(seed_gen());
  11464. std::string rand1;
  11465. rand1.resize(1000);
  11466. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11467. std::string rand2;
  11468. rand2.resize(3000);
  11469. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11471. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11472. const ContentReader &content_reader) {
  11473. ASSERT_FALSE(req.is_multipart_form_data());
  11474. std::string body;
  11475. content_reader([&](const char *data, size_t data_length) {
  11476. body.append(data, data_length);
  11477. return true;
  11478. });
  11479. EXPECT_EQ(body, "");
  11480. });
  11481. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11482. const ContentReader &content_reader) {
  11483. ASSERT_TRUE(req.is_multipart_form_data());
  11484. std::vector<FormData> items;
  11485. content_reader(
  11486. [&](const FormData &file) {
  11487. items.push_back(file);
  11488. return true;
  11489. },
  11490. [&](const char *data, size_t data_length) {
  11491. items.back().content.append(data, data_length);
  11492. return true;
  11493. });
  11494. ASSERT_TRUE(items.size() == 2);
  11495. EXPECT_EQ(std::string(items[0].name), "name1");
  11496. EXPECT_EQ(items[0].content, "Testing123");
  11497. EXPECT_EQ(items[0].filename, "filename1");
  11498. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11499. EXPECT_EQ(items[1].name, "name2");
  11500. EXPECT_EQ(items[1].content, "Testing456");
  11501. EXPECT_EQ(items[1].filename, "");
  11502. EXPECT_EQ(items[1].content_type, "");
  11503. });
  11504. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11505. const ContentReader &content_reader) {
  11506. ASSERT_TRUE(req.is_multipart_form_data());
  11507. std::vector<FormData> items;
  11508. content_reader(
  11509. [&](const FormData &file) {
  11510. items.push_back(file);
  11511. return true;
  11512. },
  11513. [&](const char *data, size_t data_length) {
  11514. items.back().content.append(data, data_length);
  11515. return true;
  11516. });
  11517. ASSERT_TRUE(items.size() == 2);
  11518. EXPECT_EQ(items[0].name, "name3");
  11519. EXPECT_EQ(items[0].content, rand1);
  11520. EXPECT_EQ(items[0].filename, "filename3");
  11521. EXPECT_EQ(items[0].content_type, "");
  11522. EXPECT_EQ(items[1].name, "name4");
  11523. EXPECT_EQ(items[1].content, rand2);
  11524. EXPECT_EQ(items[1].filename, "filename4");
  11525. EXPECT_EQ(items[1].content_type, "");
  11526. });
  11527. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11528. const ContentReader &content_reader) {
  11529. ASSERT_TRUE(req.is_multipart_form_data());
  11530. std::vector<FormData> items;
  11531. content_reader(
  11532. [&](const FormData &file) {
  11533. items.push_back(file);
  11534. return true;
  11535. },
  11536. [&](const char *data, size_t data_length) {
  11537. items.back().content.append(data, data_length);
  11538. return true;
  11539. });
  11540. ASSERT_TRUE(items.size() == 4);
  11541. EXPECT_EQ(std::string(items[0].name), "name1");
  11542. EXPECT_EQ(items[0].content, "Testing123");
  11543. EXPECT_EQ(items[0].filename, "filename1");
  11544. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11545. EXPECT_EQ(items[1].name, "name2");
  11546. EXPECT_EQ(items[1].content, "Testing456");
  11547. EXPECT_EQ(items[1].filename, "");
  11548. EXPECT_EQ(items[1].content_type, "");
  11549. EXPECT_EQ(items[2].name, "name3");
  11550. EXPECT_EQ(items[2].content, rand1);
  11551. EXPECT_EQ(items[2].filename, "filename3");
  11552. EXPECT_EQ(items[2].content_type, "");
  11553. EXPECT_EQ(items[3].name, "name4");
  11554. EXPECT_EQ(items[3].content, rand2);
  11555. EXPECT_EQ(items[3].filename, "filename4");
  11556. EXPECT_EQ(items[3].content_type, "");
  11557. });
  11558. auto port = svr.bind_to_any_port("localhost");
  11559. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11560. auto se = detail::scope_exit([&] {
  11561. svr.stop();
  11562. t.join();
  11563. ASSERT_FALSE(svr.is_running());
  11564. });
  11565. svr.wait_until_ready();
  11566. {
  11567. SSLClient cli("localhost", port);
  11568. cli.enable_server_certificate_verification(false);
  11569. UploadFormDataItems items{
  11570. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11571. {"name2", "Testing456", "", ""}, // not a file
  11572. };
  11573. {
  11574. auto res = cli.Post("/post-none", {}, {}, {});
  11575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11576. ASSERT_EQ(StatusCode::OK_200, res->status);
  11577. }
  11578. FormDataProviderItems providers;
  11579. {
  11580. auto res =
  11581. cli.Post("/post-items", {}, items, providers); // empty providers
  11582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11583. ASSERT_EQ(StatusCode::OK_200, res->status);
  11584. }
  11585. providers.push_back({"name3",
  11586. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11587. // test the offset is given correctly at each step
  11588. if (!offset)
  11589. sink.os.write(rand1.data(), 30);
  11590. else if (offset == 30)
  11591. sink.os.write(rand1.data() + 30, 300);
  11592. else if (offset == 330)
  11593. sink.os.write(rand1.data() + 330, 670);
  11594. else if (offset == rand1.size())
  11595. sink.done();
  11596. return true;
  11597. },
  11598. "filename3",
  11599. {}});
  11600. providers.push_back({"name4",
  11601. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11602. // test the offset is given correctly at each step
  11603. if (!offset)
  11604. sink.os.write(rand2.data(), 2000);
  11605. else if (offset == 2000)
  11606. sink.os.write(rand2.data() + 2000, 1);
  11607. else if (offset == 2001)
  11608. sink.os.write(rand2.data() + 2001, 999);
  11609. else if (offset == rand2.size())
  11610. sink.done();
  11611. return true;
  11612. },
  11613. "filename4",
  11614. {}});
  11615. {
  11616. auto res = cli.Post("/post-providers", {}, {}, providers);
  11617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11618. ASSERT_EQ(StatusCode::OK_200, res->status);
  11619. }
  11620. {
  11621. auto res = cli.Post("/post-both", {}, items, providers);
  11622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11623. ASSERT_EQ(StatusCode::OK_200, res->status);
  11624. }
  11625. }
  11626. }
  11627. TEST(MultipartFormDataTest, BadHeader) {
  11628. Server svr;
  11629. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11630. res.set_content("ok", "text/plain");
  11631. });
  11632. thread t = thread([&] { svr.listen(HOST, PORT); });
  11633. auto se = detail::scope_exit([&] {
  11634. svr.stop();
  11635. t.join();
  11636. ASSERT_FALSE(svr.is_running());
  11637. });
  11638. svr.wait_until_ready();
  11639. const std::string body =
  11640. "This is the preamble. It is to be ignored, though it\r\n"
  11641. "is a handy place for composition agents to include an\r\n"
  11642. "explanatory note to non-MIME conformant readers.\r\n"
  11643. "\r\n"
  11644. "\r\n"
  11645. "--simple boundary\r\n"
  11646. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11647. ": BAD...\r\n"
  11648. "\r\n"
  11649. "value1\r\n"
  11650. "--simple boundary\r\n"
  11651. "Content-Disposition: form-data; name=\"field2\"; "
  11652. "filename=\"example.txt\"\r\n"
  11653. "\r\n"
  11654. "value2\r\n"
  11655. "--simple boundary--\r\n"
  11656. "This is the epilogue. It is also to be ignored.\r\n";
  11657. std::string content_type =
  11658. R"(multipart/form-data; boundary="simple boundary")";
  11659. Client cli(HOST, PORT);
  11660. auto res = cli.Post("/post", body, content_type.c_str());
  11661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11663. }
  11664. TEST(MultipartFormDataTest, WithPreamble) {
  11665. Server svr;
  11666. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11667. res.set_content("ok", "text/plain");
  11668. });
  11669. thread t = thread([&] { svr.listen(HOST, PORT); });
  11670. auto se = detail::scope_exit([&] {
  11671. svr.stop();
  11672. t.join();
  11673. ASSERT_FALSE(svr.is_running());
  11674. });
  11675. svr.wait_until_ready();
  11676. const std::string body =
  11677. "This is the preamble. It is to be ignored, though it\r\n"
  11678. "is a handy place for composition agents to include an\r\n"
  11679. "explanatory note to non-MIME conformant readers.\r\n"
  11680. "\r\n"
  11681. "\r\n"
  11682. "--simple boundary\r\n"
  11683. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11684. "\r\n"
  11685. "value1\r\n"
  11686. "--simple boundary\r\n"
  11687. "Content-Disposition: form-data; name=\"field2\"; "
  11688. "filename=\"example.txt\"\r\n"
  11689. "\r\n"
  11690. "value2\r\n"
  11691. "--simple boundary--\r\n"
  11692. "This is the epilogue. It is also to be ignored.\r\n";
  11693. std::string content_type =
  11694. R"(multipart/form-data; boundary="simple boundary")";
  11695. Client cli(HOST, PORT);
  11696. auto res = cli.Post("/post", body, content_type.c_str());
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. EXPECT_EQ(StatusCode::OK_200, res->status);
  11699. }
  11700. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11702. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11703. const ContentReader &content_reader) {
  11704. if (req.is_multipart_form_data()) {
  11705. std::vector<FormData> items;
  11706. content_reader(
  11707. [&](const FormData &file) {
  11708. items.push_back(file);
  11709. return true;
  11710. },
  11711. [&](const char *data, size_t data_length) {
  11712. items.back().content.append(data, data_length);
  11713. return true;
  11714. });
  11715. EXPECT_TRUE(std::string(items[0].name) == "document");
  11716. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11717. EXPECT_TRUE(items[0].filename == "2MB_data");
  11718. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11719. EXPECT_TRUE(items[1].name == "hello");
  11720. EXPECT_TRUE(items[1].content == "world");
  11721. EXPECT_TRUE(items[1].filename == "");
  11722. EXPECT_TRUE(items[1].content_type == "");
  11723. } else {
  11724. std::string body;
  11725. content_reader([&](const char *data, size_t data_length) {
  11726. body.append(data, data_length);
  11727. return true;
  11728. });
  11729. }
  11730. });
  11731. auto port = svr.bind_to_any_port("localhost");
  11732. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11733. auto se = detail::scope_exit([&] {
  11734. svr.stop();
  11735. t.join();
  11736. ASSERT_FALSE(svr.is_running());
  11737. });
  11738. svr.wait_until_ready();
  11739. {
  11740. std::string data(1024 * 1024 * 2, '.');
  11741. std::stringstream buffer;
  11742. buffer << data;
  11743. SSLClient cli("localhost", port);
  11744. cli.enable_server_certificate_verification(false);
  11745. UploadFormDataItems items{
  11746. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11747. {"hello", "world", "", ""},
  11748. };
  11749. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11751. ASSERT_EQ(StatusCode::OK_200, res->status);
  11752. }
  11753. }
  11754. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11755. std::string data(1024 * 1024 * 2, '&');
  11756. std::stringstream buffer;
  11757. buffer << data;
  11758. Client cli("https://localhost:8080");
  11759. UploadFormDataItems items{
  11760. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11761. {"hello", "world", "", ""},
  11762. };
  11763. for (const char &c : " \t\r\n") {
  11764. auto res =
  11765. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11766. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11767. ASSERT_FALSE(res);
  11768. }
  11769. }
  11770. TEST(MultipartFormDataTest, PutFormData) {
  11771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11772. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11773. const ContentReader &content_reader) {
  11774. if (req.is_multipart_form_data()) {
  11775. std::vector<FormData> items;
  11776. content_reader(
  11777. [&](const FormData &file) {
  11778. items.push_back(file);
  11779. return true;
  11780. },
  11781. [&](const char *data, size_t data_length) {
  11782. items.back().content.append(data, data_length);
  11783. return true;
  11784. });
  11785. EXPECT_TRUE(std::string(items[0].name) == "document");
  11786. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11787. EXPECT_TRUE(items[0].filename == "2MB_data");
  11788. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11789. EXPECT_TRUE(items[1].name == "hello");
  11790. EXPECT_TRUE(items[1].content == "world");
  11791. EXPECT_TRUE(items[1].filename == "");
  11792. EXPECT_TRUE(items[1].content_type == "");
  11793. } else {
  11794. std::string body;
  11795. content_reader([&](const char *data, size_t data_length) {
  11796. body.append(data, data_length);
  11797. return true;
  11798. });
  11799. }
  11800. });
  11801. auto port = svr.bind_to_any_port("localhost");
  11802. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11803. auto se = detail::scope_exit([&] {
  11804. svr.stop();
  11805. t.join();
  11806. ASSERT_FALSE(svr.is_running());
  11807. });
  11808. svr.wait_until_ready();
  11809. {
  11810. std::string data(1024 * 1024 * 2, '&');
  11811. std::stringstream buffer;
  11812. buffer << data;
  11813. SSLClient cli("localhost", port);
  11814. cli.enable_server_certificate_verification(false);
  11815. UploadFormDataItems items{
  11816. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11817. {"hello", "world", "", ""},
  11818. };
  11819. auto res = cli.Put("/put", items);
  11820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11821. ASSERT_EQ(StatusCode::OK_200, res->status);
  11822. }
  11823. }
  11824. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11826. svr.Put("/put_customboundary",
  11827. [&](const Request &req, const Response & /*res*/,
  11828. const ContentReader &content_reader) {
  11829. if (req.is_multipart_form_data()) {
  11830. std::vector<FormData> items;
  11831. content_reader(
  11832. [&](const FormData &file) {
  11833. items.push_back(file);
  11834. return true;
  11835. },
  11836. [&](const char *data, size_t data_length) {
  11837. items.back().content.append(data, data_length);
  11838. return true;
  11839. });
  11840. EXPECT_TRUE(std::string(items[0].name) == "document");
  11841. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11842. EXPECT_TRUE(items[0].filename == "2MB_data");
  11843. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11844. EXPECT_TRUE(items[1].name == "hello");
  11845. EXPECT_TRUE(items[1].content == "world");
  11846. EXPECT_TRUE(items[1].filename == "");
  11847. EXPECT_TRUE(items[1].content_type == "");
  11848. } else {
  11849. std::string body;
  11850. content_reader([&](const char *data, size_t data_length) {
  11851. body.append(data, data_length);
  11852. return true;
  11853. });
  11854. }
  11855. });
  11856. auto port = svr.bind_to_any_port("localhost");
  11857. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11858. auto se = detail::scope_exit([&] {
  11859. svr.stop();
  11860. t.join();
  11861. ASSERT_FALSE(svr.is_running());
  11862. });
  11863. svr.wait_until_ready();
  11864. {
  11865. std::string data(1024 * 1024 * 2, '&');
  11866. std::stringstream buffer;
  11867. buffer << data;
  11868. SSLClient cli("localhost", port);
  11869. cli.enable_server_certificate_verification(false);
  11870. UploadFormDataItems items{
  11871. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11872. {"hello", "world", "", ""},
  11873. };
  11874. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. ASSERT_EQ(StatusCode::OK_200, res->status);
  11877. }
  11878. }
  11879. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11880. std::string data(1024 * 1024 * 2, '&');
  11881. std::stringstream buffer;
  11882. buffer << data;
  11883. Client cli("https://localhost:8080");
  11884. cli.enable_server_certificate_verification(false);
  11885. UploadFormDataItems items{
  11886. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11887. {"hello", "world", "", ""},
  11888. };
  11889. for (const char &c : " \t\r\n") {
  11890. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11891. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11892. ASSERT_FALSE(res);
  11893. }
  11894. }
  11895. TEST(MultipartFormDataTest, AlternateFilename) {
  11896. auto handled = false;
  11897. Server svr;
  11898. svr.Post("/test", [&](const Request &req, Response &res) {
  11899. ASSERT_EQ(2u, req.form.files.size());
  11900. ASSERT_EQ(1u, req.form.fields.size());
  11901. // Test files
  11902. const auto &file1 = req.form.get_file("file1");
  11903. ASSERT_EQ("file1", file1.name);
  11904. ASSERT_EQ("A.txt", file1.filename);
  11905. ASSERT_EQ("text/plain", file1.content_type);
  11906. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11907. const auto &file2 = req.form.get_file("file2");
  11908. ASSERT_EQ("file2", file2.name);
  11909. ASSERT_EQ("a.html", file2.filename);
  11910. ASSERT_EQ("text/html", file2.content_type);
  11911. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11912. file2.content);
  11913. // Test text field
  11914. const auto &text = req.form.get_field("text");
  11915. ASSERT_EQ("text default", text);
  11916. res.set_content("ok", "text/plain");
  11917. handled = true;
  11918. });
  11919. thread t = thread([&] { svr.listen(HOST, PORT); });
  11920. auto se = detail::scope_exit([&] {
  11921. svr.stop();
  11922. t.join();
  11923. ASSERT_FALSE(svr.is_running());
  11924. ASSERT_TRUE(handled);
  11925. });
  11926. svr.wait_until_ready();
  11927. auto req = "POST /test HTTP/1.1\r\n"
  11928. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11929. "Content-Length: 399\r\n"
  11930. "\r\n"
  11931. "----------\r\n"
  11932. "Content-Disposition: form-data; name=\"text\"\r\n"
  11933. "\r\n"
  11934. "text default\r\n"
  11935. "----------\r\n"
  11936. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11937. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11938. "Content-Type: text/plain\r\n"
  11939. "\r\n"
  11940. "Content of a.txt.\r\n"
  11941. "\r\n"
  11942. "----------\r\n"
  11943. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11944. "\"a.html\"\r\n"
  11945. "Content-Type: text/html\r\n"
  11946. "\r\n"
  11947. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11948. "\r\n"
  11949. "------------\r\n";
  11950. ASSERT_TRUE(send_request(1, req));
  11951. }
  11952. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11953. auto handled = false;
  11954. Server svr;
  11955. svr.Post("/test", [&](const Request &req, Response &res) {
  11956. // Case-insensitive "utf-8''" prefix with a long value
  11957. const auto &file = req.form.get_file("file1");
  11958. ASSERT_EQ("file1", file.name);
  11959. // 8000 chars exercises both the Content-Disposition parser and the
  11960. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11961. // Prior to the fix, std::regex_match on this header would cause O(N)
  11962. // stack recursion in libstdc++, leading to SIGSEGV.
  11963. std::string expected_filename(8000, 'A');
  11964. ASSERT_EQ(expected_filename, file.filename);
  11965. res.set_content("ok", "text/plain");
  11966. handled = true;
  11967. });
  11968. thread t = thread([&] { svr.listen(HOST, PORT); });
  11969. auto se = detail::scope_exit([&] {
  11970. svr.stop();
  11971. t.join();
  11972. ASSERT_FALSE(svr.is_running());
  11973. ASSERT_TRUE(handled);
  11974. });
  11975. svr.wait_until_ready();
  11976. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11977. // Regression test for GHSA-qq6v-r583-3h69
  11978. std::string long_filename(8000, 'A');
  11979. std::string body = "----------\r\n"
  11980. "Content-Disposition: form-data; name=\"file1\"; "
  11981. "filename*=\"Utf-8''" +
  11982. long_filename +
  11983. "\"\r\n"
  11984. "\r\n"
  11985. "hello\r\n"
  11986. "------------\r\n";
  11987. auto req = "POST /test HTTP/1.1\r\n"
  11988. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11989. "Content-Length: " +
  11990. std::to_string(body.size()) + "\r\n\r\n" + body;
  11991. ASSERT_TRUE(send_request(1, req));
  11992. }
  11993. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11994. auto handled = false;
  11995. Server svr;
  11996. svr.Post("/test", [&](const Request &req, Response &) {
  11997. ASSERT_EQ(2u, req.form.fields.size());
  11998. const auto &text1 = req.form.get_field("text1");
  11999. ASSERT_EQ("text1", text1);
  12000. const auto &text2 = req.form.get_field("text2");
  12001. ASSERT_EQ("text2", text2);
  12002. handled = true;
  12003. });
  12004. thread t = thread([&] { svr.listen(HOST, PORT); });
  12005. auto se = detail::scope_exit([&] {
  12006. svr.stop();
  12007. t.join();
  12008. ASSERT_FALSE(svr.is_running());
  12009. ASSERT_TRUE(handled);
  12010. });
  12011. svr.wait_until_ready();
  12012. auto req = "POST /test HTTP/1.1\r\n"
  12013. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12014. "Content-Length: 146\r\n"
  12015. "\r\n----------\r\n"
  12016. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12017. "\r\n"
  12018. "text1"
  12019. "\r\n----------\r\n"
  12020. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12021. "\r\n"
  12022. "text2"
  12023. "\r\n------------";
  12024. std::string response;
  12025. ASSERT_TRUE(send_request(1, req, &response));
  12026. ASSERT_EQ("200", response.substr(9, 3));
  12027. }
  12028. TEST(MultipartFormDataTest, ContentLength) {
  12029. auto handled = false;
  12030. Server svr;
  12031. svr.Post("/test", [&](const Request &req, Response &) {
  12032. ASSERT_EQ(2u, req.form.fields.size());
  12033. const auto &text1 = req.form.get_field("text1");
  12034. ASSERT_EQ("text1", text1);
  12035. const auto &text2 = req.form.get_field("text2");
  12036. ASSERT_EQ("text2", text2);
  12037. handled = true;
  12038. });
  12039. thread t = thread([&] { svr.listen(HOST, PORT); });
  12040. auto se = detail::scope_exit([&] {
  12041. svr.stop();
  12042. t.join();
  12043. ASSERT_FALSE(svr.is_running());
  12044. ASSERT_TRUE(handled);
  12045. });
  12046. svr.wait_until_ready();
  12047. auto req = "POST /test HTTP/1.1\r\n"
  12048. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12049. "Content-Length: 167\r\n"
  12050. "\r\n----------\r\n"
  12051. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12052. "Content-Length: 5\r\n"
  12053. "\r\n"
  12054. "text1"
  12055. "\r\n----------\r\n"
  12056. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12057. "\r\n"
  12058. "text2"
  12059. "\r\n------------\r\n";
  12060. std::string response;
  12061. ASSERT_TRUE(send_request(1, req, &response));
  12062. ASSERT_EQ("200", response.substr(9, 3));
  12063. }
  12064. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12065. auto handled = false;
  12066. Server svr;
  12067. svr.Post("/test", [&](const Request &req, Response &) {
  12068. ASSERT_EQ(2u, req.form.fields.size());
  12069. const auto &text1 = req.form.get_field("text1");
  12070. ASSERT_EQ("text1", text1);
  12071. // TODO: Add header access for text fields if needed
  12072. const auto &text2 = req.form.get_field("text2");
  12073. ASSERT_EQ("text2", text2);
  12074. // TODO: Header access for text fields needs to be implemented
  12075. // auto &headers = it->second.headers;
  12076. // ASSERT_EQ(3U, headers.size());
  12077. // auto custom_header = headers.find("x-whatever");
  12078. // ASSERT_TRUE(custom_header != headers.end());
  12079. // ASSERT_NE("customvalue", custom_header->second);
  12080. // ASSERT_EQ("CustomValue", custom_header->second);
  12081. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12082. handled = true;
  12083. });
  12084. thread t = thread([&] { svr.listen(HOST, PORT); });
  12085. auto se = detail::scope_exit([&] {
  12086. svr.stop();
  12087. t.join();
  12088. ASSERT_FALSE(svr.is_running());
  12089. ASSERT_TRUE(handled);
  12090. });
  12091. svr.wait_until_ready();
  12092. auto req = "POST /test HTTP/1.1\r\n"
  12093. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12094. "Content-Length: 232\r\n"
  12095. "\r\n----------\r\n"
  12096. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12097. "Content-Length: 5\r\n"
  12098. "X-Test: 1\r\n"
  12099. "\r\n"
  12100. "text1"
  12101. "\r\n----------\r\n"
  12102. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12103. "Content-Type: text/plain\r\n"
  12104. "X-Whatever: CustomValue\r\n"
  12105. "\r\n"
  12106. "text2"
  12107. "\r\n------------\r\n"
  12108. "That should be disregarded. Not even read";
  12109. std::string response;
  12110. ASSERT_TRUE(send_request(1, req, &response));
  12111. ASSERT_EQ("200", response.substr(9, 3));
  12112. }
  12113. TEST(MultipartFormDataTest, LargeHeader) {
  12114. auto handled = false;
  12115. Server svr;
  12116. svr.Post("/test", [&](const Request &req, Response &) {
  12117. ASSERT_EQ(1u, req.form.fields.size());
  12118. const auto &text = req.form.get_field("name1");
  12119. ASSERT_EQ("text1", text);
  12120. handled = true;
  12121. });
  12122. thread t = thread([&] { svr.listen(HOST, PORT); });
  12123. auto se = detail::scope_exit([&] {
  12124. svr.stop();
  12125. t.join();
  12126. ASSERT_FALSE(svr.is_running());
  12127. ASSERT_TRUE(handled);
  12128. });
  12129. svr.wait_until_ready();
  12130. auto boundary = std::string("cpp-httplib-multipart-data");
  12131. std::string content = "--" + boundary +
  12132. "\r\n"
  12133. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12134. "\r\n"
  12135. "text1\r\n"
  12136. "--" +
  12137. boundary + "--\r\n";
  12138. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12139. "Content-Type: multipart/form-data;boundary=" +
  12140. boundary +
  12141. "\r\n"
  12142. "Content-Length: " +
  12143. std::to_string(content.size()) +
  12144. "\r\n"
  12145. "Dummy-Header: ";
  12146. std::string header_suffix = "\r\n"
  12147. "\r\n";
  12148. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12149. size_t header_dummy_size =
  12150. read_buff_size -
  12151. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12152. auto header_dummy = std::string(header_dummy_size, '@');
  12153. auto req = header_prefix + header_dummy + header_suffix + content;
  12154. std::string response;
  12155. ASSERT_TRUE(send_request(1, req, &response));
  12156. ASSERT_EQ("200", response.substr(9, 3));
  12157. }
  12158. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12159. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12160. // (not chunked Transfer-Encoding) after the streaming refactor.
  12161. auto handled = false;
  12162. Server svr;
  12163. svr.Post("/upload", [&](const Request &req, Response &res) {
  12164. auto cl_it = req.headers.find("Content-Length");
  12165. EXPECT_TRUE(cl_it != req.headers.end());
  12166. auto te_it = req.headers.find("Transfer-Encoding");
  12167. EXPECT_TRUE(te_it == req.headers.end());
  12168. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12169. res.set_content("ok", "text/plain");
  12170. handled = true;
  12171. });
  12172. auto port = svr.bind_to_any_port(HOST);
  12173. auto t = thread([&] { svr.listen_after_bind(); });
  12174. auto se = detail::scope_exit([&] {
  12175. svr.stop();
  12176. t.join();
  12177. ASSERT_FALSE(svr.is_running());
  12178. ASSERT_TRUE(handled);
  12179. });
  12180. svr.wait_until_ready();
  12181. UploadFormDataItems items = {
  12182. {"field1", "hello", "", "text/plain"},
  12183. {"file1", "world", "test.txt", "application/octet-stream"},
  12184. };
  12185. Client cli(HOST, port);
  12186. auto res = cli.Post("/upload", {}, items);
  12187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12188. EXPECT_EQ(StatusCode::OK_200, res->status);
  12189. }
  12190. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12191. // Verify that make_multipart_content_provider coalesces many small segments
  12192. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12193. constexpr size_t kItemCount = 1000;
  12194. UploadFormDataItems items;
  12195. items.reserve(kItemCount);
  12196. for (size_t i = 0; i < kItemCount; i++) {
  12197. items.push_back(
  12198. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12199. }
  12200. const std::string boundary = "----test-boundary";
  12201. auto content_length = detail::get_multipart_content_length(items, boundary);
  12202. auto provider = detail::make_multipart_content_provider(items, boundary);
  12203. // Drive the provider the same way write_content_with_progress does
  12204. size_t write_count = 0;
  12205. size_t total_bytes = 0;
  12206. DataSink sink;
  12207. size_t offset = 0;
  12208. sink.write = [&](const char *d, size_t l) -> bool {
  12209. (void)d;
  12210. write_count++;
  12211. total_bytes += l;
  12212. offset += l;
  12213. return true;
  12214. };
  12215. sink.is_writable = []() -> bool { return true; };
  12216. while (offset < content_length) {
  12217. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12218. }
  12219. EXPECT_EQ(content_length, total_bytes);
  12220. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12221. // With buffering into 64KB blocks, write_count should be much smaller.
  12222. auto segment_count = 3 * kItemCount + 1;
  12223. EXPECT_LT(write_count, segment_count / 10);
  12224. }
  12225. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12226. // Integration test: send many UploadFormDataItems and verify the server
  12227. // receives all of them correctly (#2410).
  12228. constexpr size_t kItemCount = 500;
  12229. auto handled = false;
  12230. Server svr;
  12231. svr.Post("/upload", [&](const Request &req, Response &res) {
  12232. EXPECT_EQ(kItemCount, req.form.fields.size());
  12233. for (size_t i = 0; i < kItemCount; i++) {
  12234. auto key = "field" + std::to_string(i);
  12235. auto val = "value" + std::to_string(i);
  12236. auto it = req.form.fields.find(key);
  12237. if (it != req.form.fields.end()) {
  12238. EXPECT_EQ(val, it->second.content);
  12239. } else {
  12240. ADD_FAILURE() << "Missing field: " << key;
  12241. }
  12242. }
  12243. res.set_content("ok", "text/plain");
  12244. handled = true;
  12245. });
  12246. auto port = svr.bind_to_any_port(HOST);
  12247. auto t = thread([&] { svr.listen_after_bind(); });
  12248. auto se = detail::scope_exit([&] {
  12249. svr.stop();
  12250. t.join();
  12251. ASSERT_FALSE(svr.is_running());
  12252. ASSERT_TRUE(handled);
  12253. });
  12254. svr.wait_until_ready();
  12255. UploadFormDataItems items;
  12256. items.reserve(kItemCount);
  12257. for (size_t i = 0; i < kItemCount; i++) {
  12258. items.push_back(
  12259. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12260. }
  12261. Client cli(HOST, port);
  12262. auto res = cli.Post("/upload", items);
  12263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12264. EXPECT_EQ(StatusCode::OK_200, res->status);
  12265. }
  12266. TEST(MultipartFormDataTest, MakeFileProvider) {
  12267. // Verify make_file_provider sends a file's contents correctly.
  12268. const std::string file_content(4096, 'Z');
  12269. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12270. {
  12271. std::ofstream ofs(tmp_path, std::ios::binary);
  12272. ofs.write(file_content.data(),
  12273. static_cast<std::streamsize>(file_content.size()));
  12274. }
  12275. auto handled = false;
  12276. Server svr;
  12277. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12278. const ContentReader &content_reader) {
  12279. ASSERT_TRUE(req.is_multipart_form_data());
  12280. std::vector<FormData> items;
  12281. content_reader(
  12282. [&](const FormData &file) {
  12283. items.push_back(file);
  12284. return true;
  12285. },
  12286. [&](const char *data, size_t data_length) {
  12287. items.back().content.append(data, data_length);
  12288. return true;
  12289. });
  12290. ASSERT_EQ(1u, items.size());
  12291. EXPECT_EQ("myfile", items[0].name);
  12292. EXPECT_EQ("data.bin", items[0].filename);
  12293. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12294. EXPECT_EQ(file_content, items[0].content);
  12295. handled = true;
  12296. });
  12297. auto port = svr.bind_to_any_port(HOST);
  12298. auto t = thread([&] { svr.listen_after_bind(); });
  12299. auto se = detail::scope_exit([&] {
  12300. svr.stop();
  12301. t.join();
  12302. ASSERT_FALSE(svr.is_running());
  12303. ASSERT_TRUE(handled);
  12304. std::remove(tmp_path.c_str());
  12305. });
  12306. svr.wait_until_ready();
  12307. FormDataProviderItems providers;
  12308. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12309. "application/octet-stream"));
  12310. Client cli(HOST, port);
  12311. auto res = cli.Post("/upload", {}, {}, providers);
  12312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12313. EXPECT_EQ(StatusCode::OK_200, res->status);
  12314. }
  12315. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12316. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12317. // (100) headers is rejected with a 400 Bad Request response.
  12318. Server svr;
  12319. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12320. res.set_content("ok", "text/plain");
  12321. });
  12322. thread t = thread([&] { svr.listen(HOST, PORT); });
  12323. auto se = detail::scope_exit([&] {
  12324. svr.stop();
  12325. t.join();
  12326. ASSERT_FALSE(svr.is_running());
  12327. });
  12328. svr.wait_until_ready();
  12329. // Build a multipart part with 101 custom headers (exceeding
  12330. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12331. std::stringstream body;
  12332. body << "--simpleboundary\r\n"
  12333. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12334. for (int i = 0; i < 101; i++) {
  12335. body << "X-Custom-Header-" << i << ": value\r\n";
  12336. }
  12337. body << "\r\n"
  12338. << "value1\r\n"
  12339. << "--simpleboundary--\r\n";
  12340. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12341. Client cli(HOST, PORT);
  12342. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12344. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12345. }
  12346. TEST(MakeFileBodyTest, Basic) {
  12347. const std::string file_content(4096, 'Z');
  12348. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12349. {
  12350. std::ofstream ofs(tmp_path, std::ios::binary);
  12351. ofs.write(file_content.data(),
  12352. static_cast<std::streamsize>(file_content.size()));
  12353. }
  12354. auto handled = false;
  12355. Server svr;
  12356. svr.Post("/upload", [&](const Request &req, Response &res) {
  12357. EXPECT_EQ(file_content, req.body);
  12358. handled = true;
  12359. res.status = StatusCode::OK_200;
  12360. });
  12361. auto port = svr.bind_to_any_port(HOST);
  12362. auto t = thread([&] { svr.listen_after_bind(); });
  12363. auto se = detail::scope_exit([&] {
  12364. svr.stop();
  12365. t.join();
  12366. ASSERT_FALSE(svr.is_running());
  12367. ASSERT_TRUE(handled);
  12368. std::remove(tmp_path.c_str());
  12369. });
  12370. svr.wait_until_ready();
  12371. auto fb = make_file_body(tmp_path);
  12372. ASSERT_GT(fb.first, 0u);
  12373. Client cli(HOST, port);
  12374. auto res =
  12375. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12377. EXPECT_EQ(StatusCode::OK_200, res->status);
  12378. }
  12379. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12380. static constexpr unsigned int number_of_tasks{1000000};
  12381. std::atomic_uint count{0};
  12382. std::unique_ptr<TaskQueue> task_queue{
  12383. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12384. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12385. auto queued = task_queue->enqueue(
  12386. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12387. EXPECT_TRUE(queued);
  12388. }
  12389. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12390. task_queue->shutdown();
  12391. #else
  12392. EXPECT_NO_THROW(task_queue->shutdown());
  12393. #endif
  12394. EXPECT_EQ(number_of_tasks, count.load());
  12395. }
  12396. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12397. static constexpr unsigned int number_of_tasks{1000000};
  12398. static constexpr unsigned int qlimit{2};
  12399. unsigned int queued_count{0};
  12400. std::atomic_uint count{0};
  12401. std::unique_ptr<TaskQueue> task_queue{
  12402. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12403. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12404. if (task_queue->enqueue(
  12405. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12406. queued_count++;
  12407. }
  12408. }
  12409. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12410. task_queue->shutdown();
  12411. #else
  12412. EXPECT_NO_THROW(task_queue->shutdown());
  12413. #endif
  12414. EXPECT_EQ(queued_count, count.load());
  12415. EXPECT_TRUE(queued_count <= number_of_tasks);
  12416. EXPECT_TRUE(queued_count >= qlimit);
  12417. }
  12418. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12419. // Use a short idle timeout so a dynamic thread spawns, times out and
  12420. // exits during the test, and the pool keeps working afterwards.
  12421. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12422. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12423. /*idle_timeout_sec=*/1}};
  12424. std::atomic_uint count{0};
  12425. std::condition_variable cv;
  12426. std::mutex mtx;
  12427. bool release = false;
  12428. // Block the base thread so the second task spawns a dynamic thread.
  12429. EXPECT_TRUE(task_queue->enqueue([&] {
  12430. std::unique_lock<std::mutex> lock(mtx);
  12431. while (!release) {
  12432. cv.wait(lock);
  12433. }
  12434. count++;
  12435. }));
  12436. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12437. // Let the dynamic thread finish its task and exceed the idle timeout.
  12438. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12439. {
  12440. std::unique_lock<std::mutex> lock(mtx);
  12441. release = true;
  12442. }
  12443. cv.notify_all();
  12444. // The pool must still accept and run tasks after the dynamic thread exited.
  12445. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12446. task_queue->shutdown();
  12447. EXPECT_EQ(3u, count.load());
  12448. }
  12449. TEST(TaskQueueTest, MaxQueuedRequests) {
  12450. static constexpr unsigned int qlimit{3};
  12451. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12452. std::condition_variable sem_cv;
  12453. std::mutex sem_mtx;
  12454. int credits = 0;
  12455. bool queued;
  12456. /* Fill up the queue with tasks that will block until we give them credits to
  12457. * complete. */
  12458. for (unsigned int n = 0; n <= qlimit;) {
  12459. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12460. std::unique_lock<std::mutex> lock(sem_mtx);
  12461. while (credits <= 0) {
  12462. sem_cv.wait(lock);
  12463. }
  12464. /* Consume the credit and signal the test code if they are all gone. */
  12465. if (--credits == 0) { sem_cv.notify_one(); }
  12466. });
  12467. if (n < qlimit) {
  12468. /* The first qlimit enqueues must succeed. */
  12469. EXPECT_TRUE(queued);
  12470. } else {
  12471. /* The last one will succeed only when the worker thread
  12472. * starts and dequeues the first blocking task. Although
  12473. * not necessary for the correctness of this test, we sleep for
  12474. * a short while to avoid busy waiting. */
  12475. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12476. }
  12477. if (queued) { n++; }
  12478. }
  12479. /* Further enqueues must fail since the queue is full. */
  12480. for (auto i = 0; i < 4; i++) {
  12481. queued = task_queue->enqueue([] {});
  12482. EXPECT_FALSE(queued);
  12483. }
  12484. /* Give the credits to allow the previous tasks to complete. */
  12485. {
  12486. std::unique_lock<std::mutex> lock(sem_mtx);
  12487. credits += qlimit + 1;
  12488. }
  12489. sem_cv.notify_all();
  12490. /* Wait for all the credits to be consumed. */
  12491. {
  12492. std::unique_lock<std::mutex> lock(sem_mtx);
  12493. while (credits > 0) {
  12494. sem_cv.wait(lock);
  12495. }
  12496. }
  12497. /* Check that we are able again to enqueue at least qlimit tasks. */
  12498. for (unsigned int i = 0; i < qlimit; i++) {
  12499. queued = task_queue->enqueue([] {});
  12500. EXPECT_TRUE(queued);
  12501. }
  12502. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12503. task_queue->shutdown();
  12504. #else
  12505. EXPECT_NO_THROW(task_queue->shutdown());
  12506. #endif
  12507. }
  12508. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12509. Server svr;
  12510. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12511. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12512. });
  12513. svr.Get("/hello", [](const Request &req, Response &res) {
  12514. res.set_content(req.get_param_value("key"), "text/plain");
  12515. });
  12516. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12517. auto se = detail::scope_exit([&] {
  12518. svr.stop();
  12519. thread.join();
  12520. ASSERT_FALSE(svr.is_running());
  12521. });
  12522. svr.wait_until_ready();
  12523. {
  12524. Client cli(HOST, PORT);
  12525. cli.set_follow_location(true);
  12526. auto res = cli.Get("/");
  12527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12528. EXPECT_EQ(StatusCode::OK_200, res->status);
  12529. EXPECT_EQ("val&key2=val2", res->body);
  12530. }
  12531. }
  12532. #endif
  12533. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12534. Server svr;
  12535. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12536. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12537. });
  12538. svr.Get("/hello", [](const Request &req, Response &res) {
  12539. res.set_content(req.get_param_value("key"), "text/plain");
  12540. });
  12541. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12542. auto se = detail::scope_exit([&] {
  12543. svr.stop();
  12544. thread.join();
  12545. ASSERT_FALSE(svr.is_running());
  12546. });
  12547. svr.wait_until_ready();
  12548. {
  12549. Client cli(HOST, PORT);
  12550. cli.set_follow_location(true);
  12551. auto res = cli.Get("/");
  12552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12553. EXPECT_EQ(StatusCode::OK_200, res->status);
  12554. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12555. }
  12556. }
  12557. TEST(RedirectTest, RedirectWithPlusInPath) {
  12558. Server svr;
  12559. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12560. res.set_redirect("/a+b");
  12561. });
  12562. // Route pattern uses regex; escape + as \\+
  12563. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12564. res.set_content(req.path, "text/plain");
  12565. });
  12566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12567. auto se = detail::scope_exit([&] {
  12568. svr.stop();
  12569. thread.join();
  12570. ASSERT_FALSE(svr.is_running());
  12571. });
  12572. svr.wait_until_ready();
  12573. {
  12574. Client cli(HOST, PORT);
  12575. cli.set_follow_location(true);
  12576. auto res = cli.Get("/");
  12577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12578. EXPECT_EQ(StatusCode::OK_200, res->status);
  12579. EXPECT_EQ("/a+b", res->body);
  12580. }
  12581. }
  12582. #ifdef CPPHTTPLIB_SSL_ENABLED
  12583. TEST(RedirectTest, Issue2185_Online) {
  12584. SSLClient client("github.com");
  12585. client.set_follow_location(true);
  12586. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12587. "Coollab-Windows.zip");
  12588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12589. EXPECT_EQ(StatusCode::OK_200, res->status);
  12590. EXPECT_EQ(9920427U, res->body.size());
  12591. }
  12592. #endif
  12593. TEST(VulnerabilityTest, CRLFInjection) {
  12594. Server svr;
  12595. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12596. res.set_content("Hello 1", "text/plain");
  12597. });
  12598. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12599. res.set_content("Hello 2", "text/plain");
  12600. });
  12601. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12602. res.set_content("Hello 3", "text/plain");
  12603. });
  12604. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12605. res.set_content("Hello 4", "text/plain");
  12606. });
  12607. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12608. for (const auto &x : req.headers) {
  12609. auto key = x.first;
  12610. EXPECT_STRNE("evil", key.c_str());
  12611. }
  12612. });
  12613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12614. auto se = detail::scope_exit([&] {
  12615. svr.stop();
  12616. thread.join();
  12617. ASSERT_FALSE(svr.is_running());
  12618. });
  12619. svr.wait_until_ready();
  12620. {
  12621. Client cli(HOST, PORT);
  12622. cli.Post("/test1", "A=B",
  12623. "application/x-www-form-urlencoded\r\nevil: hello1");
  12624. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12625. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12626. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12627. }
  12628. }
  12629. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12630. auto server_thread = std::thread([] {
  12631. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12632. default_socket_options(srv);
  12633. sockaddr_in addr{};
  12634. addr.sin_family = AF_INET;
  12635. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12636. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12637. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12638. ::listen(srv, 1);
  12639. sockaddr_in cli_addr{};
  12640. socklen_t cli_len = sizeof(cli_addr);
  12641. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12642. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12643. std::string buf_all;
  12644. char buf[2048];
  12645. ssize_t n;
  12646. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12647. buf_all.append(buf, static_cast<size_t>(n));
  12648. size_t pos;
  12649. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12650. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12651. auto e = request_block.find("\r\n");
  12652. if (e != std::string::npos) {
  12653. auto request_line = request_block.substr(0, e);
  12654. std::string msg =
  12655. "CRLF injection detected in request line: '" + request_line + "'";
  12656. EXPECT_FALSE(true) << msg;
  12657. }
  12658. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12659. ::send(cli,
  12660. #ifdef _WIN32
  12661. static_cast<const char *>(resp.c_str()),
  12662. static_cast<int>(resp.size()),
  12663. #else
  12664. resp.c_str(), resp.size(),
  12665. #endif
  12666. 0);
  12667. buf_all.erase(0, pos + 4);
  12668. }
  12669. }
  12670. detail::close_socket(cli);
  12671. detail::close_socket(srv);
  12672. });
  12673. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12674. auto cli = Client("127.0.0.1", PORT + 1);
  12675. auto headers = Headers{
  12676. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12677. {"Connection", "keep-alive"}};
  12678. auto res = cli.Get("/hi", headers);
  12679. EXPECT_FALSE(res);
  12680. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12681. server_thread.join();
  12682. }
  12683. TEST(PathParamsTest, StaticMatch) {
  12684. const auto pattern = "/users/all";
  12685. detail::PathParamsMatcher matcher(pattern);
  12686. Request request;
  12687. request.path = "/users/all";
  12688. ASSERT_TRUE(matcher.match(request));
  12689. std::unordered_map<std::string, std::string> expected_params = {};
  12690. EXPECT_EQ(request.path_params, expected_params);
  12691. }
  12692. TEST(PathParamsTest, StaticMismatch) {
  12693. const auto pattern = "/users/all";
  12694. detail::PathParamsMatcher matcher(pattern);
  12695. Request request;
  12696. request.path = "/users/1";
  12697. ASSERT_FALSE(matcher.match(request));
  12698. }
  12699. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12700. const auto pattern = "/users/:id/subscriptions";
  12701. detail::PathParamsMatcher matcher(pattern);
  12702. Request request;
  12703. request.path = "/users/42/subscriptions";
  12704. ASSERT_TRUE(matcher.match(request));
  12705. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12706. EXPECT_EQ(request.path_params, expected_params);
  12707. }
  12708. TEST(PathParamsTest, SingleParamInTheEnd) {
  12709. const auto pattern = "/users/:id";
  12710. detail::PathParamsMatcher matcher(pattern);
  12711. Request request;
  12712. request.path = "/users/24";
  12713. ASSERT_TRUE(matcher.match(request));
  12714. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12715. EXPECT_EQ(request.path_params, expected_params);
  12716. }
  12717. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12718. const auto pattern = "/users/:id/";
  12719. detail::PathParamsMatcher matcher(pattern);
  12720. Request request;
  12721. request.path = "/users/42/";
  12722. ASSERT_TRUE(matcher.match(request));
  12723. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12724. EXPECT_EQ(request.path_params, expected_params);
  12725. }
  12726. TEST(PathParamsTest, EmptyParam) {
  12727. const auto pattern = "/users/:id/";
  12728. detail::PathParamsMatcher matcher(pattern);
  12729. Request request;
  12730. request.path = "/users//";
  12731. ASSERT_TRUE(matcher.match(request));
  12732. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12733. EXPECT_EQ(request.path_params, expected_params);
  12734. }
  12735. TEST(PathParamsTest, FragmentMismatch) {
  12736. const auto pattern = "/users/:id/";
  12737. detail::PathParamsMatcher matcher(pattern);
  12738. Request request;
  12739. request.path = "/admins/24/";
  12740. ASSERT_FALSE(matcher.match(request));
  12741. }
  12742. TEST(PathParamsTest, ExtraFragments) {
  12743. const auto pattern = "/users/:id";
  12744. detail::PathParamsMatcher matcher(pattern);
  12745. Request request;
  12746. request.path = "/users/42/subscriptions";
  12747. ASSERT_FALSE(matcher.match(request));
  12748. }
  12749. TEST(PathParamsTest, MissingTrailingParam) {
  12750. const auto pattern = "/users/:id";
  12751. detail::PathParamsMatcher matcher(pattern);
  12752. Request request;
  12753. request.path = "/users";
  12754. ASSERT_FALSE(matcher.match(request));
  12755. }
  12756. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12757. const auto pattern = "/users/:id/subscriptions";
  12758. detail::PathParamsMatcher matcher(pattern);
  12759. Request request;
  12760. request.path = "/users/subscriptions";
  12761. ASSERT_FALSE(matcher.match(request));
  12762. }
  12763. TEST(PathParamsTest, MultipleParams) {
  12764. const auto pattern = "/users/:userid/subscriptions/:subid";
  12765. detail::PathParamsMatcher matcher(pattern);
  12766. Request request;
  12767. request.path = "/users/42/subscriptions/2";
  12768. ASSERT_TRUE(matcher.match(request));
  12769. std::unordered_map<std::string, std::string> expected_params = {
  12770. {"userid", "42"}, {"subid", "2"}};
  12771. EXPECT_EQ(request.path_params, expected_params);
  12772. }
  12773. TEST(PathParamsTest, SequenceOfParams) {
  12774. const auto pattern = "/values/:x/:y/:z";
  12775. detail::PathParamsMatcher matcher(pattern);
  12776. Request request;
  12777. request.path = "/values/1/2/3";
  12778. ASSERT_TRUE(matcher.match(request));
  12779. std::unordered_map<std::string, std::string> expected_params = {
  12780. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12781. EXPECT_EQ(request.path_params, expected_params);
  12782. }
  12783. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12784. const auto pattern = "/prefix:suffix";
  12785. detail::PathParamsMatcher matcher(pattern);
  12786. Request request;
  12787. request.path = "/prefix:suffix";
  12788. ASSERT_TRUE(matcher.match(request));
  12789. const std::unordered_map<std::string, std::string> expected_params = {};
  12790. EXPECT_EQ(request.path_params, expected_params);
  12791. }
  12792. TEST(ParseUrlTest, VariousPatterns) {
  12793. {
  12794. detail::UrlComponents uc;
  12795. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12796. EXPECT_EQ("http", uc.scheme);
  12797. EXPECT_EQ("example.com", uc.host);
  12798. EXPECT_EQ("8080", uc.port);
  12799. EXPECT_EQ("/path", uc.path);
  12800. EXPECT_EQ("?q=1", uc.query);
  12801. }
  12802. {
  12803. detail::UrlComponents uc;
  12804. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12805. EXPECT_EQ("https", uc.scheme);
  12806. EXPECT_EQ("example.com", uc.host);
  12807. EXPECT_TRUE(uc.port.empty());
  12808. EXPECT_EQ("/path", uc.path);
  12809. }
  12810. {
  12811. detail::UrlComponents uc;
  12812. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12813. EXPECT_EQ("::1", uc.host);
  12814. EXPECT_EQ("8080", uc.port);
  12815. EXPECT_EQ("/path", uc.path);
  12816. }
  12817. {
  12818. detail::UrlComponents uc;
  12819. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12820. }
  12821. {
  12822. detail::UrlComponents uc;
  12823. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12824. EXPECT_TRUE(uc.scheme.empty());
  12825. EXPECT_EQ("example.com", uc.host);
  12826. EXPECT_EQ("/path", uc.path);
  12827. EXPECT_EQ("?q=1", uc.query);
  12828. }
  12829. {
  12830. detail::UrlComponents uc;
  12831. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12832. EXPECT_TRUE(uc.host.empty());
  12833. EXPECT_EQ("/path", uc.path);
  12834. EXPECT_EQ("?q=1", uc.query);
  12835. }
  12836. {
  12837. detail::UrlComponents uc;
  12838. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12839. EXPECT_EQ("example.com", uc.host);
  12840. EXPECT_EQ("8080", uc.port);
  12841. }
  12842. {
  12843. // Unix socket path — must not be parsed as host
  12844. detail::UrlComponents uc;
  12845. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12846. EXPECT_TRUE(uc.host.empty());
  12847. }
  12848. {
  12849. detail::UrlComponents uc;
  12850. ASSERT_TRUE(detail::parse_url("", uc));
  12851. EXPECT_TRUE(uc.host.empty());
  12852. EXPECT_TRUE(uc.path.empty());
  12853. }
  12854. {
  12855. detail::UrlComponents uc;
  12856. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12857. }
  12858. {
  12859. detail::UrlComponents uc;
  12860. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12861. }
  12862. {
  12863. // Accepted by parse_url; callers restrict to http/https
  12864. detail::UrlComponents uc;
  12865. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12866. EXPECT_EQ("ftp", uc.scheme);
  12867. }
  12868. {
  12869. detail::UrlComponents uc;
  12870. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12871. }
  12872. {
  12873. detail::UrlComponents uc;
  12874. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12875. }
  12876. }
  12877. TEST(ParseUrlTest, FragmentHandling) {
  12878. {
  12879. detail::UrlComponents uc;
  12880. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12881. EXPECT_EQ("/path", uc.path);
  12882. EXPECT_TRUE(uc.query.empty());
  12883. }
  12884. {
  12885. detail::UrlComponents uc;
  12886. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12887. EXPECT_TRUE(uc.path.empty());
  12888. EXPECT_TRUE(uc.query.empty());
  12889. }
  12890. }
  12891. TEST(ParseUrlTest, UserinfoHandling) {
  12892. // Userinfo with @ but no colon — host includes @
  12893. detail::UrlComponents uc;
  12894. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12895. EXPECT_EQ("user@host.com", uc.host);
  12896. EXPECT_EQ("/path", uc.path);
  12897. }
  12898. TEST(ParseUrlTest, IPv6EdgeCases) {
  12899. {
  12900. detail::UrlComponents uc;
  12901. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12902. EXPECT_TRUE(uc.scheme.empty());
  12903. EXPECT_EQ("::1", uc.host);
  12904. EXPECT_EQ("8080", uc.port);
  12905. }
  12906. {
  12907. // Zone ID '%25' is not in [a-fA-F0-9:]
  12908. detail::UrlComponents uc;
  12909. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12910. }
  12911. }
  12912. TEST(ParseUrlTest, SchemeEdgeCases) {
  12913. {
  12914. detail::UrlComponents uc;
  12915. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12916. }
  12917. {
  12918. detail::UrlComponents uc;
  12919. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12920. }
  12921. {
  12922. detail::UrlComponents uc;
  12923. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12924. }
  12925. }
  12926. TEST(ParseUrlTest, PortEdgeCases) {
  12927. {
  12928. detail::UrlComponents uc;
  12929. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12930. EXPECT_TRUE(uc.port.empty());
  12931. EXPECT_EQ("/path", uc.path);
  12932. }
  12933. {
  12934. // parse_url accepts any port string; validation is done by parse_port
  12935. detail::UrlComponents uc;
  12936. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12937. EXPECT_EQ("abc", uc.port);
  12938. }
  12939. }
  12940. TEST(ParseUrlTest, WebSocketPatterns) {
  12941. {
  12942. detail::UrlComponents uc;
  12943. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12944. EXPECT_EQ("ws", uc.scheme);
  12945. EXPECT_EQ("echo.example.com", uc.host);
  12946. EXPECT_EQ("8080", uc.port);
  12947. EXPECT_EQ("/ws", uc.path);
  12948. }
  12949. {
  12950. detail::UrlComponents uc;
  12951. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12952. EXPECT_EQ("wss", uc.scheme);
  12953. EXPECT_EQ("echo.example.com", uc.host);
  12954. EXPECT_TRUE(uc.port.empty());
  12955. EXPECT_EQ("/ws", uc.path);
  12956. }
  12957. }
  12958. TEST(ParseUrlTest, QueryOnly) {
  12959. detail::UrlComponents uc;
  12960. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12961. EXPECT_TRUE(uc.host.empty());
  12962. EXPECT_TRUE(uc.path.empty());
  12963. EXPECT_EQ("?q=1&r=2", uc.query);
  12964. }
  12965. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12966. detail::UrlComponents uc;
  12967. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12968. EXPECT_TRUE(uc.scheme.empty());
  12969. EXPECT_EQ("example.com", uc.host);
  12970. EXPECT_EQ("443", uc.port);
  12971. EXPECT_EQ("/path", uc.path);
  12972. }
  12973. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12974. // If ipv6 regex working, regex match codepath is taken.
  12975. // else port will default to 80 in Client impl
  12976. int clientImplMagicPort = 80;
  12977. int port = 4321;
  12978. // above ports must be different to avoid false negative
  12979. EXPECT_NE(clientImplMagicPort, port);
  12980. std::string ipV6TestURL = "http://[ff06::c3]";
  12981. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12982. CLIENT_PRIVATE_KEY_FILE);
  12983. EXPECT_EQ(cli.port(), port);
  12984. }
  12985. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12986. auto file_path = "./www/dir/index.html";
  12987. auto dir_path = "./www/dir";
  12988. detail::FileStat stat_file(file_path);
  12989. EXPECT_TRUE(stat_file.is_file());
  12990. EXPECT_FALSE(stat_file.is_dir());
  12991. detail::FileStat stat_dir(dir_path);
  12992. EXPECT_FALSE(stat_dir.is_file());
  12993. EXPECT_TRUE(stat_dir.is_dir());
  12994. }
  12995. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12996. // IPv4 with default HTTP port (80)
  12997. EXPECT_EQ("example.com",
  12998. detail::make_host_and_port_string("example.com", 80, false));
  12999. // IPv4 with default HTTPS port (443)
  13000. EXPECT_EQ("example.com",
  13001. detail::make_host_and_port_string("example.com", 443, true));
  13002. // IPv4 with non-default HTTP port
  13003. EXPECT_EQ("example.com:8080",
  13004. detail::make_host_and_port_string("example.com", 8080, false));
  13005. // IPv4 with non-default HTTPS port
  13006. EXPECT_EQ("example.com:8443",
  13007. detail::make_host_and_port_string("example.com", 8443, true));
  13008. // IPv6 with default HTTP port (80)
  13009. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13010. // IPv6 with default HTTPS port (443)
  13011. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13012. // IPv6 with non-default HTTP port
  13013. EXPECT_EQ("[::1]:8080",
  13014. detail::make_host_and_port_string("::1", 8080, false));
  13015. // IPv6 with non-default HTTPS port
  13016. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13017. // IPv6 full address with default port
  13018. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13019. detail::make_host_and_port_string(
  13020. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13021. // IPv6 full address with non-default port
  13022. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13023. detail::make_host_and_port_string(
  13024. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13025. // IPv6 localhost with non-default port
  13026. EXPECT_EQ("[::1]:3000",
  13027. detail::make_host_and_port_string("::1", 3000, false));
  13028. // IPv6 with zone ID (link-local address) with default port
  13029. EXPECT_EQ("[fe80::1%eth0]",
  13030. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13031. // IPv6 with zone ID (link-local address) with non-default port
  13032. EXPECT_EQ("[fe80::1%eth0]:8080",
  13033. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13034. // Edge case: Port 443 with is_ssl=false (should add port)
  13035. EXPECT_EQ("example.com:443",
  13036. detail::make_host_and_port_string("example.com", 443, false));
  13037. // Edge case: Port 80 with is_ssl=true (should add port)
  13038. EXPECT_EQ("example.com:80",
  13039. detail::make_host_and_port_string("example.com", 80, true));
  13040. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13041. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13042. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13043. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13044. // Security fix: Already bracketed IPv6 should not get double brackets
  13045. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13046. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13047. EXPECT_EQ("[::1]:8080",
  13048. detail::make_host_and_port_string("[::1]", 8080, false));
  13049. EXPECT_EQ("[2001:db8::1]:8080",
  13050. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13051. EXPECT_EQ("[fe80::1%eth0]",
  13052. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13053. EXPECT_EQ("[fe80::1%eth0]:8080",
  13054. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13055. // Edge case: Empty host (should return as-is)
  13056. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13057. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13058. // This is a known limitation but shouldn't crash
  13059. EXPECT_EQ("[host:name]",
  13060. detail::make_host_and_port_string("host:name", 80, false));
  13061. // Port number edge cases (no validation, but should not crash)
  13062. EXPECT_EQ("example.com:0",
  13063. detail::make_host_and_port_string("example.com", 0, false));
  13064. EXPECT_EQ("example.com:-1",
  13065. detail::make_host_and_port_string("example.com", -1, false));
  13066. EXPECT_EQ("example.com:65535",
  13067. detail::make_host_and_port_string("example.com", 65535, false));
  13068. EXPECT_EQ("example.com:65536",
  13069. detail::make_host_and_port_string("example.com", 65536, false));
  13070. }
  13071. #ifdef CPPHTTPLIB_SSL_ENABLED
  13072. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13073. httplib::SSLClient cli("roblox.com", 443);
  13074. cli.set_follow_location(true);
  13075. auto res = cli.Get("/");
  13076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13077. EXPECT_EQ(StatusCode::OK_200, res->status);
  13078. }
  13079. #endif
  13080. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13081. Server svr;
  13082. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13083. EXPECT_EQ(res.status, 400);
  13084. });
  13085. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13086. auto se = detail::scope_exit([&] {
  13087. svr.stop();
  13088. thread.join();
  13089. ASSERT_FALSE(svr.is_running());
  13090. });
  13091. svr.wait_until_ready();
  13092. Client cli(HOST, PORT);
  13093. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13094. }
  13095. TEST(InvalidHeaderCharsTest, is_field_name) {
  13096. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13097. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13098. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13099. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13100. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13101. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13102. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13103. EXPECT_FALSE(detail::fields::is_field_name(""));
  13104. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13105. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13106. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13107. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13108. }
  13109. TEST(InvalidHeaderCharsTest, is_field_value) {
  13110. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13111. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13112. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13113. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13114. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13115. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13116. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13117. EXPECT_TRUE(detail::fields::is_field_value(""));
  13118. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13119. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13120. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13121. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13122. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13123. }
  13124. TEST(InvalidHeaderCharsTest, OnServer) {
  13125. Server svr;
  13126. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13127. std::string header = "Not Set";
  13128. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13129. res.set_header(header, "value");
  13130. res.set_content("Page Content Page Content", "text/plain");
  13131. });
  13132. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13133. std::string header = "Not Set";
  13134. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13135. res.set_header("X-Test", header);
  13136. res.set_content("Page Content Page Content", "text/plain");
  13137. });
  13138. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13139. auto se = detail::scope_exit([&] {
  13140. svr.stop();
  13141. thread.join();
  13142. ASSERT_FALSE(svr.is_running());
  13143. });
  13144. svr.wait_until_ready();
  13145. Client cli(HOST, PORT);
  13146. {
  13147. auto res = cli.Get(
  13148. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13150. EXPECT_EQ("Page Content Page Content", res->body);
  13151. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13152. }
  13153. {
  13154. auto res = cli.Get(
  13155. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13157. EXPECT_EQ("Page Content Page Content", res->body);
  13158. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13159. }
  13160. }
  13161. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13162. auto handled = false;
  13163. Server svr;
  13164. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13165. thread t = thread([&] { svr.listen(HOST, PORT); });
  13166. auto se = detail::scope_exit([&] {
  13167. svr.stop();
  13168. t.join();
  13169. ASSERT_FALSE(svr.is_running());
  13170. ASSERT_FALSE(handled);
  13171. });
  13172. svr.wait_until_ready();
  13173. auto req = "POST /test HTTP/1.1\r\n"
  13174. "Content-Length: x\r\n"
  13175. "\r\n";
  13176. std::string response;
  13177. ASSERT_TRUE(send_request(1, req, &response));
  13178. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13179. response.substr(0, response.find("\r\n")));
  13180. }
  13181. #ifndef _WIN32
  13182. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13183. static constexpr char reject[] = "Unauthorized";
  13184. static constexpr char accept[] = "Upload accepted";
  13185. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13186. Server svr;
  13187. svr.set_expect_100_continue_handler(
  13188. [](const Request & /*req*/, Response &res) {
  13189. res.status = StatusCode::Unauthorized_401;
  13190. res.set_content(reject, "text/plain");
  13191. return res.status;
  13192. });
  13193. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13194. res.set_content(accept, "text/plain");
  13195. });
  13196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13197. auto se = detail::scope_exit([&] {
  13198. svr.stop();
  13199. thread.join();
  13200. ASSERT_FALSE(svr.is_running());
  13201. });
  13202. svr.wait_until_ready();
  13203. {
  13204. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13205. curl_easy_init(), &curl_easy_cleanup};
  13206. ASSERT_NE(curl, nullptr);
  13207. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13208. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13209. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13210. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13211. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13212. &curl_slist_free_all};
  13213. ASSERT_NE(list, nullptr);
  13214. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13215. struct read_data {
  13216. size_t read_size;
  13217. size_t total_size;
  13218. } data = {0, total_size};
  13219. using read_callback_t =
  13220. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13221. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13222. void *userdata) -> size_t {
  13223. read_data *d = (read_data *)userdata;
  13224. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13225. std::fill_n(ptr, size * nmemb, 'A');
  13226. d->read_size += size * nmemb;
  13227. return size * nmemb;
  13228. };
  13229. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13230. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13231. std::vector<char> buffer;
  13232. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13233. using write_callback_t =
  13234. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13235. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13236. void *userdata) -> size_t {
  13237. std::vector<char> *buf = (std::vector<char> *)userdata;
  13238. buf->reserve(buf->size() + size * nmemb + 1);
  13239. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13240. return size * nmemb;
  13241. };
  13242. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13243. {
  13244. const auto res = curl_easy_perform(curl.get());
  13245. ASSERT_EQ(res, CURLE_OK);
  13246. }
  13247. {
  13248. auto response_code = long{};
  13249. const auto res =
  13250. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13251. ASSERT_EQ(res, CURLE_OK);
  13252. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13253. }
  13254. {
  13255. auto dl = curl_off_t{};
  13256. const auto res =
  13257. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13258. ASSERT_EQ(res, CURLE_OK);
  13259. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13260. }
  13261. {
  13262. buffer.push_back('\0');
  13263. ASSERT_STRCASEEQ(buffer.data(), reject);
  13264. }
  13265. }
  13266. }
  13267. #endif
  13268. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13269. // Regression test for #2458.
  13270. //
  13271. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13272. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13273. // ticket can make the client socket spuriously readable during the
  13274. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13275. // the client withholds the body and then blocks reading a response that never
  13276. // comes, failing with `Failed to read connection`.
  13277. //
  13278. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13279. // within the timeout. This raw OpenSSL server deliberately never sends
  13280. // `100 Continue`; the client must still deliver the body and receive 200.
  13281. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13282. signal(SIGPIPE, SIG_IGN);
  13283. const auto port = PORT + 4;
  13284. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13285. ASSERT_NE(srv, INVALID_SOCKET);
  13286. int opt = 1;
  13287. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13288. sockaddr_in addr{};
  13289. addr.sin_family = AF_INET;
  13290. addr.sin_port = htons(static_cast<uint16_t>(port));
  13291. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13292. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13293. ASSERT_EQ(0, ::listen(srv, 1));
  13294. std::atomic<size_t> server_body_bytes{0};
  13295. auto server_thread = std::thread([&] {
  13296. sockaddr_in cli_addr{};
  13297. socklen_t cli_len = sizeof(cli_addr);
  13298. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13299. if (cli == INVALID_SOCKET) { return; }
  13300. // Bound the lifetime of the server side so a buggy client (which never
  13301. // sends the body) cannot make this thread block forever on join.
  13302. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13303. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13304. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13305. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13306. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13307. SSL *ssl = SSL_new(ctx);
  13308. SSL_set_fd(ssl, static_cast<int>(cli));
  13309. if (SSL_accept(ssl) > 0) {
  13310. // Read the request headers. Reading here also flushes the TLS 1.3
  13311. // session tickets to the client. Deliberately do NOT send
  13312. // `100 Continue`.
  13313. std::string buf;
  13314. char tmp[1024];
  13315. while (buf.find("\r\n\r\n") == std::string::npos) {
  13316. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13317. if (n <= 0) { break; }
  13318. buf.append(tmp, static_cast<size_t>(n));
  13319. }
  13320. // A correct client sends the body now; count what arrives.
  13321. auto pos = buf.find("\r\n\r\n");
  13322. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13323. while (body < 4096) {
  13324. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13325. if (n <= 0) { break; }
  13326. body += static_cast<size_t>(n);
  13327. }
  13328. server_body_bytes = body;
  13329. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13330. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13331. SSL_shutdown(ssl);
  13332. }
  13333. SSL_free(ssl);
  13334. detail::close_socket(cli);
  13335. SSL_CTX_free(ctx);
  13336. });
  13337. auto se = detail::scope_exit([&] {
  13338. server_thread.join();
  13339. detail::close_socket(srv);
  13340. });
  13341. SSLClient cli("127.0.0.1", port);
  13342. cli.enable_server_certificate_verification(false);
  13343. cli.set_connection_timeout(5, 0);
  13344. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13345. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13346. std::string body(4096, 'A');
  13347. auto res = cli.Put("/api/test", body, "application/json");
  13348. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13349. EXPECT_EQ(StatusCode::OK_200, res->status);
  13350. EXPECT_EQ(body.size(), server_body_bytes.load());
  13351. }
  13352. #endif
  13353. template <typename S, typename C>
  13354. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13355. svr.Get("/stream", [&](const Request &, Response &res) {
  13356. auto data = new std::string("01234567890123456789");
  13357. res.set_content_provider(
  13358. data->size(), "text/plain",
  13359. [&, data](size_t offset, size_t length, DataSink &sink) {
  13360. const size_t DATA_CHUNK_SIZE = 4;
  13361. const auto &d = *data;
  13362. std::this_thread::sleep_for(std::chrono::seconds(1));
  13363. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13364. return true;
  13365. },
  13366. [data](bool success) {
  13367. EXPECT_FALSE(success);
  13368. delete data;
  13369. });
  13370. });
  13371. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13372. auto i = new size_t(0);
  13373. res.set_content_provider(
  13374. "text/plain",
  13375. [i](size_t, DataSink &sink) {
  13376. if (*i < 5) {
  13377. std::this_thread::sleep_for(std::chrono::seconds(1));
  13378. sink.write("abcd", 4);
  13379. (*i)++;
  13380. } else {
  13381. sink.done();
  13382. }
  13383. return true;
  13384. },
  13385. [i](bool success) {
  13386. EXPECT_FALSE(success);
  13387. delete i;
  13388. });
  13389. });
  13390. svr.Get("/chunked", [&](const Request &, Response &res) {
  13391. auto i = new size_t(0);
  13392. res.set_chunked_content_provider(
  13393. "text/plain",
  13394. [i](size_t, DataSink &sink) {
  13395. if (*i < 5) {
  13396. std::this_thread::sleep_for(std::chrono::seconds(1));
  13397. sink.os << "abcd";
  13398. (*i)++;
  13399. } else {
  13400. sink.done();
  13401. }
  13402. return true;
  13403. },
  13404. [i](bool success) {
  13405. EXPECT_FALSE(success);
  13406. delete i;
  13407. });
  13408. });
  13409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13410. auto se = detail::scope_exit([&] {
  13411. svr.stop();
  13412. listen_thread.join();
  13413. ASSERT_FALSE(svr.is_running());
  13414. });
  13415. svr.wait_until_ready();
  13416. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13417. {
  13418. auto start = std::chrono::steady_clock::now();
  13419. auto res = cli.Get("/stream");
  13420. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13421. std::chrono::steady_clock::now() - start)
  13422. .count();
  13423. ASSERT_FALSE(res);
  13424. EXPECT_EQ(Error::Read, res.error());
  13425. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13426. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13427. }
  13428. {
  13429. auto start = std::chrono::steady_clock::now();
  13430. auto res = cli.Get("/stream_without_length");
  13431. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13432. std::chrono::steady_clock::now() - start)
  13433. .count();
  13434. ASSERT_FALSE(res);
  13435. EXPECT_EQ(Error::Read, res.error());
  13436. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13437. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13438. }
  13439. {
  13440. auto start = std::chrono::steady_clock::now();
  13441. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13442. EXPECT_EQ("abcd", string(data, data_length));
  13443. return true;
  13444. });
  13445. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13446. std::chrono::steady_clock::now() - start)
  13447. .count();
  13448. ASSERT_FALSE(res);
  13449. EXPECT_EQ(Error::Read, res.error());
  13450. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13451. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13452. }
  13453. }
  13454. TEST(MaxTimeoutTest, ContentStream) {
  13455. time_t timeout = 2000;
  13456. time_t threshold = 200;
  13457. Server svr;
  13458. Client cli("localhost", PORT);
  13459. max_timeout_test(svr, cli, timeout, threshold);
  13460. }
  13461. #ifdef CPPHTTPLIB_SSL_ENABLED
  13462. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13463. time_t timeout = 2000;
  13464. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13465. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13466. SSLClient cli("localhost", PORT);
  13467. cli.enable_server_certificate_verification(false);
  13468. max_timeout_test(svr, cli, timeout, threshold);
  13469. }
  13470. #endif
  13471. class EventDispatcher {
  13472. public:
  13473. EventDispatcher() {}
  13474. bool wait_event(DataSink *sink) {
  13475. unique_lock<mutex> lk(m_);
  13476. int id = id_;
  13477. // Wait with timeout to prevent hanging if client disconnects
  13478. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13479. [&] { return cid_ == id; })) {
  13480. return false; // Timeout occurred
  13481. }
  13482. sink->write(message_.data(), message_.size());
  13483. return true;
  13484. }
  13485. void send_event(const string &message) {
  13486. lock_guard<mutex> lk(m_);
  13487. cid_ = id_++;
  13488. message_ = message;
  13489. cv_.notify_all();
  13490. }
  13491. private:
  13492. mutex m_;
  13493. condition_variable cv_;
  13494. atomic_int id_{0};
  13495. atomic_int cid_{-1};
  13496. string message_;
  13497. };
  13498. TEST(ClientInThreadTest, Issue2068) {
  13499. EventDispatcher ed;
  13500. Server svr;
  13501. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13502. res.set_chunked_content_provider("text/event-stream",
  13503. [&](size_t /*offset*/, DataSink &sink) {
  13504. return ed.wait_event(&sink);
  13505. });
  13506. });
  13507. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13508. svr.wait_until_ready();
  13509. thread event_thread([&] {
  13510. int id = 0;
  13511. while (svr.is_running()) {
  13512. this_thread::sleep_for(chrono::milliseconds(500));
  13513. std::stringstream ss;
  13514. ss << "data: " << id << "\n\n";
  13515. ed.send_event(ss.str());
  13516. id++;
  13517. }
  13518. });
  13519. auto se = detail::scope_exit([&] {
  13520. svr.stop();
  13521. listen_thread.join();
  13522. event_thread.join();
  13523. ASSERT_FALSE(svr.is_running());
  13524. });
  13525. {
  13526. auto client = detail::make_unique<Client>(HOST, PORT);
  13527. client->set_read_timeout(std::chrono::minutes(10));
  13528. std::atomic<bool> stop{false};
  13529. std::thread t([&] {
  13530. client->Get("/event1",
  13531. [&](const char *, size_t) -> bool { return !stop; });
  13532. });
  13533. std::this_thread::sleep_for(std::chrono::seconds(2));
  13534. stop = true;
  13535. client->stop();
  13536. t.join();
  13537. // Reset client after thread has finished
  13538. client.reset();
  13539. }
  13540. }
  13541. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13542. auto handled = false;
  13543. Server svr;
  13544. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13545. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13546. auto se = detail::scope_exit([&] {
  13547. svr.stop();
  13548. t.join();
  13549. ASSERT_FALSE(svr.is_running());
  13550. ASSERT_FALSE(handled);
  13551. });
  13552. svr.wait_until_ready();
  13553. // Two Content-Length headers with different values — must be rejected
  13554. auto req = "POST /test HTTP/1.1\r\n"
  13555. "Content-Length: 5\r\n"
  13556. "Content-Length: 10\r\n"
  13557. "\r\n"
  13558. "hello";
  13559. std::string response;
  13560. ASSERT_TRUE(send_request(1, req, &response));
  13561. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13562. response.substr(0, response.find("\r\n")));
  13563. }
  13564. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13565. auto handled = false;
  13566. Server svr;
  13567. svr.Post("/test", [&](const Request &, Response &res) {
  13568. handled = true;
  13569. res.set_content("ok", "text/plain");
  13570. });
  13571. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13572. auto se = detail::scope_exit([&] {
  13573. svr.stop();
  13574. t.join();
  13575. ASSERT_FALSE(svr.is_running());
  13576. ASSERT_TRUE(handled);
  13577. });
  13578. svr.wait_until_ready();
  13579. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13580. auto req = "POST /test HTTP/1.1\r\n"
  13581. "Content-Length: 5\r\n"
  13582. "Content-Length: 5\r\n"
  13583. "\r\n"
  13584. "hello";
  13585. std::string response;
  13586. ASSERT_TRUE(send_request(1, req, &response));
  13587. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13588. }
  13589. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13590. Server svr;
  13591. svr.Get("/", [](const Request &req, Response &res) {
  13592. EXPECT_EQ(2U, req.trailers.size());
  13593. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13594. // Denied
  13595. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13596. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13597. // Accepted
  13598. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13599. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13600. EXPECT_TRUE(req.has_trailer("X-World"));
  13601. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13602. res.set_content("ok", "text/plain");
  13603. });
  13604. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13605. auto se = detail::scope_exit([&] {
  13606. svr.stop();
  13607. t.join();
  13608. ASSERT_FALSE(svr.is_running());
  13609. });
  13610. svr.wait_until_ready();
  13611. const std::string req = "GET / HTTP/1.1\r\n"
  13612. "Transfer-Encoding: chunked\r\n"
  13613. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13614. "\r\n"
  13615. "0\r\n"
  13616. "Content-Length: 10\r\n"
  13617. "Host: internal.local\r\n"
  13618. "Content-Type: malicious/content\r\n"
  13619. "Cookie: any\r\n"
  13620. "Set-Cookie: any\r\n"
  13621. "X-Forwarded-For: attacker.com\r\n"
  13622. "X-Real-Ip: 1.1.1.1\r\n"
  13623. "X-Hello: hello\r\n"
  13624. "X-World: world\r\n"
  13625. "\r\n";
  13626. std::string res;
  13627. ASSERT_TRUE(send_request(1, req, &res));
  13628. }
  13629. // A direct client that is not listed in trusted_proxies must not be able to
  13630. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13631. // the peer address on the actual TCP connection determines whether the
  13632. // header is honored.
  13633. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13634. Server svr;
  13635. // Deliberately does NOT include the loopback address the test client
  13636. // actually connects from, so the direct connection is not a trusted proxy.
  13637. svr.set_trusted_proxies({"203.0.113.66"});
  13638. std::string observed_remote_addr;
  13639. svr.Get("/ip", [&](const Request &req, Response &res) {
  13640. observed_remote_addr = req.remote_addr;
  13641. res.set_content("ok", "text/plain");
  13642. });
  13643. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13644. auto se = detail::scope_exit([&] {
  13645. svr.stop();
  13646. t.join();
  13647. ASSERT_FALSE(svr.is_running());
  13648. });
  13649. svr.wait_until_ready();
  13650. Client cli(HOST, PORT);
  13651. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13653. EXPECT_EQ(StatusCode::OK_200, res->status);
  13654. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13655. // ignored entirely and the real connection-level address retained.
  13656. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13657. observed_remote_addr == "127.0.0.1");
  13658. }
  13659. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13660. Server svr;
  13661. std::string observed_remote_addr;
  13662. std::string observed_xff;
  13663. svr.Get("/ip", [&](const Request &req, Response &res) {
  13664. observed_remote_addr = req.remote_addr;
  13665. observed_xff = req.get_header_value("X-Forwarded-For");
  13666. res.set_content("ok", "text/plain");
  13667. });
  13668. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13669. auto se = detail::scope_exit([&] {
  13670. svr.stop();
  13671. t.join();
  13672. ASSERT_FALSE(svr.is_running());
  13673. });
  13674. svr.wait_until_ready();
  13675. Client cli(HOST, PORT);
  13676. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13678. EXPECT_EQ(StatusCode::OK_200, res->status);
  13679. EXPECT_EQ(observed_xff, "203.0.113.66");
  13680. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13681. observed_remote_addr == "127.0.0.1");
  13682. }
  13683. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13684. Server svr;
  13685. svr.set_trusted_proxies({"203.0.113.66"});
  13686. std::string observed_remote_addr;
  13687. std::string observed_xff;
  13688. svr.Get("/ip", [&](const Request &req, Response &res) {
  13689. observed_remote_addr = req.remote_addr;
  13690. observed_xff = req.get_header_value("X-Forwarded-For");
  13691. res.set_content("ok", "text/plain");
  13692. });
  13693. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13694. auto se = detail::scope_exit([&] {
  13695. svr.stop();
  13696. t.join();
  13697. ASSERT_FALSE(svr.is_running());
  13698. });
  13699. svr.wait_until_ready();
  13700. Client cli(HOST, PORT);
  13701. auto res = cli.Get("/ip");
  13702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13703. EXPECT_EQ(StatusCode::OK_200, res->status);
  13704. EXPECT_EQ(observed_xff, "");
  13705. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13706. observed_remote_addr == "127.0.0.1");
  13707. }
  13708. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13709. Server svr;
  13710. // Include the loopback address the test client actually connects from, so
  13711. // the direct connection itself is recognized as the trusted proxy hop.
  13712. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13713. std::string observed_remote_addr;
  13714. std::string observed_xff;
  13715. svr.Get("/ip", [&](const Request &req, Response &res) {
  13716. observed_remote_addr = req.remote_addr;
  13717. observed_xff = req.get_header_value("X-Forwarded-For");
  13718. res.set_content("ok", "text/plain");
  13719. });
  13720. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13721. auto se = detail::scope_exit([&] {
  13722. svr.stop();
  13723. t.join();
  13724. ASSERT_FALSE(svr.is_running());
  13725. });
  13726. svr.wait_until_ready();
  13727. Client cli(HOST, PORT);
  13728. auto res = cli.Get(
  13729. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13731. EXPECT_EQ(StatusCode::OK_200, res->status);
  13732. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13733. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13734. }
  13735. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13736. Server svr;
  13737. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13738. std::string observed_remote_addr;
  13739. std::string observed_xff;
  13740. svr.Get("/ip", [&](const Request &req, Response &res) {
  13741. observed_remote_addr = req.remote_addr;
  13742. observed_xff = req.get_header_value("X-Forwarded-For");
  13743. res.set_content("ok", "text/plain");
  13744. });
  13745. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13746. auto se = detail::scope_exit([&] {
  13747. svr.stop();
  13748. t.join();
  13749. ASSERT_FALSE(svr.is_running());
  13750. });
  13751. svr.wait_until_ready();
  13752. Client cli(HOST, PORT);
  13753. auto res = cli.Get(
  13754. "/ip",
  13755. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13757. EXPECT_EQ(StatusCode::OK_200, res->status);
  13758. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13759. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13760. }
  13761. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13762. Server svr;
  13763. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13764. std::string observed_remote_addr;
  13765. std::string observed_xff;
  13766. svr.Get("/ip", [&](const Request &req, Response &res) {
  13767. observed_remote_addr = req.remote_addr;
  13768. observed_xff = req.get_header_value("X-Forwarded-For");
  13769. res.set_content("ok", "text/plain");
  13770. });
  13771. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13772. auto se = detail::scope_exit([&] {
  13773. svr.stop();
  13774. t.join();
  13775. ASSERT_FALSE(svr.is_running());
  13776. });
  13777. svr.wait_until_ready();
  13778. Client cli(HOST, PORT);
  13779. auto res = cli.Get(
  13780. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13782. EXPECT_EQ(StatusCode::OK_200, res->status);
  13783. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13784. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13785. // and must not be selected.
  13786. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13787. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13788. }
  13789. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13790. Server svr;
  13791. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13792. std::string observed_remote_addr;
  13793. svr.Get("/ip", [&](const Request &req, Response &res) {
  13794. observed_remote_addr = req.remote_addr;
  13795. res.set_content("ok", "text/plain");
  13796. });
  13797. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13798. auto se = detail::scope_exit([&] {
  13799. svr.stop();
  13800. t.join();
  13801. ASSERT_FALSE(svr.is_running());
  13802. });
  13803. svr.wait_until_ready();
  13804. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13805. // a forged address and the trusted proxy's own address; the forged value must
  13806. // not win over the address the trusted proxy actually recorded.
  13807. Client cli(HOST, PORT);
  13808. auto res = cli.Get(
  13809. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13811. EXPECT_EQ(StatusCode::OK_200, res->status);
  13812. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13813. }
  13814. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13815. Server svr;
  13816. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13817. std::string observed_remote_addr;
  13818. std::string observed_xff;
  13819. svr.Get("/ip", [&](const Request &req, Response &res) {
  13820. observed_remote_addr = req.remote_addr;
  13821. observed_xff = req.get_header_value("X-Forwarded-For");
  13822. res.set_content("ok", "text/plain");
  13823. });
  13824. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13825. auto se = detail::scope_exit([&] {
  13826. svr.stop();
  13827. t.join();
  13828. ASSERT_FALSE(svr.is_running());
  13829. });
  13830. svr.wait_until_ready();
  13831. Client cli(HOST, PORT);
  13832. auto res = cli.Get(
  13833. "/ip",
  13834. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13836. EXPECT_EQ(StatusCode::OK_200, res->status);
  13837. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13838. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13839. }
  13840. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13841. Server svr;
  13842. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13843. std::string observed_remote_addr;
  13844. std::string observed_xff;
  13845. svr.Get("/ip", [&](const Request &req, Response &res) {
  13846. observed_remote_addr = req.remote_addr;
  13847. observed_xff = req.get_header_value("X-Forwarded-For");
  13848. res.set_content("ok", "text/plain");
  13849. });
  13850. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13851. auto se = detail::scope_exit([&] {
  13852. svr.stop();
  13853. t.join();
  13854. ASSERT_FALSE(svr.is_running());
  13855. });
  13856. svr.wait_until_ready();
  13857. std::string raw_req =
  13858. "GET /ip HTTP/1.1\r\n"
  13859. "Host: localhost\r\n"
  13860. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13861. "Connection: close\r\n"
  13862. "\r\n";
  13863. std::string out;
  13864. ASSERT_TRUE(send_request(5, raw_req, &out));
  13865. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13866. // Header parser trims surrounding whitespace of the header value
  13867. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13868. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13869. }
  13870. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13871. // crash the server (it used to call front() on an empty vector inside
  13872. // get_client_ip). The connection-level remote address must be retained instead.
  13873. static void run_malformed_xff_test(const std::string &xff_value) {
  13874. Server svr;
  13875. svr.set_trusted_proxies({"192.0.2.45"});
  13876. std::string observed_remote_addr;
  13877. svr.Get("/ip", [&](const Request &req, Response &res) {
  13878. observed_remote_addr = req.remote_addr;
  13879. res.set_content("ok", "text/plain");
  13880. });
  13881. int port = 0;
  13882. thread t = thread([&]() {
  13883. port = svr.bind_to_any_port(HOST);
  13884. svr.listen_after_bind();
  13885. });
  13886. auto se = detail::scope_exit([&] {
  13887. svr.stop();
  13888. t.join();
  13889. ASSERT_FALSE(svr.is_running());
  13890. });
  13891. svr.wait_until_ready();
  13892. Client cli(HOST, port);
  13893. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13895. EXPECT_EQ(StatusCode::OK_200, res->status);
  13896. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13897. observed_remote_addr == "127.0.0.1");
  13898. }
  13899. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13900. run_malformed_xff_test("");
  13901. }
  13902. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13903. run_malformed_xff_test(",");
  13904. }
  13905. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13906. run_malformed_xff_test(", , ,");
  13907. }
  13908. #ifndef _WIN32
  13909. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13910. Server svr;
  13911. svr.Post("/post", [&](const Request &req, Response &res) {
  13912. res.set_content(req.body, "text/plain");
  13913. });
  13914. svr.Put("/put", [&](const Request &req, Response &res) {
  13915. res.set_content(req.body, "text/plain");
  13916. });
  13917. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13918. res.set_content(req.body, "text/plain");
  13919. });
  13920. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13921. res.set_content(req.body, "text/plain");
  13922. });
  13923. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13924. auto se = detail::scope_exit([&] {
  13925. svr.stop();
  13926. t.join();
  13927. ASSERT_FALSE(svr.is_running());
  13928. });
  13929. svr.wait_until_ready();
  13930. std::string resp;
  13931. // POST without Content-Length
  13932. ASSERT_TRUE(send_request(5,
  13933. "POST /post HTTP/1.1\r\n"
  13934. "Host: localhost\r\n"
  13935. "Connection: close\r\n"
  13936. "\r\n",
  13937. &resp));
  13938. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13939. // PUT without Content-Length
  13940. resp.clear();
  13941. ASSERT_TRUE(send_request(5,
  13942. "PUT /put HTTP/1.1\r\n"
  13943. "Host: localhost\r\n"
  13944. "Connection: close\r\n"
  13945. "\r\n",
  13946. &resp));
  13947. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13948. // PATCH without Content-Length
  13949. resp.clear();
  13950. ASSERT_TRUE(send_request(5,
  13951. "PATCH /patch HTTP/1.1\r\n"
  13952. "Host: localhost\r\n"
  13953. "Connection: close\r\n"
  13954. "\r\n",
  13955. &resp));
  13956. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13957. // DELETE without Content-Length
  13958. resp.clear();
  13959. ASSERT_TRUE(send_request(5,
  13960. "DELETE /delete HTTP/1.1\r\n"
  13961. "Host: localhost\r\n"
  13962. "Connection: close\r\n"
  13963. "\r\n",
  13964. &resp));
  13965. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13966. }
  13967. #endif
  13968. //==============================================================================
  13969. // open_stream() Tests
  13970. //==============================================================================
  13971. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13972. std::string result;
  13973. char buf[8192];
  13974. ssize_t n;
  13975. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13976. result.append(buf, static_cast<size_t>(n));
  13977. }
  13978. return result;
  13979. }
  13980. // Mock stream for unit tests
  13981. class MockStream : public Stream {
  13982. public:
  13983. std::string data;
  13984. size_t pos = 0;
  13985. ssize_t error_after = -1; // -1 = no error
  13986. explicit MockStream(const std::string &d, ssize_t err = -1)
  13987. : data(d), error_after(err) {}
  13988. bool is_readable() const override { return true; }
  13989. bool wait_readable() const override { return true; }
  13990. bool wait_writable() const override { return true; }
  13991. ssize_t read(char *ptr, size_t size) override {
  13992. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13993. if (pos >= data.size()) return 0;
  13994. size_t limit =
  13995. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13996. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13997. std::memcpy(ptr, data.data() + pos, to_read);
  13998. pos += to_read;
  13999. return static_cast<ssize_t>(to_read);
  14000. }
  14001. ssize_t write(const char *, size_t) override { return -1; }
  14002. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14003. ip = "127.0.0.1";
  14004. port = 0;
  14005. }
  14006. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14007. ip = "127.0.0.1";
  14008. port = 0;
  14009. }
  14010. socket_t socket() const override { return INVALID_SOCKET; }
  14011. time_t duration() const override { return 0; }
  14012. };
  14013. TEST(StreamHandleTest, Basic) {
  14014. ClientImpl::StreamHandle handle;
  14015. EXPECT_FALSE(handle.is_valid());
  14016. handle.response = detail::make_unique<Response>();
  14017. handle.error = Error::Connection;
  14018. EXPECT_FALSE(handle.is_valid());
  14019. handle.error = Error::Success;
  14020. EXPECT_TRUE(handle.is_valid());
  14021. }
  14022. TEST(BodyReaderTest, Basic) {
  14023. MockStream stream("Hello, World!");
  14024. detail::BodyReader reader;
  14025. reader.stream = &stream;
  14026. reader.content_length = 13;
  14027. char buf[32];
  14028. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14029. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14030. EXPECT_TRUE(reader.eof);
  14031. }
  14032. TEST(BodyReaderTest, NoStream) {
  14033. detail::BodyReader reader;
  14034. char buf[32];
  14035. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14036. EXPECT_EQ(Error::Connection, reader.last_error);
  14037. }
  14038. TEST(BodyReaderTest, Error) {
  14039. MockStream stream("Hello, World!", 5);
  14040. detail::BodyReader reader;
  14041. reader.stream = &stream;
  14042. reader.content_length = 13;
  14043. char buf[32];
  14044. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14045. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14046. EXPECT_EQ(Error::Read, reader.last_error);
  14047. }
  14048. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14049. // Mock-based StreamHandle tests relying on private internals are removed.
  14050. class OpenStreamTest : public ::testing::Test {
  14051. protected:
  14052. void SetUp() override {
  14053. svr_.Get("/hello", [](const Request &, Response &res) {
  14054. res.set_content("Hello World!", "text/plain");
  14055. });
  14056. svr_.Get("/large", [](const Request &, Response &res) {
  14057. res.set_content(std::string(10000, 'X'), "text/plain");
  14058. });
  14059. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14060. res.set_content("Hello World!", "image/jpeg");
  14061. res.set_header("Content-Encoding", "UTF-8");
  14062. });
  14063. svr_.Get("/chunked", [](const Request &, Response &res) {
  14064. res.set_chunked_content_provider("text/plain",
  14065. [](size_t offset, DataSink &sink) {
  14066. if (offset < 15) {
  14067. sink.write("chunk", 5);
  14068. return true;
  14069. }
  14070. sink.done();
  14071. return true;
  14072. });
  14073. });
  14074. svr_.Get("/compressible", [](const Request &, Response &res) {
  14075. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14076. DataSink &sink) {
  14077. if (offset < 100 * 1024) {
  14078. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14079. sink.write(chunk.data(), chunk.size());
  14080. return true;
  14081. }
  14082. sink.done();
  14083. return true;
  14084. });
  14085. });
  14086. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14087. [](const Request & /*req*/, Response &res) {
  14088. auto i = new int(0);
  14089. res.set_header("Trailer", "Content-Length, X-Allowed");
  14090. res.set_chunked_content_provider(
  14091. "text/plain",
  14092. [i](size_t /*offset*/, DataSink &sink) {
  14093. switch (*i) {
  14094. case 0: sink.os << "123"; break;
  14095. case 1: sink.os << "456"; break;
  14096. case 2: sink.os << "789"; break;
  14097. case 3: {
  14098. sink.done_with_trailer(
  14099. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14100. } break;
  14101. }
  14102. (*i)++;
  14103. return true;
  14104. },
  14105. [i](bool success) {
  14106. EXPECT_TRUE(success);
  14107. delete i;
  14108. });
  14109. });
  14110. // Echo headers endpoint for header-related tests
  14111. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14112. std::string body;
  14113. for (const auto &h : req.headers) {
  14114. body.append(h.first);
  14115. body.push_back(':');
  14116. body.append(h.second);
  14117. body.push_back('\n');
  14118. }
  14119. res.set_content(body, "text/plain");
  14120. });
  14121. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14122. std::string body;
  14123. for (const auto &h : req.headers) {
  14124. body.append(h.first);
  14125. body.push_back(':');
  14126. body.append(h.second);
  14127. body.push_back('\n');
  14128. }
  14129. res.set_content(body, "text/plain");
  14130. });
  14131. port_ = svr_.bind_to_any_port("127.0.0.1");
  14132. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14133. svr_.wait_until_ready();
  14134. }
  14135. void TearDown() override {
  14136. svr_.stop();
  14137. if (thread_.joinable()) thread_.join();
  14138. }
  14139. Server svr_;
  14140. std::thread thread_;
  14141. int port_ = 0;
  14142. };
  14143. TEST_F(OpenStreamTest, Basic) {
  14144. Client cli("127.0.0.1", port_);
  14145. auto handle = cli.open_stream("GET", "/hello");
  14146. EXPECT_TRUE(handle.is_valid());
  14147. EXPECT_EQ("Hello World!", read_all(handle));
  14148. }
  14149. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14150. Client cli("127.0.0.1", port_);
  14151. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14152. ASSERT_TRUE(handle.is_valid());
  14153. EXPECT_EQ("Hello World!", read_all(handle));
  14154. }
  14155. TEST_F(OpenStreamTest, SmallBuffer) {
  14156. Client cli("127.0.0.1", port_);
  14157. auto handle = cli.open_stream("GET", "/hello");
  14158. std::string result;
  14159. char buf[4];
  14160. ssize_t n;
  14161. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14162. result.append(buf, static_cast<size_t>(n));
  14163. EXPECT_EQ("Hello World!", result);
  14164. }
  14165. TEST_F(OpenStreamTest, DefaultHeaders) {
  14166. Client cli("127.0.0.1", port_);
  14167. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14168. {
  14169. auto handle = cli.open_stream("GET", "/echo-headers");
  14170. ASSERT_TRUE(handle.is_valid());
  14171. auto body = read_all(handle);
  14172. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14173. std::string::npos);
  14174. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14175. std::string::npos);
  14176. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14177. }
  14178. // open_stream POST with body and no explicit content_type should NOT add
  14179. // text/plain Content-Type (behavior differs from non-streaming path), but
  14180. // should include Content-Length
  14181. {
  14182. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14183. ASSERT_TRUE(handle.is_valid());
  14184. auto body = read_all(handle);
  14185. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14186. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14187. }
  14188. // open_stream POST with explicit Content-Type should preserve it
  14189. {
  14190. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14191. {{"Content-Type", "application/custom"}},
  14192. "{}", "application/custom");
  14193. ASSERT_TRUE(handle.is_valid());
  14194. auto body = read_all(handle);
  14195. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14196. }
  14197. // User-specified User-Agent must not be overwritten for stream API
  14198. {
  14199. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14200. {{"User-Agent", "MyAgent/1.2"}});
  14201. ASSERT_TRUE(handle.is_valid());
  14202. auto body = read_all(handle);
  14203. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14204. }
  14205. }
  14206. TEST_F(OpenStreamTest, Large) {
  14207. Client cli("127.0.0.1", port_);
  14208. auto handle = cli.open_stream("GET", "/large");
  14209. EXPECT_EQ(10000u, read_all(handle).size());
  14210. }
  14211. TEST_F(OpenStreamTest, ConnectionError) {
  14212. Client cli("127.0.0.1", 9999);
  14213. auto handle = cli.open_stream("GET", "/hello");
  14214. EXPECT_FALSE(handle.is_valid());
  14215. }
  14216. TEST_F(OpenStreamTest, Chunked) {
  14217. Client cli("127.0.0.1", port_);
  14218. auto handle = cli.open_stream("GET", "/chunked");
  14219. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14220. "Transfer-Encoding") == "chunked");
  14221. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14222. }
  14223. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14224. Client cli("127.0.0.1", port_);
  14225. auto handle =
  14226. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14227. ASSERT_TRUE(handle.is_valid());
  14228. // Consume body to allow trailers to be received/parsed
  14229. auto body = read_all(handle);
  14230. // Explicitly parse trailers (ensure trailers are available for assertion)
  14231. handle.parse_trailers_if_needed();
  14232. EXPECT_EQ(std::string("123456789"), body);
  14233. // The response should include a Trailer header declaring both names
  14234. ASSERT_TRUE(handle.response);
  14235. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14236. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14237. handle.response->get_header_value("Trailer"));
  14238. // Prohibited trailer must not be present
  14239. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14240. // Allowed trailer should be present
  14241. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14242. EXPECT_EQ(std::string("yes"),
  14243. handle.response->get_trailer_value("X-Allowed"));
  14244. // Verify trailers are NOT present as regular headers
  14245. EXPECT_EQ(std::string(""),
  14246. handle.response->get_header_value("Content-Length"));
  14247. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14248. }
  14249. static std::thread serve_single_response(std::promise<int> &port_promise,
  14250. const std::string &response) {
  14251. return std::thread([&port_promise, response] {
  14252. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14253. default_socket_options(srv);
  14254. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14255. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14256. sockaddr_in addr{};
  14257. addr.sin_family = AF_INET;
  14258. addr.sin_port = htons(0); // Let OS assign a free port
  14259. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14260. int opt = 1;
  14261. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14262. #ifdef _WIN32
  14263. reinterpret_cast<const char *>(&opt),
  14264. #else
  14265. &opt,
  14266. #endif
  14267. sizeof(opt));
  14268. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14269. ::listen(srv, 1) != 0) {
  14270. port_promise.set_value(-1);
  14271. detail::close_socket(srv);
  14272. return;
  14273. }
  14274. socklen_t addr_len = sizeof(addr);
  14275. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14276. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14277. sockaddr_in cli_addr{};
  14278. socklen_t cli_len = sizeof(cli_addr);
  14279. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14280. if (cli != INVALID_SOCKET) {
  14281. // Read the complete HTTP request (until the blank line that terminates
  14282. // headers) before sending the response. If the server closes the socket
  14283. // while the client's request data is still unread in the kernel receive
  14284. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14285. // connection on both sides: it discards the client's receive buffer
  14286. // (which already holds our response) and causes any in-progress write on
  14287. // the client to fail with ECONNRESET. Reading all request data first
  14288. // ensures close() emits a graceful FIN.
  14289. {
  14290. char rbuf[256];
  14291. std::string req;
  14292. while (req.find("\r\n\r\n") == std::string::npos) {
  14293. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14294. if (n <= 0) { break; }
  14295. req.append(rbuf, static_cast<size_t>(n));
  14296. }
  14297. }
  14298. ::send(cli,
  14299. #ifdef _WIN32
  14300. static_cast<const char *>(response.c_str()),
  14301. static_cast<int>(response.size()),
  14302. #else
  14303. response.c_str(), response.size(),
  14304. #endif
  14305. 0);
  14306. detail::close_socket(cli);
  14307. }
  14308. detail::close_socket(srv);
  14309. });
  14310. }
  14311. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14312. #ifndef _WIN32
  14313. signal(SIGPIPE, SIG_IGN);
  14314. #endif
  14315. std::promise<int> port_promise;
  14316. auto port_future = port_promise.get_future();
  14317. auto server_thread =
  14318. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14319. "Content-Type: text/plain\r\n"
  14320. "Content-Length: not-a-number\r\n"
  14321. "Connection: close\r\n"
  14322. "\r\n"
  14323. "hello");
  14324. auto port = port_future.get();
  14325. ASSERT_GT(port, 0);
  14326. Client cli("127.0.0.1", port);
  14327. auto handle = cli.open_stream("GET", "/");
  14328. EXPECT_FALSE(handle.is_valid());
  14329. server_thread.join();
  14330. }
  14331. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14332. #ifndef _WIN32
  14333. signal(SIGPIPE, SIG_IGN);
  14334. #endif
  14335. std::promise<int> port_promise;
  14336. auto port_future = port_promise.get_future();
  14337. auto server_thread = serve_single_response(
  14338. port_promise, "HTTP/1.1 200 OK\r\n"
  14339. "Content-Type: text/plain\r\n"
  14340. "Content-Length: 99999999999999999999999999\r\n"
  14341. "Connection: close\r\n"
  14342. "\r\n"
  14343. "hello");
  14344. auto port = port_future.get();
  14345. ASSERT_GT(port, 0);
  14346. // Historically std::stoull would throw std::out_of_range here and crash
  14347. // the process, then parsing silently clamped to a bogus framing length and
  14348. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14349. // so the stream fails to open, matching the not-a-number case above. The
  14350. // process still must NOT terminate.
  14351. Client cli("127.0.0.1", port);
  14352. auto handle = cli.open_stream("GET", "/");
  14353. EXPECT_FALSE(handle.is_valid());
  14354. server_thread.join();
  14355. }
  14356. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14357. TEST_F(OpenStreamTest, Gzip) {
  14358. Client cli("127.0.0.1", port_);
  14359. auto handle = cli.open_stream("GET", "/compressible", {},
  14360. {{"Accept-Encoding", "gzip"}});
  14361. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14362. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14363. }
  14364. #endif
  14365. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14366. TEST_F(OpenStreamTest, Brotli) {
  14367. Client cli("127.0.0.1", port_);
  14368. auto handle =
  14369. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14370. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14371. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14372. }
  14373. #endif
  14374. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14375. TEST_F(OpenStreamTest, Zstd) {
  14376. Client cli("127.0.0.1", port_);
  14377. auto handle = cli.open_stream("GET", "/compressible", {},
  14378. {{"Accept-Encoding", "zstd"}});
  14379. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14380. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14381. }
  14382. #endif
  14383. #ifdef CPPHTTPLIB_SSL_ENABLED
  14384. class SSLOpenStreamTest : public ::testing::Test {
  14385. protected:
  14386. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14387. void SetUp() override {
  14388. svr_.Get("/hello", [](const Request &, Response &res) {
  14389. res.set_content("Hello SSL World!", "text/plain");
  14390. });
  14391. svr_.Get("/chunked", [](const Request &, Response &res) {
  14392. res.set_chunked_content_provider("text/plain",
  14393. [](size_t offset, DataSink &sink) {
  14394. if (offset < 15) {
  14395. sink.write("chunk", 5);
  14396. return true;
  14397. }
  14398. sink.done();
  14399. return true;
  14400. });
  14401. });
  14402. svr_.Post("/echo", [](const Request &req, Response &res) {
  14403. res.set_content(req.body, req.get_header_value("Content-Type"));
  14404. });
  14405. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14406. std::string body = req.body;
  14407. res.set_chunked_content_provider(
  14408. "text/plain", [body](size_t offset, DataSink &sink) {
  14409. if (offset < body.size()) {
  14410. sink.write(body.data() + offset, body.size() - offset);
  14411. }
  14412. sink.done();
  14413. return true;
  14414. });
  14415. });
  14416. port_ = svr_.bind_to_any_port("127.0.0.1");
  14417. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14418. svr_.wait_until_ready();
  14419. }
  14420. void TearDown() override {
  14421. svr_.stop();
  14422. if (thread_.joinable()) thread_.join();
  14423. }
  14424. SSLServer svr_;
  14425. std::thread thread_;
  14426. int port_ = 0;
  14427. };
  14428. TEST_F(SSLOpenStreamTest, Basic) {
  14429. SSLClient cli("127.0.0.1", port_);
  14430. cli.enable_server_certificate_verification(false);
  14431. auto handle = cli.open_stream("GET", "/hello");
  14432. ASSERT_TRUE(handle.is_valid());
  14433. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14434. }
  14435. TEST_F(SSLOpenStreamTest, Chunked) {
  14436. SSLClient cli("127.0.0.1", port_);
  14437. cli.enable_server_certificate_verification(false);
  14438. auto handle = cli.open_stream("GET", "/chunked");
  14439. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14440. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14441. "Transfer-Encoding") == "chunked");
  14442. auto body = read_all(handle);
  14443. EXPECT_EQ("chunkchunkchunk", body);
  14444. }
  14445. TEST_F(SSLOpenStreamTest, Post) {
  14446. SSLClient cli("127.0.0.1", port_);
  14447. cli.enable_server_certificate_verification(false);
  14448. auto handle =
  14449. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14450. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14451. EXPECT_EQ(200, handle.response->status);
  14452. auto body = read_all(handle);
  14453. EXPECT_EQ("Hello SSL POST", body);
  14454. }
  14455. TEST_F(SSLOpenStreamTest, PostChunked) {
  14456. SSLClient cli("127.0.0.1", port_);
  14457. cli.enable_server_certificate_verification(false);
  14458. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14459. "Chunked SSL Data", "text/plain");
  14460. ASSERT_TRUE(handle.is_valid());
  14461. EXPECT_EQ(200, handle.response->status);
  14462. auto body = read_all(handle);
  14463. EXPECT_EQ("Chunked SSL Data", body);
  14464. }
  14465. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14466. // Content-Length is terminated by the server closing the connection. When the
  14467. // SSL peer sends a close_notify after the body, the client must treat it as a
  14468. // clean EOF and return a successful response rather than an error.
  14469. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14471. ASSERT_TRUE(svr.is_valid());
  14472. svr.set_keep_alive_max_count(1);
  14473. const std::string expected_body = "Hello from connection-close response!";
  14474. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14475. res.set_content_provider("text/plain",
  14476. [&](size_t offset, DataSink &sink) -> bool {
  14477. if (offset < expected_body.size()) {
  14478. sink.write(expected_body.data() + offset,
  14479. expected_body.size() - offset);
  14480. }
  14481. sink.done();
  14482. return true;
  14483. });
  14484. });
  14485. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14486. auto se = detail::scope_exit([&] {
  14487. svr.stop();
  14488. listen_thread.join();
  14489. ASSERT_FALSE(svr.is_running());
  14490. });
  14491. svr.wait_until_ready();
  14492. SSLClient cli(HOST, PORT);
  14493. cli.enable_server_certificate_verification(false);
  14494. auto res = cli.Get("/no-content-length");
  14495. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14496. EXPECT_EQ(StatusCode::OK_200, res->status);
  14497. EXPECT_EQ(expected_body, res->body);
  14498. }
  14499. #endif // CPPHTTPLIB_SSL_ENABLED
  14500. //==============================================================================
  14501. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14502. // results for various scenarios.
  14503. //==============================================================================
  14504. TEST(ParityTest, GetVsOpenStream) {
  14505. Server svr;
  14506. const std::string path = "/parity";
  14507. const std::string content = "Parity test content: hello world";
  14508. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14509. res.set_content(content, "text/plain");
  14510. });
  14511. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14512. auto se = detail::scope_exit([&] {
  14513. svr.stop();
  14514. t.join();
  14515. ASSERT_FALSE(svr.is_running());
  14516. });
  14517. svr.wait_until_ready();
  14518. Client cli(HOST, PORT);
  14519. // Non-stream path
  14520. auto r1 = cli.Get(path);
  14521. ASSERT_TRUE(r1);
  14522. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14523. // Stream path
  14524. auto h = cli.open_stream("GET", path);
  14525. ASSERT_TRUE(h.is_valid());
  14526. EXPECT_EQ(r1->body, read_all(h));
  14527. }
  14528. // Helper to compress data with provided compressor type T
  14529. template <typename Compressor>
  14530. static std::string compress_payload_for_parity(const std::string &in) {
  14531. std::string out;
  14532. Compressor compressor;
  14533. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14534. [&](const char *data, size_t n) {
  14535. out.append(data, n);
  14536. return true;
  14537. });
  14538. EXPECT_TRUE(ok);
  14539. return out;
  14540. }
  14541. // Helper function for compression parity tests
  14542. template <typename Compressor>
  14543. static void test_compression_parity(const std::string &original,
  14544. const std::string &path,
  14545. const std::string &encoding) {
  14546. const std::string compressed =
  14547. compress_payload_for_parity<Compressor>(original);
  14548. Server svr;
  14549. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14550. res.set_content(compressed, "application/octet-stream");
  14551. res.set_header("Content-Encoding", encoding);
  14552. });
  14553. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14554. auto se = detail::scope_exit([&] {
  14555. svr.stop();
  14556. t.join();
  14557. ASSERT_FALSE(svr.is_running());
  14558. });
  14559. svr.wait_until_ready();
  14560. Client cli(HOST, PORT);
  14561. // Non-streaming
  14562. {
  14563. auto res = cli.Get(path);
  14564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14565. EXPECT_EQ(StatusCode::OK_200, res->status);
  14566. EXPECT_EQ(original, res->body);
  14567. }
  14568. // Streaming
  14569. {
  14570. auto h = cli.open_stream("GET", path);
  14571. ASSERT_TRUE(h.is_valid());
  14572. EXPECT_EQ(original, read_all(h));
  14573. }
  14574. }
  14575. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14576. TEST(ParityTest, Gzip) {
  14577. test_compression_parity<detail::gzip_compressor>(
  14578. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14579. }
  14580. #endif
  14581. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14582. TEST(ParityTest, Brotli) {
  14583. test_compression_parity<detail::brotli_compressor>(
  14584. "Hello, brotli parity test payload", "/parity-br", "br");
  14585. }
  14586. #endif
  14587. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14588. TEST(ParityTest, Zstd) {
  14589. test_compression_parity<detail::zstd_compressor>(
  14590. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14591. }
  14592. #endif
  14593. //==============================================================================
  14594. // New Stream API Tests
  14595. //==============================================================================
  14596. inline std::string read_body(httplib::stream::Result &result) {
  14597. std::string body;
  14598. while (result.next()) {
  14599. body.append(result.data(), result.size());
  14600. }
  14601. return body;
  14602. }
  14603. TEST(ClientConnectionTest, Basic) {
  14604. httplib::ClientConnection conn;
  14605. EXPECT_FALSE(conn.is_open());
  14606. conn.sock = 1;
  14607. EXPECT_TRUE(conn.is_open());
  14608. httplib::ClientConnection conn2(std::move(conn));
  14609. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14610. conn2.sock = INVALID_SOCKET;
  14611. }
  14612. // Unified test server for all stream::* tests
  14613. class StreamApiTest : public ::testing::Test {
  14614. protected:
  14615. void SetUp() override {
  14616. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14617. res.set_content("Hello World!", "text/plain");
  14618. });
  14619. svr_.Get("/echo-params",
  14620. [](const httplib::Request &req, httplib::Response &res) {
  14621. std::string r;
  14622. for (const auto &p : req.params) {
  14623. if (!r.empty()) r += "&";
  14624. r += p.first + "=" + p.second;
  14625. }
  14626. res.set_content(r, "text/plain");
  14627. });
  14628. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14629. res.set_content(req.body, req.get_header_value("Content-Type"));
  14630. });
  14631. svr_.Post("/echo-headers",
  14632. [](const httplib::Request &req, httplib::Response &res) {
  14633. std::string r;
  14634. for (const auto &h : req.headers)
  14635. r += h.first + ": " + h.second + "\n";
  14636. res.set_content(r, "text/plain");
  14637. });
  14638. svr_.Post("/echo-params",
  14639. [](const httplib::Request &req, httplib::Response &res) {
  14640. std::string r = "params:";
  14641. for (const auto &p : req.params)
  14642. r += p.first + "=" + p.second + ";";
  14643. res.set_content(r + " body:" + req.body, "text/plain");
  14644. });
  14645. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14646. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14647. });
  14648. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14649. res.set_content("PUT:" + req.body, "text/plain");
  14650. });
  14651. svr_.Patch("/echo",
  14652. [](const httplib::Request &req, httplib::Response &res) {
  14653. res.set_content("PATCH:" + req.body, "text/plain");
  14654. });
  14655. svr_.Delete(
  14656. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14657. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14658. "text/plain");
  14659. });
  14660. svr_.Get("/head-test",
  14661. [](const httplib::Request &, httplib::Response &res) {
  14662. res.set_content("body for HEAD", "text/plain");
  14663. });
  14664. svr_.Options("/options",
  14665. [](const httplib::Request &, httplib::Response &res) {
  14666. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14667. });
  14668. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14669. svr_.wait_until_ready();
  14670. }
  14671. void TearDown() override {
  14672. svr_.stop();
  14673. if (thread_.joinable()) thread_.join();
  14674. }
  14675. httplib::Server svr_;
  14676. std::thread thread_;
  14677. };
  14678. // stream::Get tests
  14679. TEST_F(StreamApiTest, GetBasic) {
  14680. httplib::Client cli(HOST, PORT);
  14681. auto result = httplib::stream::Get(cli, "/hello");
  14682. ASSERT_TRUE(result.is_valid());
  14683. EXPECT_EQ(200, result.status());
  14684. EXPECT_EQ("Hello World!", read_body(result));
  14685. }
  14686. TEST_F(StreamApiTest, GetWithParams) {
  14687. httplib::Client cli(HOST, PORT);
  14688. httplib::Params params{{"foo", "bar"}};
  14689. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14690. ASSERT_TRUE(result.is_valid());
  14691. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14692. }
  14693. TEST_F(StreamApiTest, GetConnectionError) {
  14694. httplib::Client cli(HOST, 9999);
  14695. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14696. }
  14697. TEST_F(StreamApiTest, Get404) {
  14698. httplib::Client cli(HOST, PORT);
  14699. auto result = httplib::stream::Get(cli, "/nonexistent");
  14700. EXPECT_TRUE(result.is_valid());
  14701. EXPECT_EQ(404, result.status());
  14702. }
  14703. // stream::Post tests
  14704. TEST_F(StreamApiTest, PostBasic) {
  14705. httplib::Client cli(HOST, PORT);
  14706. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14707. "application/json");
  14708. ASSERT_TRUE(result.is_valid());
  14709. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14710. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14711. }
  14712. TEST_F(StreamApiTest, PostWithHeaders) {
  14713. httplib::Client cli(HOST, PORT);
  14714. httplib::Headers headers{{"X-Custom", "value"}};
  14715. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14716. "text/plain");
  14717. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14718. }
  14719. TEST_F(StreamApiTest, PostWithParams) {
  14720. httplib::Client cli(HOST, PORT);
  14721. httplib::Params params{{"k", "v"}};
  14722. auto result =
  14723. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14724. auto body = read_body(result);
  14725. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14726. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14727. }
  14728. TEST_F(StreamApiTest, PostLarge) {
  14729. httplib::Client cli(HOST, PORT);
  14730. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14731. size_t total = 0;
  14732. while (result.next()) {
  14733. total += result.size();
  14734. }
  14735. EXPECT_EQ(100u * 1024u, total);
  14736. }
  14737. // stream::Put/Patch tests
  14738. TEST_F(StreamApiTest, PutAndPatch) {
  14739. httplib::Client cli(HOST, PORT);
  14740. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14741. EXPECT_EQ("PUT:test", read_body(put));
  14742. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14743. EXPECT_EQ("PATCH:test", read_body(patch));
  14744. }
  14745. // stream::Delete tests
  14746. TEST_F(StreamApiTest, Delete) {
  14747. httplib::Client cli(HOST, PORT);
  14748. auto del1 = httplib::stream::Delete(cli, "/resource");
  14749. EXPECT_EQ("Deleted", read_body(del1));
  14750. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14751. EXPECT_EQ("Deleted:data", read_body(del2));
  14752. }
  14753. // stream::Head/Options tests
  14754. TEST_F(StreamApiTest, HeadAndOptions) {
  14755. httplib::Client cli(HOST, PORT);
  14756. auto head = httplib::stream::Head(cli, "/head-test");
  14757. EXPECT_TRUE(head.is_valid());
  14758. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14759. auto opts = httplib::stream::Options(cli, "/options");
  14760. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14761. }
  14762. // SSL stream::* tests
  14763. #ifdef CPPHTTPLIB_SSL_ENABLED
  14764. class SSLStreamApiTest : public ::testing::Test {
  14765. protected:
  14766. void SetUp() override {
  14767. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14768. res.set_content("Hello SSL!", "text/plain");
  14769. });
  14770. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14771. res.set_content(req.body, "text/plain");
  14772. });
  14773. port_ = svr_.bind_to_any_port("127.0.0.1");
  14774. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14775. svr_.wait_until_ready();
  14776. }
  14777. void TearDown() override {
  14778. svr_.stop();
  14779. if (thread_.joinable()) thread_.join();
  14780. }
  14781. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14782. std::thread thread_;
  14783. int port_ = 0;
  14784. };
  14785. TEST_F(SSLStreamApiTest, GetAndPost) {
  14786. httplib::SSLClient cli("127.0.0.1", port_);
  14787. cli.enable_server_certificate_verification(false);
  14788. auto get = httplib::stream::Get(cli, "/hello");
  14789. EXPECT_EQ("Hello SSL!", read_body(get));
  14790. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14791. EXPECT_EQ("test", read_body(post));
  14792. }
  14793. #endif
  14794. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14795. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14796. // BodyReader
  14797. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14798. // Test that read timeout during streaming is detected
  14799. // Use a large content-length response where server delays mid-stream
  14800. Server svr;
  14801. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14802. // Send a large response with delay in the middle
  14803. res.set_content_provider(
  14804. 1000, // content_length
  14805. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14806. if (offset < 100) {
  14807. // Send first 100 bytes immediately
  14808. std::string data(100, 'A');
  14809. sink.write(data.c_str(), data.size());
  14810. return true;
  14811. }
  14812. // Then delay longer than client timeout
  14813. std::this_thread::sleep_for(std::chrono::seconds(3));
  14814. std::string data(900, 'B');
  14815. sink.write(data.c_str(), data.size());
  14816. return true;
  14817. });
  14818. });
  14819. auto port = 8091;
  14820. std::thread t([&]() { svr.listen("localhost", port); });
  14821. svr.wait_until_ready();
  14822. Client cli("localhost", port);
  14823. cli.set_read_timeout(1, 0); // 1 second timeout
  14824. auto handle = cli.open_stream("GET", "/slow-stream");
  14825. ASSERT_TRUE(handle.is_valid());
  14826. char buf[256];
  14827. ssize_t total = 0;
  14828. ssize_t n;
  14829. bool got_error = false;
  14830. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14831. total += n;
  14832. }
  14833. if (n < 0) {
  14834. got_error = true;
  14835. // Should be timeout or read error
  14836. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14837. handle.get_read_error() == Error::Read)
  14838. << "Actual error: " << to_string(handle.get_read_error());
  14839. }
  14840. // Either we got an error, or we got less data than expected
  14841. EXPECT_TRUE(got_error || total < 1000)
  14842. << "Expected timeout but got all " << total << " bytes";
  14843. svr.stop();
  14844. t.join();
  14845. }
  14846. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14847. // Test connection closed detection via BodyReader
  14848. Server svr;
  14849. std::atomic<bool> close_now{false};
  14850. svr.Get("/will-close", [&](const Request &, Response &res) {
  14851. res.set_content_provider(
  14852. 10000, // Large content_length that we won't fully send
  14853. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14854. if (offset < 100) {
  14855. std::string data(100, 'X');
  14856. sink.write(data.c_str(), data.size());
  14857. return true;
  14858. }
  14859. // Wait for signal then abort
  14860. while (!close_now) {
  14861. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14862. }
  14863. return false; // Abort - server will close connection
  14864. });
  14865. });
  14866. auto port = 8092;
  14867. std::thread t([&]() { svr.listen("localhost", port); });
  14868. svr.wait_until_ready();
  14869. Client cli("localhost", port);
  14870. auto handle = cli.open_stream("GET", "/will-close");
  14871. ASSERT_TRUE(handle.is_valid());
  14872. char buf[256];
  14873. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14874. EXPECT_GT(n, 0) << "First read should succeed";
  14875. // Signal server to close
  14876. close_now = true;
  14877. // Keep reading until error or EOF
  14878. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14879. // Keep reading
  14880. }
  14881. // Should get an error since content_length wasn't satisfied
  14882. if (n < 0) {
  14883. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14884. handle.get_read_error() == Error::Read)
  14885. << "Actual error: " << to_string(handle.get_read_error());
  14886. }
  14887. svr.stop();
  14888. t.join();
  14889. }
  14890. #ifdef CPPHTTPLIB_SSL_ENABLED
  14891. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14892. // Test that read timeout during SSL streaming is detected
  14893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14894. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14895. res.set_content_provider(
  14896. 1000, "text/plain",
  14897. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14898. if (offset < 100) {
  14899. std::string data(100, 'A');
  14900. sink.write(data.c_str(), data.size());
  14901. return true;
  14902. }
  14903. std::this_thread::sleep_for(std::chrono::seconds(3));
  14904. std::string data(900, 'B');
  14905. sink.write(data.c_str(), data.size());
  14906. return true;
  14907. });
  14908. });
  14909. auto port = 8093;
  14910. std::thread t([&]() { svr.listen("localhost", port); });
  14911. svr.wait_until_ready();
  14912. SSLClient cli("localhost", port);
  14913. cli.enable_server_certificate_verification(false);
  14914. cli.set_read_timeout(1, 0); // 1 second timeout
  14915. auto handle = cli.open_stream("GET", "/slow-stream");
  14916. ASSERT_TRUE(handle.is_valid());
  14917. char buf[256];
  14918. ssize_t total = 0;
  14919. ssize_t n;
  14920. bool got_error = false;
  14921. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14922. total += n;
  14923. }
  14924. if (n < 0) {
  14925. got_error = true;
  14926. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14927. handle.get_read_error() == Error::Read)
  14928. << "Actual error: " << to_string(handle.get_read_error());
  14929. }
  14930. EXPECT_TRUE(got_error || total < 1000)
  14931. << "Expected timeout but got all " << total << " bytes";
  14932. svr.stop();
  14933. t.join();
  14934. }
  14935. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14936. // Test SSL connection closed detection
  14937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14938. std::atomic<bool> close_now{false};
  14939. svr.Get("/will-close", [&](const Request &, Response &res) {
  14940. res.set_content_provider(
  14941. 10000, "text/plain",
  14942. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14943. if (offset < 100) {
  14944. std::string data(100, 'X');
  14945. sink.write(data.c_str(), data.size());
  14946. return true;
  14947. }
  14948. while (!close_now) {
  14949. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14950. }
  14951. return false;
  14952. });
  14953. });
  14954. auto port = 8094;
  14955. std::thread t([&]() { svr.listen("localhost", port); });
  14956. svr.wait_until_ready();
  14957. SSLClient cli("localhost", port);
  14958. cli.enable_server_certificate_verification(false);
  14959. auto handle = cli.open_stream("GET", "/will-close");
  14960. ASSERT_TRUE(handle.is_valid());
  14961. char buf[256];
  14962. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14963. EXPECT_GT(n, 0);
  14964. // Signal server to close
  14965. close_now = true;
  14966. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14967. // Keep reading
  14968. }
  14969. if (n < 0) {
  14970. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14971. handle.get_read_error() == Error::Read)
  14972. << "Actual error: " << to_string(handle.get_read_error());
  14973. }
  14974. svr.stop();
  14975. t.join();
  14976. }
  14977. #endif
  14978. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14979. using namespace httplib;
  14980. // Create a test file
  14981. const char *fname = "etag_testfile.txt";
  14982. const char *content = "etag-content";
  14983. {
  14984. std::ofstream ofs(fname);
  14985. ofs << content;
  14986. ASSERT_TRUE(ofs.good());
  14987. }
  14988. Server svr;
  14989. svr.set_mount_point("/static", ".");
  14990. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14991. svr.wait_until_ready();
  14992. Client cli(HOST, PORT);
  14993. // First request: should get 200 with ETag header
  14994. auto res1 = cli.Get("/static/etag_testfile.txt");
  14995. ASSERT_TRUE(res1);
  14996. ASSERT_EQ(200, res1->status);
  14997. ASSERT_TRUE(res1->has_header("ETag"));
  14998. std::string etag = res1->get_header_value("ETag");
  14999. EXPECT_FALSE(etag.empty());
  15000. // Verify ETag format: W/"hex-hex"
  15001. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15002. EXPECT_EQ('W', etag[0]);
  15003. EXPECT_EQ('/', etag[1]);
  15004. EXPECT_EQ('"', etag[2]);
  15005. EXPECT_EQ('"', etag.back());
  15006. // Exact match: expect 304 Not Modified
  15007. Headers h2 = {{"If-None-Match", etag}};
  15008. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15009. ASSERT_TRUE(res2);
  15010. EXPECT_EQ(304, res2->status);
  15011. // Wildcard match: expect 304 Not Modified
  15012. Headers h3 = {{"If-None-Match", "*"}};
  15013. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15014. ASSERT_TRUE(res3);
  15015. EXPECT_EQ(304, res3->status);
  15016. // Non-matching ETag: expect 200
  15017. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15018. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15019. ASSERT_TRUE(res4);
  15020. EXPECT_EQ(200, res4->status);
  15021. // Multiple ETags with one matching: expect 304
  15022. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15023. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15024. ASSERT_TRUE(res5);
  15025. EXPECT_EQ(304, res5->status);
  15026. svr.stop();
  15027. t.join();
  15028. std::remove(fname);
  15029. }
  15030. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15031. using namespace httplib;
  15032. Server svr;
  15033. svr.set_mount_point("/static", ".");
  15034. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15035. svr.wait_until_ready();
  15036. Client cli(HOST, PORT);
  15037. // Send If-None-Match: * to a non-existent file
  15038. Headers h = {{"If-None-Match", "*"}};
  15039. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15041. EXPECT_EQ(404, res->status);
  15042. svr.stop();
  15043. t.join();
  15044. }
  15045. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15046. using namespace httplib;
  15047. // Create a test file
  15048. const char *fname = "etag_boundary_testfile.txt";
  15049. const char *content = "boundary-test";
  15050. {
  15051. std::ofstream ofs(fname);
  15052. ofs << content;
  15053. ASSERT_TRUE(ofs.good());
  15054. }
  15055. Server svr;
  15056. svr.set_mount_point("/static", ".");
  15057. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15058. svr.wait_until_ready();
  15059. Client cli(HOST, PORT);
  15060. // Get the actual ETag
  15061. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15062. ASSERT_TRUE(res1);
  15063. ASSERT_EQ(200, res1->status);
  15064. ASSERT_TRUE(res1->has_header("ETag"));
  15065. std::string etag = res1->get_header_value("ETag");
  15066. // Test 1: Very long ETag value (longer than actual ETag)
  15067. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15068. Headers h1 = {{"If-None-Match", "W/"
  15069. "\"very-long-etag-value-that-is-much-longer-"
  15070. "than-the-actual-etag-value\""}};
  15071. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15072. ASSERT_TRUE(res2);
  15073. EXPECT_EQ(200, res2->status); // Should not match
  15074. // Test 2: Long string followed by wildcard
  15075. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15076. // string)
  15077. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15078. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15079. ASSERT_TRUE(res3);
  15080. EXPECT_EQ(304, res3->status); // Should match on "*"
  15081. // Test 3: Wildcard followed by long string
  15082. // Should match on "*" immediately and return 304
  15083. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15084. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15085. ASSERT_TRUE(res4);
  15086. EXPECT_EQ(304, res4->status); // Should match on "*"
  15087. // Test 4: Multiple long non-matching values
  15088. // Should NOT match and return 200 (test that all comparisons are safe)
  15089. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15090. "W/\"second-long-non-matching-value\", "
  15091. "W/\"third-long-non-matching-value\""}};
  15092. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15093. ASSERT_TRUE(res5);
  15094. EXPECT_EQ(200, res5->status); // Should not match
  15095. // Test 5: Single character that is not "*" (edge case)
  15096. Headers h5 = {{"If-None-Match", "X"}};
  15097. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15098. ASSERT_TRUE(res6);
  15099. EXPECT_EQ(200, res6->status); // Should not match
  15100. svr.stop();
  15101. t.join();
  15102. std::remove(fname);
  15103. }
  15104. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15105. using namespace httplib;
  15106. // Create a test file
  15107. const char *fname = "ims_testfile.txt";
  15108. const char *content = "if-modified-since-test";
  15109. {
  15110. std::ofstream ofs(fname);
  15111. ofs << content;
  15112. ASSERT_TRUE(ofs.good());
  15113. }
  15114. Server svr;
  15115. svr.set_mount_point("/static", ".");
  15116. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15117. svr.wait_until_ready();
  15118. Client cli(HOST, PORT);
  15119. // First request: should get 200 with Last-Modified header
  15120. auto res1 = cli.Get("/static/ims_testfile.txt");
  15121. ASSERT_TRUE(res1);
  15122. ASSERT_EQ(200, res1->status);
  15123. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15124. std::string last_modified = res1->get_header_value("Last-Modified");
  15125. EXPECT_FALSE(last_modified.empty());
  15126. // If-Modified-Since with same time: expect 304
  15127. Headers h2 = {{"If-Modified-Since", last_modified}};
  15128. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15129. ASSERT_TRUE(res2);
  15130. EXPECT_EQ(304, res2->status);
  15131. // If-Modified-Since with future time: expect 304
  15132. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15133. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15134. ASSERT_TRUE(res3);
  15135. EXPECT_EQ(304, res3->status);
  15136. // If-Modified-Since with past time: expect 200
  15137. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15138. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15139. ASSERT_TRUE(res4);
  15140. EXPECT_EQ(200, res4->status);
  15141. // If-None-Match takes precedence over If-Modified-Since
  15142. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15143. ASSERT_TRUE(res1->has_header("ETag"));
  15144. std::string etag = res1->get_header_value("ETag");
  15145. Headers h5 = {{"If-None-Match", etag},
  15146. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15147. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15148. ASSERT_TRUE(res5);
  15149. EXPECT_EQ(304, res5->status);
  15150. svr.stop();
  15151. t.join();
  15152. std::remove(fname);
  15153. }
  15154. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15155. using namespace httplib;
  15156. Server svr;
  15157. // Endpoint that returns compressible content
  15158. svr.Get("/compressible", [](const Request &, Response &res) {
  15159. // Return a large enough body to trigger compression
  15160. std::string body(1000, 'a');
  15161. res.set_content(body, "text/plain");
  15162. });
  15163. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15164. svr.wait_until_ready();
  15165. Client cli(HOST, PORT);
  15166. // Request with gzip support: should get Vary header when compressed
  15167. cli.set_compress(true);
  15168. auto res1 = cli.Get("/compressible");
  15169. ASSERT_TRUE(res1);
  15170. EXPECT_EQ(200, res1->status);
  15171. // If Content-Encoding is set, Vary should also be set
  15172. if (res1->has_header("Content-Encoding")) {
  15173. EXPECT_TRUE(res1->has_header("Vary"));
  15174. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15175. }
  15176. // Request without Accept-Encoding header: should not have compression
  15177. Headers h_no_compress;
  15178. auto res2 = cli.Get("/compressible", h_no_compress);
  15179. ASSERT_TRUE(res2);
  15180. EXPECT_EQ(200, res2->status);
  15181. // Verify Vary header is present when compression is applied
  15182. // (the exact behavior depends on server configuration)
  15183. svr.stop();
  15184. t.join();
  15185. }
  15186. TEST(ETagTest, IfRangeWithETag) {
  15187. using namespace httplib;
  15188. // Create a test file with known content
  15189. const char *fname = "if_range_testfile.txt";
  15190. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15191. {
  15192. std::ofstream ofs(fname);
  15193. ofs << content;
  15194. ASSERT_TRUE(ofs.good());
  15195. }
  15196. Server svr;
  15197. svr.set_mount_point("/static", ".");
  15198. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15199. svr.wait_until_ready();
  15200. Client cli(HOST, PORT);
  15201. // First request: get ETag
  15202. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15203. ASSERT_TRUE(res1);
  15204. ASSERT_EQ(200, res1->status);
  15205. ASSERT_TRUE(res1->has_header("ETag"));
  15206. std::string etag = res1->get_header_value("ETag");
  15207. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15208. // Since our server generates weak ETags (W/"..."), If-Range with our
  15209. // ETag should NOT result in partial content - it should return full content.
  15210. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15211. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15212. ASSERT_TRUE(res2);
  15213. // Weak ETag in If-Range -> full content (200), not partial (206)
  15214. EXPECT_EQ(200, res2->status);
  15215. EXPECT_EQ(content, res2->body);
  15216. EXPECT_FALSE(res2->has_header("Content-Range"));
  15217. // Range request with non-matching If-Range (ETag): should get 200 (full
  15218. // content)
  15219. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15220. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15221. ASSERT_TRUE(res3);
  15222. EXPECT_EQ(200, res3->status);
  15223. EXPECT_EQ(content, res3->body);
  15224. EXPECT_FALSE(res3->has_header("Content-Range"));
  15225. // Range request with strong ETag (hypothetical - our server doesn't generate
  15226. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15227. // should return full content)
  15228. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15229. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15230. ASSERT_TRUE(res4);
  15231. EXPECT_EQ(200, res4->status);
  15232. EXPECT_EQ(content, res4->body);
  15233. EXPECT_FALSE(res4->has_header("Content-Range"));
  15234. svr.stop();
  15235. t.join();
  15236. std::remove(fname);
  15237. }
  15238. TEST(ETagTest, IfRangeWithDate) {
  15239. using namespace httplib;
  15240. // Create a test file
  15241. const char *fname = "if_range_date_testfile.txt";
  15242. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15243. {
  15244. std::ofstream ofs(fname);
  15245. ofs << content;
  15246. ASSERT_TRUE(ofs.good());
  15247. }
  15248. Server svr;
  15249. svr.set_mount_point("/static", ".");
  15250. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15251. svr.wait_until_ready();
  15252. Client cli(HOST, PORT);
  15253. // First request: get Last-Modified
  15254. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15255. ASSERT_TRUE(res1);
  15256. ASSERT_EQ(200, res1->status);
  15257. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15258. std::string last_modified = res1->get_header_value("Last-Modified");
  15259. // Range request with matching If-Range (date): should get 206
  15260. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15261. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15262. ASSERT_TRUE(res2);
  15263. EXPECT_EQ(206, res2->status);
  15264. EXPECT_EQ("FGHIJ", res2->body);
  15265. // Range request with old If-Range date: should get 200 (full content)
  15266. Headers h3 = {{"Range", "bytes=5-9"},
  15267. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15268. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15269. ASSERT_TRUE(res3);
  15270. EXPECT_EQ(200, res3->status);
  15271. EXPECT_EQ(content, res3->body);
  15272. // Range request with future If-Range date: should get 206
  15273. Headers h4 = {{"Range", "bytes=0-4"},
  15274. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15275. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15276. ASSERT_TRUE(res4);
  15277. EXPECT_EQ(206, res4->status);
  15278. EXPECT_EQ("ABCDE", res4->body);
  15279. svr.stop();
  15280. t.join();
  15281. std::remove(fname);
  15282. }
  15283. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15284. using namespace httplib;
  15285. const char *fname = "etag_malformed.txt";
  15286. const char *content = "malformed-etag";
  15287. {
  15288. std::ofstream ofs(fname);
  15289. ofs << content;
  15290. ASSERT_TRUE(ofs.good());
  15291. }
  15292. Server svr;
  15293. svr.set_mount_point("/static", ".");
  15294. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15295. svr.wait_until_ready();
  15296. Client cli(HOST, PORT);
  15297. // baseline: should get 200 and an ETag
  15298. auto res1 = cli.Get("/static/etag_malformed.txt");
  15299. ASSERT_TRUE(res1);
  15300. ASSERT_EQ(200, res1->status);
  15301. ASSERT_TRUE(res1->has_header("ETag"));
  15302. // Malformed ETag value (missing quotes) should be treated as non-matching
  15303. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15304. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15305. ASSERT_TRUE(res_bad);
  15306. EXPECT_EQ(200, res_bad->status);
  15307. // Whitespace-only header value should be considered invalid / non-matching
  15308. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15309. "Host: localhost\r\n"
  15310. "If-None-Match: \r\n"
  15311. "Connection: close\r\n"
  15312. "\r\n";
  15313. std::string out;
  15314. ASSERT_TRUE(send_request(5, raw_req, &out));
  15315. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15316. svr.stop();
  15317. t.join();
  15318. std::remove(fname);
  15319. }
  15320. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15321. using namespace httplib;
  15322. const char *fname = "ims_invalid_format.txt";
  15323. const char *content = "ims-bad-format";
  15324. {
  15325. std::ofstream ofs(fname);
  15326. ofs << content;
  15327. ASSERT_TRUE(ofs.good());
  15328. }
  15329. Server svr;
  15330. svr.set_mount_point("/static", ".");
  15331. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15332. svr.wait_until_ready();
  15333. Client cli(HOST, PORT);
  15334. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15335. ASSERT_TRUE(res1);
  15336. ASSERT_EQ(200, res1->status);
  15337. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15338. // If-Modified-Since with invalid format should not result in 304
  15339. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15340. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15341. ASSERT_TRUE(res_bad);
  15342. EXPECT_EQ(200, res_bad->status);
  15343. // If-Range with invalid date format should be treated as mismatch -> full
  15344. // content (200)
  15345. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15346. {"If-Range", "invalid-date"}};
  15347. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15348. ASSERT_TRUE(res_ifrange);
  15349. EXPECT_EQ(200, res_ifrange->status);
  15350. svr.stop();
  15351. t.join();
  15352. std::remove(fname);
  15353. }
  15354. TEST(ETagTest, IfRangeWithMalformedETag) {
  15355. using namespace httplib;
  15356. const char *fname = "ifrange_malformed.txt";
  15357. const std::string content = "0123456789";
  15358. {
  15359. std::ofstream ofs(fname);
  15360. ofs << content;
  15361. ASSERT_TRUE(ofs.good());
  15362. }
  15363. Server svr;
  15364. svr.set_mount_point("/static", ".");
  15365. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15366. svr.wait_until_ready();
  15367. Client cli(HOST, PORT);
  15368. // First request: get ETag
  15369. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15370. ASSERT_TRUE(res1);
  15371. ASSERT_EQ(200, res1->status);
  15372. ASSERT_TRUE(res1->has_header("ETag"));
  15373. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15374. // full content (200)
  15375. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15376. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15377. ASSERT_TRUE(res2);
  15378. EXPECT_EQ(200, res2->status);
  15379. EXPECT_EQ(content, res2->body);
  15380. svr.stop();
  15381. t.join();
  15382. std::remove(fname);
  15383. }
  15384. TEST(ETagTest, ExtremeLargeDateValues) {
  15385. using namespace httplib;
  15386. const char *fname = "ims_extreme_date.txt";
  15387. const char *content = "ims-extreme-date";
  15388. {
  15389. std::ofstream ofs(fname);
  15390. ofs << content;
  15391. ASSERT_TRUE(ofs.good());
  15392. }
  15393. Server svr;
  15394. svr.set_mount_point("/static", ".");
  15395. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15396. svr.wait_until_ready();
  15397. Client cli(HOST, PORT);
  15398. auto res1 = cli.Get(std::string("/static/") + fname);
  15399. ASSERT_TRUE(res1);
  15400. ASSERT_EQ(200, res1->status);
  15401. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15402. // Extremely large year that may overflow date parsing routines.
  15403. Headers h_large_date = {
  15404. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15405. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15406. ASSERT_TRUE(res_bad);
  15407. // Expect server to treat this as invalid/mismatch and return full content
  15408. EXPECT_EQ(200, res_bad->status);
  15409. // If-Range with extremely large date should be treated as mismatch -> full
  15410. // content (200)
  15411. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15412. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15413. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15414. ASSERT_TRUE(res_ifrange);
  15415. EXPECT_EQ(200, res_ifrange->status);
  15416. svr.stop();
  15417. t.join();
  15418. std::remove(fname);
  15419. }
  15420. TEST(ETagTest, NegativeFileModificationTime) {
  15421. using namespace httplib;
  15422. const char *fname = "ims_negative_mtime.txt";
  15423. const std::string content = "negative-mtime";
  15424. {
  15425. std::ofstream ofs(fname);
  15426. ofs << content;
  15427. ASSERT_TRUE(ofs.good());
  15428. }
  15429. // Try to set file mtime to a negative value. This may fail on some
  15430. // platforms/filesystems; if it fails, the test will still verify server
  15431. // behaves safely by performing a regular conditional request.
  15432. #if defined(__APPLE__) || defined(__linux__)
  15433. bool set_negative = false;
  15434. do {
  15435. struct timeval times[2];
  15436. // access time: now
  15437. times[0].tv_sec = time(nullptr);
  15438. times[0].tv_usec = 0;
  15439. // modification time: negative (e.g., -1)
  15440. times[1].tv_sec = -1;
  15441. times[1].tv_usec = 0;
  15442. if (utimes(fname, times) == 0) { set_negative = true; }
  15443. } while (0);
  15444. #else
  15445. bool set_negative = false;
  15446. #endif
  15447. Server svr;
  15448. svr.set_mount_point("/static", ".");
  15449. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15450. svr.wait_until_ready();
  15451. Client cli(HOST, PORT);
  15452. auto res1 = cli.Get(std::string("/static/") + fname);
  15453. ASSERT_TRUE(res1);
  15454. ASSERT_EQ(200, res1->status);
  15455. bool has_last_modified = res1->has_header("Last-Modified");
  15456. std::string last_modified;
  15457. if (has_last_modified) {
  15458. last_modified = res1->get_header_value("Last-Modified");
  15459. }
  15460. if (set_negative) {
  15461. // If we successfully set a negative mtime, ensure server returns a
  15462. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15463. // with an old date and ensure server handles it without crash.
  15464. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15465. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15466. ASSERT_TRUE(res2);
  15467. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15468. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15469. } else {
  15470. // Could not set negative mtime on this platform; fall back to verifying
  15471. // that normal invalid/malformed dates are treated safely (non-304).
  15472. Headers h_bad_date = {
  15473. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15474. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15475. ASSERT_TRUE(res_bad);
  15476. EXPECT_EQ(200, res_bad->status);
  15477. }
  15478. svr.stop();
  15479. t.join();
  15480. std::remove(fname);
  15481. }
  15482. //==============================================================================
  15483. // SSE Parsing Tests
  15484. //==============================================================================
  15485. class SSEParsingTest : public ::testing::Test {
  15486. protected:
  15487. // Test helper that mimics SSE parsing behavior
  15488. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15489. int &retry_ms) {
  15490. // Blank line signals end of event
  15491. if (line.empty() || line == "\r") { return true; }
  15492. // Lines starting with ':' are comments (ignored)
  15493. if (!line.empty() && line[0] == ':') { return false; }
  15494. // Find the colon separator
  15495. auto colon_pos = line.find(':');
  15496. if (colon_pos == std::string::npos) {
  15497. // Line with no colon is treated as field name with empty value
  15498. return false;
  15499. }
  15500. std::string field = line.substr(0, colon_pos);
  15501. std::string value;
  15502. // Value starts after colon, skip optional single space
  15503. if (colon_pos + 1 < line.size()) {
  15504. size_t value_start = colon_pos + 1;
  15505. if (line[value_start] == ' ') { value_start++; }
  15506. value = line.substr(value_start);
  15507. // Remove trailing \r if present
  15508. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15509. }
  15510. // Handle known fields
  15511. if (field == "event") {
  15512. msg.event = value;
  15513. } else if (field == "data") {
  15514. // Multiple data lines are concatenated with newlines
  15515. if (!msg.data.empty()) { msg.data += "\n"; }
  15516. msg.data += value;
  15517. } else if (field == "id") {
  15518. // Empty id is valid (clears the last event ID)
  15519. msg.id = value;
  15520. } else if (field == "retry") {
  15521. // Parse retry interval in milliseconds
  15522. {
  15523. int v = 0;
  15524. auto res =
  15525. detail::from_chars(value.data(), value.data() + value.size(), v);
  15526. if (res.ec == std::errc{}) { retry_ms = v; }
  15527. }
  15528. }
  15529. // Unknown fields are ignored per SSE spec
  15530. return false;
  15531. }
  15532. };
  15533. // Test: Single-line data
  15534. TEST_F(SSEParsingTest, SingleLineData) {
  15535. sse::SSEMessage msg;
  15536. int retry_ms = 3000;
  15537. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15538. EXPECT_EQ(msg.data, "hello");
  15539. EXPECT_EQ(msg.event, "message");
  15540. // Blank line ends event
  15541. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15542. }
  15543. // Test: Multi-line data
  15544. TEST_F(SSEParsingTest, MultiLineData) {
  15545. sse::SSEMessage msg;
  15546. int retry_ms = 3000;
  15547. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15548. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15549. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15550. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15551. }
  15552. // Test: Custom event types
  15553. TEST_F(SSEParsingTest, CustomEventType) {
  15554. sse::SSEMessage msg;
  15555. int retry_ms = 3000;
  15556. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15557. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15558. EXPECT_EQ(msg.event, "update");
  15559. EXPECT_EQ(msg.data, "payload");
  15560. }
  15561. // Test: Event ID handling
  15562. TEST_F(SSEParsingTest, EventIdHandling) {
  15563. sse::SSEMessage msg;
  15564. int retry_ms = 3000;
  15565. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15566. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15567. EXPECT_EQ(msg.id, "12345");
  15568. }
  15569. // Test: Empty event ID (clears last event ID)
  15570. TEST_F(SSEParsingTest, EmptyEventId) {
  15571. sse::SSEMessage msg;
  15572. msg.id = "previous";
  15573. int retry_ms = 3000;
  15574. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15575. EXPECT_EQ(msg.id, "");
  15576. }
  15577. // Test: Retry field parsing
  15578. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15579. sse::SSEMessage msg;
  15580. int retry_ms = 3000;
  15581. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15582. EXPECT_EQ(retry_ms, 5000);
  15583. }
  15584. // Test: Invalid retry value
  15585. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15586. sse::SSEMessage msg;
  15587. int retry_ms = 3000;
  15588. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15589. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15590. }
  15591. // Test: Comments (lines starting with :)
  15592. TEST_F(SSEParsingTest, CommentsIgnored) {
  15593. sse::SSEMessage msg;
  15594. int retry_ms = 3000;
  15595. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15596. EXPECT_EQ(msg.data, "");
  15597. EXPECT_EQ(msg.event, "message");
  15598. }
  15599. // Test: Colon in value
  15600. TEST_F(SSEParsingTest, ColonInValue) {
  15601. sse::SSEMessage msg;
  15602. int retry_ms = 3000;
  15603. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15604. EXPECT_EQ(msg.data, "hello:world:test");
  15605. }
  15606. // Test: Line with no colon (field name only)
  15607. TEST_F(SSEParsingTest, FieldNameOnly) {
  15608. sse::SSEMessage msg;
  15609. int retry_ms = 3000;
  15610. // According to SSE spec, this is treated as field name with empty value
  15611. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15612. // Since we don't recognize "data" without colon, data should be empty
  15613. EXPECT_EQ(msg.data, "");
  15614. }
  15615. // Test: Trailing \r handling
  15616. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15617. sse::SSEMessage msg;
  15618. int retry_ms = 3000;
  15619. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15620. EXPECT_EQ(msg.data, "hello");
  15621. }
  15622. // Test: Unknown fields ignored
  15623. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15624. sse::SSEMessage msg;
  15625. int retry_ms = 3000;
  15626. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15627. EXPECT_EQ(msg.data, "");
  15628. EXPECT_EQ(msg.event, "message");
  15629. }
  15630. // Test: Space after colon is optional
  15631. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15632. sse::SSEMessage msg1, msg2;
  15633. int retry_ms = 3000;
  15634. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15635. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15636. EXPECT_EQ(msg1.data, "hello");
  15637. EXPECT_EQ(msg2.data, "hello");
  15638. }
  15639. // Test: SSEMessage clear
  15640. TEST_F(SSEParsingTest, MessageClear) {
  15641. sse::SSEMessage msg;
  15642. msg.event = "custom";
  15643. msg.data = "some data";
  15644. msg.id = "123";
  15645. msg.clear();
  15646. EXPECT_EQ(msg.event, "message");
  15647. EXPECT_EQ(msg.data, "");
  15648. EXPECT_EQ(msg.id, "");
  15649. }
  15650. // Test: Complete event parsing
  15651. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15652. sse::SSEMessage msg;
  15653. int retry_ms = 3000;
  15654. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15655. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15656. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15657. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15658. // Blank line ends event
  15659. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15660. EXPECT_EQ(msg.event, "notification");
  15661. EXPECT_EQ(msg.id, "evt-42");
  15662. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15663. EXPECT_EQ(retry_ms, 1000);
  15664. }
  15665. //==============================================================================
  15666. // Integration Tests with Server
  15667. //==============================================================================
  15668. class SSEIntegrationTest : public ::testing::Test {
  15669. protected:
  15670. void SetUp() override {
  15671. stop_server_.store(false);
  15672. events_.clear();
  15673. server_ = httplib::detail::make_unique<Server>();
  15674. setup_server();
  15675. start_server();
  15676. }
  15677. void TearDown() override {
  15678. stop_server_.store(true);
  15679. event_cv_.notify_all();
  15680. server_->stop();
  15681. if (server_thread_.joinable()) { server_thread_.join(); }
  15682. }
  15683. void setup_server() {
  15684. // Simple SSE endpoint
  15685. server_->Get("/events", [this](const Request &req, Response &res) {
  15686. auto last_id = req.get_header_value("Last-Event-ID");
  15687. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15688. res.set_chunked_content_provider(
  15689. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15690. std::unique_lock<std::mutex> lock(event_mutex_);
  15691. if (event_cv_.wait_for(
  15692. lock, std::chrono::milliseconds(200), [this] {
  15693. return !events_.empty() || stop_server_.load();
  15694. })) {
  15695. if (stop_server_.load()) { return false; }
  15696. if (!events_.empty()) {
  15697. std::string event = events_.front();
  15698. events_.erase(events_.begin());
  15699. sink.write(event.data(), event.size());
  15700. return true;
  15701. }
  15702. }
  15703. return !stop_server_.load();
  15704. });
  15705. });
  15706. // Endpoint that returns error
  15707. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15708. res.status = 500;
  15709. res.set_content("Internal Server Error", "text/plain");
  15710. });
  15711. // Endpoint for custom event types
  15712. server_->Get("/custom-events", [](const Request &, Response &res) {
  15713. res.set_chunked_content_provider(
  15714. "text/event-stream", [](size_t offset, DataSink &sink) {
  15715. if (offset == 0) {
  15716. std::string event = "event: update\ndata: updated\n\n"
  15717. "event: delete\ndata: deleted\n\n";
  15718. sink.write(event.data(), event.size());
  15719. }
  15720. return false; // End stream after sending
  15721. });
  15722. });
  15723. }
  15724. void start_server() {
  15725. port_ = server_->bind_to_any_port(HOST);
  15726. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15727. // Wait for server to start
  15728. while (!server_->is_running()) {
  15729. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15730. }
  15731. }
  15732. int get_port() const { return port_; }
  15733. void send_event(const std::string &event) {
  15734. std::lock_guard<std::mutex> lock(event_mutex_);
  15735. events_.push_back(event);
  15736. event_cv_.notify_all();
  15737. }
  15738. std::unique_ptr<Server> server_;
  15739. std::thread server_thread_;
  15740. std::mutex event_mutex_;
  15741. std::condition_variable event_cv_;
  15742. std::vector<std::string> events_;
  15743. std::atomic<bool> stop_server_{false};
  15744. std::string last_received_event_id_;
  15745. int port_ = 0;
  15746. };
  15747. // Test: Successful connection and on_open callback
  15748. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15749. // Add a simple endpoint that sends one event and closes
  15750. server_->Get("/simple-event", [](const Request &, Response &res) {
  15751. res.set_chunked_content_provider(
  15752. "text/event-stream", [](size_t offset, DataSink &sink) {
  15753. if (offset == 0) {
  15754. std::string event = "data: hello\n\n";
  15755. sink.write(event.data(), event.size());
  15756. }
  15757. return false; // Close stream after sending
  15758. });
  15759. });
  15760. Client client("localhost", get_port());
  15761. sse::SSEClient sse(client, "/simple-event");
  15762. std::atomic<bool> open_called{false};
  15763. std::atomic<bool> message_received{false};
  15764. sse.on_open([&open_called]() { open_called.store(true); });
  15765. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15766. if (msg.data == "hello") { message_received.store(true); }
  15767. });
  15768. sse.set_reconnect_interval(100);
  15769. sse.set_max_reconnect_attempts(1);
  15770. // Start async
  15771. sse.start_async();
  15772. // Wait for message to be processed
  15773. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15774. sse.stop();
  15775. EXPECT_TRUE(open_called.load());
  15776. EXPECT_TRUE(message_received.load());
  15777. }
  15778. // Test: on_message callback
  15779. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15780. // Endpoint that sends multiple events then closes
  15781. server_->Get("/multi-event", [](const Request &, Response &res) {
  15782. res.set_chunked_content_provider(
  15783. "text/event-stream", [](size_t offset, DataSink &sink) {
  15784. if (offset == 0) {
  15785. std::string events = "data: message1\n\ndata: message2\n\n";
  15786. sink.write(events.data(), events.size());
  15787. }
  15788. return false;
  15789. });
  15790. });
  15791. Client client("localhost", get_port());
  15792. sse::SSEClient sse(client, "/multi-event");
  15793. std::vector<std::string> received_messages;
  15794. std::mutex messages_mutex;
  15795. sse.on_message([&](const sse::SSEMessage &msg) {
  15796. std::lock_guard<std::mutex> lock(messages_mutex);
  15797. received_messages.push_back(msg.data);
  15798. });
  15799. sse.set_reconnect_interval(100);
  15800. sse.set_max_reconnect_attempts(1);
  15801. sse.start_async();
  15802. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15803. sse.stop();
  15804. std::lock_guard<std::mutex> lock(messages_mutex);
  15805. EXPECT_GE(received_messages.size(), 2u);
  15806. if (received_messages.size() >= 2) {
  15807. EXPECT_EQ(received_messages[0], "message1");
  15808. EXPECT_EQ(received_messages[1], "message2");
  15809. }
  15810. }
  15811. // Test: on_event for specific types
  15812. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15813. Client client("localhost", get_port());
  15814. sse::SSEClient sse(client, "/custom-events");
  15815. std::atomic<bool> update_received{false};
  15816. std::atomic<bool> delete_received{false};
  15817. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15818. if (msg.data == "updated") { update_received.store(true); }
  15819. });
  15820. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15821. if (msg.data == "deleted") { delete_received.store(true); }
  15822. });
  15823. sse.set_max_reconnect_attempts(1);
  15824. sse.start_async();
  15825. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15826. sse.stop();
  15827. EXPECT_TRUE(update_received.load());
  15828. EXPECT_TRUE(delete_received.load());
  15829. }
  15830. // Test: on_error callback on connection failure
  15831. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15832. // Connect to a non-existent port
  15833. Client client("localhost", 59999);
  15834. sse::SSEClient sse(client, "/events");
  15835. std::atomic<bool> error_called{false};
  15836. Error received_error = Error::Success;
  15837. sse.on_error([&](Error err) {
  15838. error_called.store(true);
  15839. received_error = err;
  15840. });
  15841. sse.set_reconnect_interval(50);
  15842. sse.set_max_reconnect_attempts(1);
  15843. sse.start_async();
  15844. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15845. sse.stop();
  15846. EXPECT_TRUE(error_called.load());
  15847. EXPECT_NE(received_error, Error::Success);
  15848. }
  15849. // Test: Last-Event-ID header sent on reconnect
  15850. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15851. // Endpoint that sends event with ID
  15852. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15853. res.set_chunked_content_provider(
  15854. "text/event-stream", [](size_t offset, DataSink &sink) {
  15855. if (offset == 0) {
  15856. std::string event = "id: evt-123\ndata: test\n\n";
  15857. sink.write(event.data(), event.size());
  15858. }
  15859. return false;
  15860. });
  15861. });
  15862. Client client("localhost", get_port());
  15863. sse::SSEClient sse(client, "/event-with-id");
  15864. std::atomic<bool> id_received{false};
  15865. sse.on_message([&](const sse::SSEMessage &msg) {
  15866. if (!msg.id.empty()) { id_received.store(true); }
  15867. });
  15868. sse.set_reconnect_interval(100);
  15869. sse.set_max_reconnect_attempts(1);
  15870. sse.start_async();
  15871. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15872. sse.stop();
  15873. EXPECT_TRUE(id_received.load());
  15874. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15875. }
  15876. // Test: Manual stop
  15877. TEST_F(SSEIntegrationTest, ManualStop) {
  15878. // Endpoint that sends one event and stays open briefly
  15879. std::atomic<bool> handler_running{true};
  15880. server_->Get("/stay-open", [&handler_running](const Request &,
  15881. Response &res) {
  15882. res.set_chunked_content_provider(
  15883. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15884. if (offset == 0) {
  15885. std::string event = "data: connected\n\n";
  15886. sink.write(event.data(), event.size());
  15887. }
  15888. // Keep connection open while handler_running is true
  15889. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15890. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15891. }
  15892. return false;
  15893. });
  15894. });
  15895. Client client("localhost", get_port());
  15896. sse::SSEClient sse(client, "/stay-open");
  15897. std::atomic<bool> connected{false};
  15898. sse.on_open([&connected]() { connected.store(true); });
  15899. sse.set_reconnect_interval(100);
  15900. sse.set_max_reconnect_attempts(1);
  15901. sse.start_async();
  15902. // Wait for connection to establish
  15903. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15904. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15905. }
  15906. EXPECT_TRUE(connected.load());
  15907. EXPECT_TRUE(sse.is_connected());
  15908. // Signal handler to stop
  15909. handler_running.store(false);
  15910. // Stop SSE client
  15911. sse.stop();
  15912. EXPECT_FALSE(sse.is_connected());
  15913. }
  15914. // Test: SSEClient with custom headers
  15915. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15916. // Setup a server endpoint that checks for custom header
  15917. std::atomic<bool> header_received{false};
  15918. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15919. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15920. header_received.store(true);
  15921. }
  15922. res.set_chunked_content_provider("text/event-stream",
  15923. [](size_t, DataSink &) { return false; });
  15924. });
  15925. Client client("localhost", get_port());
  15926. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15927. sse::SSEClient sse(client, "/header-check", headers);
  15928. sse.set_max_reconnect_attempts(1);
  15929. sse.start_async();
  15930. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15931. sse.stop();
  15932. EXPECT_TRUE(header_received.load());
  15933. }
  15934. // Test: Reconnect interval configuration
  15935. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15936. Client client("localhost", get_port());
  15937. sse::SSEClient sse(client, "/events");
  15938. auto &result = sse.set_reconnect_interval(500);
  15939. // Builder pattern should return reference to self
  15940. EXPECT_EQ(&result, &sse);
  15941. }
  15942. // Test: Max reconnect attempts
  15943. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15944. // Connect to non-existent port to force reconnects
  15945. Client client("localhost", 59998);
  15946. sse::SSEClient sse(client, "/events");
  15947. std::atomic<int> error_count{0};
  15948. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15949. sse.set_reconnect_interval(50);
  15950. sse.set_max_reconnect_attempts(2);
  15951. auto start = std::chrono::steady_clock::now();
  15952. sse.start(); // Blocking call
  15953. auto end = std::chrono::steady_clock::now();
  15954. // Should have stopped after 2 failed attempts
  15955. EXPECT_GE(error_count.load(), 2);
  15956. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15957. auto duration =
  15958. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15959. #ifdef _WIN32
  15960. // Windows is much slower for socket connection failures
  15961. EXPECT_LT(duration.count(), 7000);
  15962. #else
  15963. EXPECT_LT(duration.count(), 1000);
  15964. #endif
  15965. }
  15966. // Test: Multi-line data in integration
  15967. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15968. // Endpoint with multi-line data
  15969. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15970. res.set_chunked_content_provider(
  15971. "text/event-stream", [](size_t offset, DataSink &sink) {
  15972. if (offset == 0) {
  15973. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15974. sink.write(event.data(), event.size());
  15975. }
  15976. return false;
  15977. });
  15978. });
  15979. Client client("localhost", get_port());
  15980. sse::SSEClient sse(client, "/multiline-data");
  15981. std::string received_data;
  15982. std::mutex data_mutex;
  15983. sse.on_message([&](const sse::SSEMessage &msg) {
  15984. std::lock_guard<std::mutex> lock(data_mutex);
  15985. received_data = msg.data;
  15986. });
  15987. sse.set_reconnect_interval(100);
  15988. sse.set_max_reconnect_attempts(1);
  15989. sse.start_async();
  15990. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15991. sse.stop();
  15992. std::lock_guard<std::mutex> lock(data_mutex);
  15993. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15994. }
  15995. // Test: Auto-reconnect after server disconnection
  15996. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15997. std::atomic<int> connection_count{0};
  15998. std::atomic<int> message_count{0};
  15999. // Endpoint that sends one event and closes, forcing reconnect
  16000. server_->Get("/reconnect-test",
  16001. [&connection_count](const Request &, Response &res) {
  16002. connection_count.fetch_add(1);
  16003. res.set_chunked_content_provider(
  16004. "text/event-stream", [](size_t offset, DataSink &sink) {
  16005. if (offset == 0) {
  16006. std::string event = "data: hello\n\n";
  16007. sink.write(event.data(), event.size());
  16008. }
  16009. return false; // Close connection after sending
  16010. });
  16011. });
  16012. Client client("localhost", get_port());
  16013. sse::SSEClient sse(client, "/reconnect-test");
  16014. sse.on_message([&message_count](const sse::SSEMessage &) {
  16015. message_count.fetch_add(1);
  16016. });
  16017. sse.set_reconnect_interval(100);
  16018. sse.set_max_reconnect_attempts(3);
  16019. sse.start_async();
  16020. // Wait long enough for multiple reconnects
  16021. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16022. sse.stop();
  16023. // Should have connected multiple times (initial + reconnects)
  16024. EXPECT_GE(connection_count.load(), 2);
  16025. // Should have received messages from multiple connections
  16026. EXPECT_GE(message_count.load(), 2);
  16027. }
  16028. // Test: Last-Event-ID sent on reconnect
  16029. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16030. std::atomic<int> connection_count{0};
  16031. std::vector<std::string> received_last_event_ids;
  16032. std::mutex id_mutex;
  16033. // Endpoint that checks Last-Event-ID header and sends event with ID
  16034. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16035. int conn = connection_count.fetch_add(1);
  16036. // Capture the Last-Event-ID header from each connection
  16037. {
  16038. std::lock_guard<std::mutex> lock(id_mutex);
  16039. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16040. }
  16041. res.set_chunked_content_provider(
  16042. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16043. if (offset == 0) {
  16044. std::string event =
  16045. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16046. sink.write(event.data(), event.size());
  16047. }
  16048. return false;
  16049. });
  16050. });
  16051. Client client("localhost", get_port());
  16052. sse::SSEClient sse(client, "/reconnect-with-id");
  16053. sse.set_reconnect_interval(100);
  16054. sse.set_max_reconnect_attempts(3);
  16055. sse.start_async();
  16056. // Wait for at least 2 connections
  16057. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16058. sse.stop();
  16059. // Verify behavior
  16060. std::lock_guard<std::mutex> lock(id_mutex);
  16061. EXPECT_GE(received_last_event_ids.size(), 2u);
  16062. // First connection should have no Last-Event-ID
  16063. if (!received_last_event_ids.empty()) {
  16064. EXPECT_EQ(received_last_event_ids[0], "");
  16065. }
  16066. // Second connection should have Last-Event-ID from first connection
  16067. if (received_last_event_ids.size() >= 2) {
  16068. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16069. }
  16070. }
  16071. // Test: set_headers updates headers used on reconnect
  16072. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16073. std::vector<std::string> received_tokens;
  16074. std::mutex token_mutex;
  16075. // Endpoint that captures Authorization header
  16076. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16077. {
  16078. std::lock_guard<std::mutex> lock(token_mutex);
  16079. received_tokens.push_back(req.get_header_value("Authorization"));
  16080. }
  16081. res.set_chunked_content_provider(
  16082. "text/event-stream", [](size_t offset, DataSink &sink) {
  16083. if (offset == 0) {
  16084. std::string event = "data: hello\n\n";
  16085. sink.write(event.data(), event.size());
  16086. }
  16087. return false; // Close connection to trigger reconnect
  16088. });
  16089. });
  16090. Client client("localhost", get_port());
  16091. Headers headers = {{"Authorization", "Bearer old-token"}};
  16092. sse::SSEClient sse(client, "/auth-check", headers);
  16093. // Update headers on each successful connection
  16094. sse.on_open(
  16095. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16096. sse.set_reconnect_interval(100);
  16097. sse.set_max_reconnect_attempts(3);
  16098. sse.start_async();
  16099. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16100. sse.stop();
  16101. std::lock_guard<std::mutex> lock(token_mutex);
  16102. ASSERT_GE(received_tokens.size(), 2u);
  16103. // First connection uses original header
  16104. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16105. // Second connection uses updated header from set_headers
  16106. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16107. }
  16108. // Test: 401 allows reconnection (so on_error can refresh headers)
  16109. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16110. std::atomic<int> connection_count{0};
  16111. // Endpoint: returns 401 on first attempt, 200 on second
  16112. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16113. int conn = connection_count.fetch_add(1);
  16114. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16115. res.status = StatusCode::Unauthorized_401;
  16116. res.set_content("Unauthorized", "text/plain");
  16117. return;
  16118. }
  16119. res.set_chunked_content_provider(
  16120. "text/event-stream", [](size_t offset, DataSink &sink) {
  16121. if (offset == 0) {
  16122. std::string event = "data: authenticated\n\n";
  16123. sink.write(event.data(), event.size());
  16124. }
  16125. return false;
  16126. });
  16127. });
  16128. Client client("localhost", get_port());
  16129. Headers headers = {{"Authorization", "Bearer expired"}};
  16130. sse::SSEClient sse(client, "/auth-retry", headers);
  16131. std::atomic<bool> message_received{false};
  16132. // Refresh token on error
  16133. sse.on_error(
  16134. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16135. sse.on_message([&](const sse::SSEMessage &msg) {
  16136. if (msg.data == "authenticated") { message_received.store(true); }
  16137. });
  16138. sse.set_reconnect_interval(100);
  16139. sse.set_max_reconnect_attempts(3);
  16140. sse.start_async();
  16141. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16142. sse.stop();
  16143. // Should have reconnected after 401 and succeeded with new token
  16144. EXPECT_GE(connection_count.load(), 2);
  16145. EXPECT_TRUE(message_received.load());
  16146. }
  16147. TEST(Issue2318Test, EmptyHostString) {
  16148. {
  16149. httplib::Client cli_empty("", PORT);
  16150. auto res = cli_empty.Get("/");
  16151. ASSERT_FALSE(res);
  16152. EXPECT_EQ(httplib::Error::Connection, res.error());
  16153. }
  16154. {
  16155. httplib::Client cli(" ", PORT);
  16156. auto res = cli.Get("/");
  16157. ASSERT_FALSE(res);
  16158. EXPECT_EQ(httplib::Error::Connection, res.error());
  16159. }
  16160. }
  16161. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16162. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16163. Server svr;
  16164. // Set a small payload limit (1KB)
  16165. svr.set_payload_max_length(1024);
  16166. svr.Post("/test", [&](const Request &req, Response &res) {
  16167. res.set_content("Body size: " + std::to_string(req.body.size()),
  16168. "text/plain");
  16169. });
  16170. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16171. auto se = detail::scope_exit([&] {
  16172. svr.stop();
  16173. listen_thread.join();
  16174. });
  16175. svr.wait_until_ready();
  16176. // Create data that compresses well but exceeds limit when decompressed
  16177. // 8KB of repeated null bytes compresses to a very small size
  16178. std::string original_data(8 * 1024, '\0');
  16179. // Compress the data using gzip
  16180. std::string compressed_data;
  16181. detail::gzip_compressor compressor;
  16182. compressor.compress(original_data.data(), original_data.size(), true,
  16183. [&](const char *data, size_t size) {
  16184. compressed_data.append(data, size);
  16185. return true;
  16186. });
  16187. // Verify compression worked (compressed should be much smaller)
  16188. ASSERT_LT(compressed_data.size(), original_data.size());
  16189. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16190. // Send compressed data with Content-Encoding: gzip
  16191. Client cli(HOST, PORT);
  16192. Headers headers = {{"Content-Encoding", "gzip"}};
  16193. auto res =
  16194. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16195. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16197. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16198. }
  16199. #endif
  16200. // ============================================================================
  16201. // OpenSSL-Specific Tests
  16202. // ============================================================================
  16203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16204. X509 *readCertificate(const std::string &strFileName) {
  16205. std::ifstream inStream(strFileName);
  16206. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16207. std::istreambuf_iterator<char>());
  16208. if (strCertPEM.empty()) return (nullptr);
  16209. BIO *pbCert = BIO_new(BIO_s_mem());
  16210. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16211. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16212. BIO_free(pbCert);
  16213. return (pCert);
  16214. }
  16215. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16216. std::ifstream inStream(strFileName);
  16217. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16218. std::istreambuf_iterator<char>());
  16219. if (strPrivateKeyPEM.empty()) return (nullptr);
  16220. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16221. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16222. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16223. BIO_free(pbPrivKey);
  16224. return (pPrivateKey);
  16225. }
  16226. TEST(BindServerTest, UpdateCerts) {
  16227. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16228. int port = svr.bind_to_any_port("0.0.0.0");
  16229. ASSERT_TRUE(svr.is_valid());
  16230. ASSERT_TRUE(port > 0);
  16231. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16232. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16233. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16234. ASSERT_TRUE(cert != nullptr);
  16235. ASSERT_TRUE(ca_cert != nullptr);
  16236. ASSERT_TRUE(key != nullptr);
  16237. X509_STORE *cert_store = X509_STORE_new();
  16238. X509_STORE_add_cert(cert_store, ca_cert);
  16239. // svr.update_certs(cert, key, cert_store); // deprecated
  16240. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16241. CLIENT_CA_CERT_FILE);
  16242. ASSERT_TRUE(svr.is_valid());
  16243. svr.stop();
  16244. X509_STORE_free(cert_store);
  16245. X509_free(cert);
  16246. X509_free(ca_cert);
  16247. EVP_PKEY_free(key);
  16248. }
  16249. // Test that update_certs() updates client CA list correctly
  16250. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16251. // Start with file-based constructor
  16252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16253. ASSERT_TRUE(svr.is_valid());
  16254. // Initially no client CA list should be set
  16255. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16256. ASSERT_TRUE(ssl_ctx != nullptr);
  16257. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16258. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16259. EXPECT_EQ(0, count_before);
  16260. // Now update with client CA (PEM string)
  16261. std::string cert_pem, key_pem, ca_pem;
  16262. read_file(SERVER_CERT_FILE, cert_pem);
  16263. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16264. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16265. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16266. ASSERT_TRUE(svr.is_valid());
  16267. // Now client CA list should be set
  16268. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16269. ASSERT_TRUE(ca_list_after != nullptr);
  16270. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16271. }
  16272. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16273. // Test that the file-path SSLServer constructor properly sets the client CA
  16274. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16276. ASSERT_TRUE(svr.is_valid());
  16277. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16278. ASSERT_TRUE(ssl_ctx != nullptr);
  16279. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16280. ASSERT_TRUE(ca_list != nullptr);
  16281. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16282. }
  16283. #endif
  16284. // ============================================================================
  16285. // MbedTLS-Specific Tests
  16286. // ============================================================================
  16287. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16288. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16289. using namespace httplib::tls;
  16290. // Track if callback was invoked
  16291. bool callback_invoked = false;
  16292. // The callback receives void* ctx which is actually MbedTlsContext*
  16293. // We can access the mbedtls_ssl_config via the context
  16294. auto setup_callback = [&callback_invoked](void *ctx) {
  16295. callback_invoked = true;
  16296. // Cast to MbedTlsContext* to access the ssl config
  16297. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16298. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16299. // Use static variables to hold certificate data (simplified for test)
  16300. static mbedtls_x509_crt own_cert;
  16301. static mbedtls_pk_context own_key;
  16302. static mbedtls_x509_crt ca_chain;
  16303. static bool initialized = false;
  16304. if (!initialized) {
  16305. mbedtls_x509_crt_init(&own_cert);
  16306. mbedtls_pk_init(&own_key);
  16307. mbedtls_x509_crt_init(&ca_chain);
  16308. // Load server certificate
  16309. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16310. return false;
  16311. }
  16312. // Load server private key.
  16313. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16314. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16315. #if MBEDTLS_VERSION_MAJOR == 3
  16316. ,
  16317. mbedtls_ctr_drbg_random, nullptr
  16318. #endif
  16319. ) != 0) {
  16320. return false;
  16321. }
  16322. // Load CA chain for client verification
  16323. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16324. return false;
  16325. }
  16326. initialized = true;
  16327. }
  16328. // Configure the SSL config
  16329. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16330. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16331. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16332. // Set minimum TLS version using mbedTLS native API
  16333. #if MBEDTLS_VERSION_MAJOR >= 3
  16334. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16335. #else
  16336. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16337. MBEDTLS_SSL_MINOR_VERSION_3);
  16338. #endif
  16339. return true;
  16340. };
  16341. SSLServer svr(setup_callback);
  16342. ASSERT_TRUE(svr.is_valid());
  16343. ASSERT_TRUE(callback_invoked);
  16344. svr.Get("/test", [&](const Request &req, Response &res) {
  16345. res.set_content("test", "text/plain");
  16346. auto cert = req.peer_cert();
  16347. ASSERT_TRUE(static_cast<bool>(cert));
  16348. auto common_name = cert.subject_cn();
  16349. EXPECT_EQ("Common Name", common_name);
  16350. });
  16351. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16352. auto se = detail::scope_exit([&] {
  16353. svr.stop();
  16354. t.join();
  16355. ASSERT_FALSE(svr.is_running());
  16356. });
  16357. svr.wait_until_ready();
  16358. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16359. cli.enable_server_certificate_verification(false);
  16360. cli.set_connection_timeout(30);
  16361. auto res = cli.Get("/test");
  16362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16363. ASSERT_EQ(StatusCode::OK_200, res->status);
  16364. }
  16365. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16366. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16367. // keep-alive SSL session, which reads through that config in
  16368. // mbedtls_ssl_close_notify.
  16369. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16371. ASSERT_TRUE(svr.is_valid());
  16372. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16373. res.set_content("test", "text/plain");
  16374. });
  16375. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16376. auto se = detail::scope_exit([&] {
  16377. svr.stop();
  16378. t.join();
  16379. ASSERT_FALSE(svr.is_running());
  16380. });
  16381. svr.wait_until_ready();
  16382. {
  16383. SSLClient cli(HOST, PORT);
  16384. cli.enable_server_certificate_verification(false);
  16385. cli.set_keep_alive(true);
  16386. auto res = cli.Get("/test");
  16387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16388. ASSERT_EQ(StatusCode::OK_200, res->status);
  16389. // cli is destructed here with the keep-alive SSL session still open.
  16390. }
  16391. }
  16392. #endif
  16393. // WebSocket Tests
  16394. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16395. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16396. // defining the meaning of these bits has been negotiated.
  16397. auto make_frame = [](uint8_t first_byte) {
  16398. std::string frame;
  16399. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16400. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16401. frame += "Hello";
  16402. return frame;
  16403. };
  16404. // RSV1 set (0x40)
  16405. {
  16406. detail::BufferStream strm;
  16407. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16408. ws::Opcode opcode;
  16409. std::string payload;
  16410. bool fin;
  16411. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16412. false, 1024));
  16413. }
  16414. // RSV2 set (0x20)
  16415. {
  16416. detail::BufferStream strm;
  16417. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16418. ws::Opcode opcode;
  16419. std::string payload;
  16420. bool fin;
  16421. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16422. false, 1024));
  16423. }
  16424. // RSV3 set (0x10)
  16425. {
  16426. detail::BufferStream strm;
  16427. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16428. ws::Opcode opcode;
  16429. std::string payload;
  16430. bool fin;
  16431. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16432. false, 1024));
  16433. }
  16434. // No RSV bits set - should succeed
  16435. {
  16436. detail::BufferStream strm;
  16437. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16438. ws::Opcode opcode;
  16439. std::string payload;
  16440. bool fin;
  16441. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16442. false, 1024));
  16443. EXPECT_EQ(ws::Opcode::Text, opcode);
  16444. EXPECT_EQ("Hello", payload);
  16445. EXPECT_TRUE(fin);
  16446. }
  16447. }
  16448. TEST(WebSocketTest, ControlFrameValidation) {
  16449. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16450. // payload length <= 125.
  16451. // Ping with FIN=0 - must be rejected
  16452. {
  16453. detail::BufferStream strm;
  16454. std::string frame;
  16455. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16456. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16457. strm.write(frame.data(), frame.size());
  16458. ws::Opcode opcode;
  16459. std::string payload;
  16460. bool fin;
  16461. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16462. false, 1024));
  16463. }
  16464. // Close with FIN=0 - must be rejected
  16465. {
  16466. detail::BufferStream strm;
  16467. std::string frame;
  16468. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16469. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16470. strm.write(frame.data(), frame.size());
  16471. ws::Opcode opcode;
  16472. std::string payload;
  16473. bool fin;
  16474. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16475. false, 1024));
  16476. }
  16477. // Ping with payload_len=126 (extended length) - must be rejected
  16478. {
  16479. detail::BufferStream strm;
  16480. std::string frame;
  16481. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16482. frame += static_cast<char>(126); // payload_len=126 (>125)
  16483. frame += static_cast<char>(0x00); // extended length high byte
  16484. frame += static_cast<char>(126); // extended length low byte
  16485. frame += std::string(126, 'x');
  16486. strm.write(frame.data(), frame.size());
  16487. ws::Opcode opcode;
  16488. std::string payload;
  16489. bool fin;
  16490. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16491. false, 1024));
  16492. }
  16493. // Ping with FIN=1 and payload_len=125 - should succeed
  16494. {
  16495. detail::BufferStream strm;
  16496. std::string frame;
  16497. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16498. frame += static_cast<char>(125); // payload_len=125
  16499. frame += std::string(125, 'x');
  16500. strm.write(frame.data(), frame.size());
  16501. ws::Opcode opcode;
  16502. std::string payload;
  16503. bool fin;
  16504. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16505. false, 1024));
  16506. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16507. EXPECT_EQ(125u, payload.size());
  16508. EXPECT_TRUE(fin);
  16509. }
  16510. }
  16511. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16512. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16513. // length MUST be 0.
  16514. // MSB set - must be rejected
  16515. {
  16516. detail::BufferStream strm;
  16517. std::string frame;
  16518. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16519. frame += static_cast<char>(127); // 64-bit extended length
  16520. frame += static_cast<char>(0x80); // MSB set (invalid)
  16521. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16522. strm.write(frame.data(), frame.size());
  16523. ws::Opcode opcode;
  16524. std::string payload;
  16525. bool fin;
  16526. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16527. false, 1024));
  16528. }
  16529. // MSB clear - should pass length parsing (will be rejected by max_len,
  16530. // but that's a different check; use a small length to verify)
  16531. {
  16532. detail::BufferStream strm;
  16533. std::string frame;
  16534. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16535. frame += static_cast<char>(127); // 64-bit extended length
  16536. frame += std::string(7, '\0'); // high bytes = 0
  16537. frame += static_cast<char>(0x03); // length = 3
  16538. frame += "abc";
  16539. strm.write(frame.data(), frame.size());
  16540. ws::Opcode opcode;
  16541. std::string payload;
  16542. bool fin;
  16543. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16544. false, 1024));
  16545. EXPECT_EQ(ws::Opcode::Text, opcode);
  16546. EXPECT_EQ("abc", payload);
  16547. }
  16548. }
  16549. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16550. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16551. // Valid UTF-8
  16552. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16553. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16554. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16555. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16556. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16557. // Invalid UTF-8
  16558. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16559. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16560. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16561. EXPECT_FALSE(
  16562. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16563. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16564. }
  16565. TEST(WebSocketTest, ConnectAndDisconnect) {
  16566. Server svr;
  16567. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16568. std::string msg;
  16569. while (ws.read(msg)) {}
  16570. });
  16571. auto port = svr.bind_to_any_port(HOST);
  16572. std::thread t([&]() { svr.listen_after_bind(); });
  16573. svr.wait_until_ready();
  16574. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16575. ASSERT_TRUE(client.connect());
  16576. EXPECT_TRUE(client.is_open());
  16577. client.close();
  16578. EXPECT_FALSE(client.is_open());
  16579. svr.stop();
  16580. t.join();
  16581. }
  16582. TEST(WebSocketTest, ValidURL) {
  16583. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16584. EXPECT_TRUE(ws1.is_valid());
  16585. ws::WebSocketClient ws2("ws://example.com/path");
  16586. EXPECT_TRUE(ws2.is_valid());
  16587. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16588. EXPECT_TRUE(ws3.is_valid());
  16589. #ifdef CPPHTTPLIB_SSL_ENABLED
  16590. ws::WebSocketClient wss1("wss://example.com/path");
  16591. EXPECT_TRUE(wss1.is_valid());
  16592. ws::WebSocketClient wss2("wss://example.com:443/path");
  16593. EXPECT_TRUE(wss2.is_valid());
  16594. #endif
  16595. }
  16596. TEST(WebSocketTest, InvalidURL) {
  16597. // No scheme
  16598. ws::WebSocketClient ws1("localhost:8080/path");
  16599. EXPECT_FALSE(ws1.is_valid());
  16600. // No path
  16601. ws::WebSocketClient ws2("ws://localhost:8080");
  16602. EXPECT_FALSE(ws2.is_valid());
  16603. // Empty string
  16604. ws::WebSocketClient ws3("");
  16605. EXPECT_FALSE(ws3.is_valid());
  16606. // Missing host
  16607. ws::WebSocketClient ws4("ws://:8080/path");
  16608. EXPECT_FALSE(ws4.is_valid());
  16609. // Port number overflow — should not crash
  16610. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16611. EXPECT_FALSE(ws5.is_valid());
  16612. // Port out of range
  16613. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16614. EXPECT_FALSE(ws6.is_valid());
  16615. }
  16616. TEST(WebSocketTest, UnsupportedScheme) {
  16617. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16618. ws::WebSocketClient ws1("http://localhost:8080/path");
  16619. EXPECT_FALSE(ws1.is_valid());
  16620. ws::WebSocketClient ws2("https://localhost:8080/path");
  16621. EXPECT_FALSE(ws2.is_valid());
  16622. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16623. EXPECT_FALSE(ws3.is_valid());
  16624. #else
  16625. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16626. std::invalid_argument);
  16627. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16628. std::invalid_argument);
  16629. #endif
  16630. }
  16631. TEST(WebSocketTest, ConnectWhenInvalid) {
  16632. ws::WebSocketClient ws("not a valid url");
  16633. EXPECT_FALSE(ws.is_valid());
  16634. EXPECT_FALSE(ws.connect());
  16635. }
  16636. TEST(WebSocketTest, DefaultPort) {
  16637. ws::WebSocketClient ws1("ws://example.com/path");
  16638. EXPECT_TRUE(ws1.is_valid());
  16639. // ws:// defaults to port 80 (verified by successful parse)
  16640. #ifdef CPPHTTPLIB_SSL_ENABLED
  16641. ws::WebSocketClient ws2("wss://example.com/path");
  16642. EXPECT_TRUE(ws2.is_valid());
  16643. // wss:// defaults to port 443 (verified by successful parse)
  16644. #endif
  16645. }
  16646. TEST(WebSocketTest, IPv6LiteralAddress) {
  16647. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16648. EXPECT_TRUE(ws1.is_valid());
  16649. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16650. EXPECT_TRUE(ws2.is_valid());
  16651. }
  16652. TEST(WebSocketTest, ComplexPath) {
  16653. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16654. EXPECT_TRUE(ws1.is_valid());
  16655. ws::WebSocketClient ws2("ws://localhost:8080/");
  16656. EXPECT_TRUE(ws2.is_valid());
  16657. }
  16658. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16659. Server svr;
  16660. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16661. std::string msg;
  16662. while (ws.read(msg)) {}
  16663. });
  16664. auto port = svr.bind_to_any_port(HOST);
  16665. std::thread t([&]() { svr.listen_after_bind(); });
  16666. svr.wait_until_ready();
  16667. auto another_host = "example.com";
  16668. auto wrong_ip = "192.0.2.1";
  16669. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16670. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16671. ASSERT_TRUE(client.connect());
  16672. EXPECT_TRUE(client.is_open());
  16673. client.close();
  16674. svr.stop();
  16675. t.join();
  16676. }
  16677. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16678. Server svr;
  16679. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16680. std::string msg;
  16681. while (ws.read(msg)) {}
  16682. });
  16683. auto port = svr.bind_to_any_port(HOST);
  16684. std::thread t([&]() { svr.listen_after_bind(); });
  16685. svr.wait_until_ready();
  16686. auto wrong_ip = "192.0.2.1";
  16687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16688. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16689. client.set_connection_timeout(1);
  16690. client.set_read_timeout(1);
  16691. client.set_write_timeout(1);
  16692. EXPECT_FALSE(client.connect());
  16693. EXPECT_FALSE(client.is_open());
  16694. svr.stop();
  16695. t.join();
  16696. }
  16697. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16698. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16699. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16700. // (RFC 6761) is only a map key and the Host header value.
  16701. auto host = "target.invalid";
  16702. Server svr;
  16703. std::string received_host;
  16704. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16705. received_host = req.get_header_value("Host");
  16706. std::string msg;
  16707. while (ws.read(msg)) {}
  16708. });
  16709. auto port = svr.bind_to_any_port(HOST);
  16710. std::thread t([&]() { svr.listen_after_bind(); });
  16711. // ASSERT_* below returns from the test body, which would leave t joinable
  16712. // and make ~thread call std::terminate.
  16713. auto se = detail::scope_exit([&] {
  16714. svr.stop();
  16715. if (t.joinable()) { t.join(); }
  16716. });
  16717. svr.wait_until_ready();
  16718. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16719. std::to_string(port) + "/ws");
  16720. client.set_hostname_addr_map({{host, HOST}});
  16721. ASSERT_TRUE(client.connect());
  16722. EXPECT_TRUE(client.is_open());
  16723. client.close();
  16724. svr.stop();
  16725. t.join();
  16726. // The mapping only redirects the connection; the identity stays host_.
  16727. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16728. }
  16729. class WebSocketIntegrationTest : public ::testing::Test {
  16730. protected:
  16731. void SetUp() override {
  16732. server_ = httplib::detail::make_unique<Server>();
  16733. setup_server();
  16734. start_server();
  16735. }
  16736. void TearDown() override {
  16737. server_->stop();
  16738. if (server_thread_.joinable()) { server_thread_.join(); }
  16739. }
  16740. void setup_server() {
  16741. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16742. std::string msg;
  16743. ws::ReadResult ret;
  16744. while ((ret = ws.read(msg))) {
  16745. if (ret == ws::Binary) {
  16746. ws.send(msg.data(), msg.size());
  16747. } else {
  16748. ws.send(msg);
  16749. }
  16750. }
  16751. });
  16752. server_->WebSocket("/ws-echo-string",
  16753. [](const Request &, ws::WebSocket &ws) {
  16754. std::string msg;
  16755. while (ws.read(msg)) {
  16756. ws.send("echo: " + msg);
  16757. }
  16758. });
  16759. server_->WebSocket(
  16760. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16761. // Echo back request metadata
  16762. ws.send("path:" + req.path);
  16763. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16764. std::string msg;
  16765. while (ws.read(msg)) {}
  16766. });
  16767. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16768. std::string msg;
  16769. ws.read(msg); // wait for a message
  16770. ws.close();
  16771. });
  16772. server_->WebSocket("/ws-close-status",
  16773. [](const Request &, ws::WebSocket &ws) {
  16774. std::string msg;
  16775. ws.read(msg); // wait for a message
  16776. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16777. });
  16778. server_->WebSocket(
  16779. "/ws-subprotocol",
  16780. [](const Request &, ws::WebSocket &ws) {
  16781. std::string msg;
  16782. while (ws.read(msg)) {
  16783. ws.send(msg);
  16784. }
  16785. },
  16786. [](const std::vector<std::string> &protocols) -> std::string {
  16787. for (const auto &p : protocols) {
  16788. if (p == "graphql-ws") { return p; }
  16789. }
  16790. return "";
  16791. });
  16792. }
  16793. void start_server() {
  16794. port_ = server_->bind_to_any_port(HOST);
  16795. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16796. server_->wait_until_ready();
  16797. }
  16798. std::unique_ptr<Server> server_;
  16799. std::thread server_thread_;
  16800. int port_ = 0;
  16801. };
  16802. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16803. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16804. "/ws-echo");
  16805. ASSERT_TRUE(client.connect());
  16806. ASSERT_TRUE(client.is_open());
  16807. ASSERT_TRUE(client.send("Hello WebSocket"));
  16808. std::string msg;
  16809. EXPECT_EQ(ws::Text, client.read(msg));
  16810. EXPECT_EQ("Hello WebSocket", msg);
  16811. client.close();
  16812. }
  16813. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16814. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16815. "/ws-echo");
  16816. ASSERT_TRUE(client.connect());
  16817. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16818. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16819. std::string msg;
  16820. EXPECT_EQ(ws::Binary, client.read(msg));
  16821. EXPECT_EQ(binary_data, msg);
  16822. client.close();
  16823. }
  16824. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16826. "/ws-echo");
  16827. ASSERT_TRUE(client.connect());
  16828. for (int i = 0; i < 10; i++) {
  16829. auto text = "message " + std::to_string(i);
  16830. ASSERT_TRUE(client.send(text));
  16831. std::string msg;
  16832. ASSERT_TRUE(client.read(msg));
  16833. EXPECT_EQ(text, msg);
  16834. }
  16835. client.close();
  16836. }
  16837. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16838. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16839. "/ws-close");
  16840. ASSERT_TRUE(client.connect());
  16841. // Send a message to trigger the server to close
  16842. ASSERT_TRUE(client.send("trigger close"));
  16843. // The server will close, so read should return false
  16844. std::string msg;
  16845. EXPECT_FALSE(client.read(msg));
  16846. EXPECT_FALSE(client.is_open());
  16847. }
  16848. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16849. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16850. "/ws-echo");
  16851. ASSERT_TRUE(client.connect());
  16852. // 128KB message
  16853. std::string large_data(128 * 1024, 'X');
  16854. ASSERT_TRUE(client.send(large_data));
  16855. std::string msg;
  16856. ASSERT_TRUE(client.read(msg));
  16857. EXPECT_EQ(large_data, msg);
  16858. client.close();
  16859. }
  16860. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16861. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16862. "/ws-echo");
  16863. ASSERT_TRUE(client.connect());
  16864. const int num_threads = 4;
  16865. std::vector<std::thread> threads;
  16866. std::atomic<int> send_count{0};
  16867. for (int t = 0; t < num_threads; t++) {
  16868. threads.emplace_back([&client, &send_count, t]() {
  16869. for (int i = 0; i < 5; i++) {
  16870. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16871. if (client.send(text)) { send_count++; }
  16872. }
  16873. });
  16874. }
  16875. for (auto &th : threads) {
  16876. th.join();
  16877. }
  16878. int received = 0;
  16879. std::string msg;
  16880. while (received < send_count.load()) {
  16881. if (!client.read(msg)) { break; }
  16882. received++;
  16883. }
  16884. EXPECT_EQ(send_count.load(), received);
  16885. client.close();
  16886. }
  16887. TEST_F(WebSocketIntegrationTest, ReadString) {
  16888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16889. "/ws-echo-string");
  16890. ASSERT_TRUE(client.connect());
  16891. ASSERT_TRUE(client.send("hello"));
  16892. std::string msg;
  16893. ASSERT_TRUE(client.read(msg));
  16894. EXPECT_EQ("echo: hello", msg);
  16895. ASSERT_TRUE(client.send("world"));
  16896. ASSERT_TRUE(client.read(msg));
  16897. EXPECT_EQ("echo: world", msg);
  16898. client.close();
  16899. }
  16900. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16901. Headers headers = {{"X-Test-Header", "test-value"}};
  16902. ws::WebSocketClient client(
  16903. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16904. ASSERT_TRUE(client.connect());
  16905. std::string msg;
  16906. ASSERT_TRUE(client.read(msg));
  16907. EXPECT_EQ("path:/ws-request-info", msg);
  16908. ASSERT_TRUE(client.read(msg));
  16909. EXPECT_EQ("header:test-value", msg);
  16910. client.close();
  16911. }
  16912. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16914. "/ws-echo");
  16915. client.set_read_timeout(1, 0); // 1 second
  16916. ASSERT_TRUE(client.connect());
  16917. // Don't send anything — server echo handler waits for a message,
  16918. // so read() should time out and return false.
  16919. std::string msg;
  16920. EXPECT_FALSE(client.read(msg));
  16921. }
  16922. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16923. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16924. "/ws-echo");
  16925. client.set_read_timeout(5, 0);
  16926. ASSERT_TRUE(client.connect());
  16927. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16928. // The server should reject it and close the connection.
  16929. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16930. client.send(oversized);
  16931. // The server's read() should have failed due to payload limit,
  16932. // so our read() should return false (connection closed).
  16933. std::string msg;
  16934. EXPECT_FALSE(client.read(msg));
  16935. }
  16936. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16938. "/ws-echo");
  16939. client.set_read_timeout(10, 0);
  16940. ASSERT_TRUE(client.connect());
  16941. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16942. // This should succeed.
  16943. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16944. ASSERT_TRUE(client.send(at_limit));
  16945. std::string msg;
  16946. ASSERT_TRUE(client.read(msg));
  16947. EXPECT_EQ(at_limit.size(), msg.size());
  16948. client.close();
  16949. }
  16950. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16952. "/nonexistent");
  16953. EXPECT_FALSE(client.connect());
  16954. EXPECT_FALSE(client.is_open());
  16955. }
  16956. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16958. "/ws-echo");
  16959. ASSERT_TRUE(client.connect());
  16960. ASSERT_TRUE(client.send(""));
  16961. std::string msg;
  16962. EXPECT_EQ(ws::Text, client.read(msg));
  16963. EXPECT_EQ("", msg);
  16964. client.close();
  16965. }
  16966. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16968. "/ws-echo");
  16969. // First connection
  16970. ASSERT_TRUE(client.connect());
  16971. ASSERT_TRUE(client.send("first"));
  16972. std::string msg;
  16973. ASSERT_TRUE(client.read(msg));
  16974. EXPECT_EQ("first", msg);
  16975. client.close();
  16976. EXPECT_FALSE(client.is_open());
  16977. // Reconnect using the same client object
  16978. ASSERT_TRUE(client.connect());
  16979. ASSERT_TRUE(client.is_open());
  16980. ASSERT_TRUE(client.send("second"));
  16981. ASSERT_TRUE(client.read(msg));
  16982. EXPECT_EQ("second", msg);
  16983. client.close();
  16984. }
  16985. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16986. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16987. "/ws-close-status");
  16988. ASSERT_TRUE(client.connect());
  16989. // Trigger the server to close with GoingAway status
  16990. ASSERT_TRUE(client.send("trigger"));
  16991. // read() should return false after receiving the close frame
  16992. std::string msg;
  16993. EXPECT_FALSE(client.read(msg));
  16994. EXPECT_FALSE(client.is_open());
  16995. }
  16996. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16997. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16998. "/ws-echo");
  16999. ASSERT_TRUE(client.connect());
  17000. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17001. EXPECT_FALSE(client.is_open());
  17002. }
  17003. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17004. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17005. ws::WebSocketClient client(
  17006. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17007. ASSERT_TRUE(client.connect());
  17008. // Server should have selected graphql-ws
  17009. EXPECT_EQ("graphql-ws", client.subprotocol());
  17010. client.close();
  17011. }
  17012. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17013. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17014. ws::WebSocketClient client(
  17015. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17016. ASSERT_TRUE(client.connect());
  17017. // Server should not have selected any subprotocol
  17018. EXPECT_TRUE(client.subprotocol().empty());
  17019. client.close();
  17020. }
  17021. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17022. // Connect without requesting any subprotocol
  17023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17024. "/ws-subprotocol");
  17025. ASSERT_TRUE(client.connect());
  17026. EXPECT_TRUE(client.subprotocol().empty());
  17027. client.close();
  17028. }
  17029. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17030. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17031. "/ws-echo");
  17032. client.set_tcp_nodelay(true);
  17033. client.set_connection_timeout(3, 0);
  17034. bool socket_options_called = false;
  17035. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17036. ASSERT_TRUE(client.connect());
  17037. ASSERT_TRUE(client.is_open());
  17038. EXPECT_TRUE(socket_options_called);
  17039. ASSERT_TRUE(client.send("hello"));
  17040. std::string msg;
  17041. auto result = client.read(msg);
  17042. EXPECT_EQ(result, ws::ReadResult::Text);
  17043. EXPECT_EQ(msg, "hello");
  17044. client.close();
  17045. }
  17046. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17047. Server svr;
  17048. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17049. if (!req.has_header("Authorization")) {
  17050. res.status = StatusCode::Unauthorized_401;
  17051. res.set_content("Unauthorized", "text/plain");
  17052. return Server::HandlerResponse::Handled;
  17053. }
  17054. return Server::HandlerResponse::Unhandled;
  17055. });
  17056. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17057. std::string msg;
  17058. while (ws.read(msg)) {
  17059. ws.send(msg);
  17060. }
  17061. });
  17062. auto port = svr.bind_to_any_port("localhost");
  17063. std::thread t([&]() { svr.listen_after_bind(); });
  17064. svr.wait_until_ready();
  17065. // Without Authorization header - should be rejected before upgrade
  17066. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17067. EXPECT_FALSE(client1.connect());
  17068. // With Authorization header - should succeed
  17069. Headers headers = {{"Authorization", "Bearer token123"}};
  17070. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17071. headers);
  17072. ASSERT_TRUE(client2.connect());
  17073. ASSERT_TRUE(client2.send("hello"));
  17074. std::string msg;
  17075. ASSERT_TRUE(client2.read(msg));
  17076. EXPECT_EQ("hello", msg);
  17077. client2.close();
  17078. svr.stop();
  17079. t.join();
  17080. }
  17081. TEST(WebSocketTest, QueryStringInHandshake) {
  17082. Server svr;
  17083. std::mutex mtx;
  17084. std::string received_target;
  17085. std::string received_token;
  17086. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17087. {
  17088. std::lock_guard<std::mutex> lock(mtx);
  17089. received_target = req.target;
  17090. if (req.has_param("token")) {
  17091. received_token = req.get_param_value("token");
  17092. }
  17093. }
  17094. std::string msg;
  17095. while (ws.read(msg)) {
  17096. ws.send(msg);
  17097. }
  17098. });
  17099. auto port = svr.bind_to_any_port("localhost");
  17100. std::thread t([&]() { svr.listen_after_bind(); });
  17101. svr.wait_until_ready();
  17102. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17103. "/ws?token=ABC&session=123");
  17104. ASSERT_TRUE(client.connect());
  17105. // Round-trip ensures the handler has run and captured the request.
  17106. ASSERT_TRUE(client.send("hello"));
  17107. std::string msg;
  17108. ASSERT_TRUE(client.read(msg));
  17109. EXPECT_EQ("hello", msg);
  17110. client.close();
  17111. {
  17112. std::lock_guard<std::mutex> lock(mtx);
  17113. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17114. EXPECT_EQ("ABC", received_token);
  17115. }
  17116. svr.stop();
  17117. t.join();
  17118. }
  17119. // Run a handshake against a throwaway server and hand the request the server
  17120. // received back to the caller, so tests can assert on the headers the client
  17121. // actually put on the wire.
  17122. static void capture_websocket_handshake_request(
  17123. const Headers &client_headers,
  17124. std::function<void(const Request &, int port)> verify) {
  17125. Server svr;
  17126. std::mutex mtx;
  17127. Request received;
  17128. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17129. {
  17130. std::lock_guard<std::mutex> lock(mtx);
  17131. received = req;
  17132. }
  17133. std::string msg;
  17134. while (ws.read(msg)) {
  17135. ws.send(msg);
  17136. }
  17137. });
  17138. auto port = svr.bind_to_any_port("localhost");
  17139. std::thread t([&]() { svr.listen_after_bind(); });
  17140. auto se = detail::scope_exit([&] {
  17141. svr.stop();
  17142. t.join();
  17143. });
  17144. svr.wait_until_ready();
  17145. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17146. client_headers);
  17147. ASSERT_TRUE(client.connect());
  17148. ASSERT_TRUE(client.send("hello"));
  17149. std::string msg;
  17150. ASSERT_TRUE(client.read(msg));
  17151. client.close();
  17152. {
  17153. std::lock_guard<std::mutex> lock(mtx);
  17154. verify(received, port);
  17155. }
  17156. }
  17157. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17158. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17159. // Non-default port must be present in the Host header. Default ports
  17160. // (80/443) are omitted; that logic is covered by
  17161. // MakeHostAndPortStringTest.
  17162. EXPECT_EQ("localhost:" + std::to_string(port),
  17163. req.get_header_value("Host"));
  17164. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17165. req.get_header_value("User-Agent"));
  17166. EXPECT_FALSE(req.has_header("Accept"));
  17167. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17168. EXPECT_FALSE(req.has_header("Content-Length"));
  17169. });
  17170. }
  17171. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17172. capture_websocket_handshake_request(
  17173. {{"Host", "example.com"},
  17174. {"User-Agent", "custom-agent"},
  17175. {"X-Custom", "value"}},
  17176. [](const Request &req, int) {
  17177. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17178. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17179. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17180. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17181. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17182. });
  17183. }
  17184. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17185. capture_websocket_handshake_request(
  17186. {{"Upgrade", "bogus"},
  17187. {"Connection", "close"},
  17188. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17189. {"Sec-WebSocket-Version", "8"}},
  17190. [](const Request &req, int) {
  17191. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17192. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17193. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17194. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17195. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17196. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17197. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17198. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17199. req.get_header_value("Sec-WebSocket-Key"));
  17200. });
  17201. }
  17202. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17203. // A header the client refuses to send must abort the handshake before any
  17204. // part of it reaches the wire; a lone request line would otherwise sit in
  17205. // the peer's buffer as a truncated request.
  17206. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17207. ASSERT_NE(INVALID_SOCKET, srv);
  17208. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17209. sockaddr_in addr{};
  17210. addr.sin_family = AF_INET;
  17211. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17212. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17213. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17214. ASSERT_EQ(0, ::listen(srv, 1));
  17215. sockaddr_in bound{};
  17216. socklen_t bound_len = sizeof(bound);
  17217. ASSERT_EQ(
  17218. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17219. auto port = ntohs(bound.sin_port);
  17220. ssize_t received = -1;
  17221. std::thread t([&] {
  17222. // Bound every blocking call so a regression fails the test with a bad
  17223. // value instead of hanging the suite.
  17224. fd_set rfds;
  17225. FD_ZERO(&rfds);
  17226. FD_SET(srv, &rfds);
  17227. timeval tv{5, 0};
  17228. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17229. 0) {
  17230. return;
  17231. }
  17232. sockaddr_in cli_addr{};
  17233. socklen_t cli_len = sizeof(cli_addr);
  17234. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17235. if (cli == INVALID_SOCKET) { return; }
  17236. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17237. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17238. char buf[4096];
  17239. received = ::recv(cli, buf, sizeof(buf), 0);
  17240. });
  17241. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17242. // connect() has already shut the socket down by the time it returns false,
  17243. // so the peer sees EOF without waiting for the client to be destroyed.
  17244. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17245. {{"X-Bad", "a\r\nInjected: 1"}});
  17246. EXPECT_FALSE(client.connect());
  17247. t.join();
  17248. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17249. EXPECT_EQ(0, received);
  17250. }
  17251. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17252. // The socket path doubles as the URL host, so it must not contain '/'.
  17253. const char *shard = getenv("GTEST_SHARD_INDEX");
  17254. const std::string sock_path =
  17255. shard ? std::string("httplib-ws-") + shard + ".sock"
  17256. : std::string("httplib-ws.sock");
  17257. std::remove(sock_path.c_str());
  17258. Server svr;
  17259. std::mutex mtx;
  17260. std::string received_host;
  17261. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17262. {
  17263. std::lock_guard<std::mutex> lock(mtx);
  17264. received_host = req.get_header_value("Host");
  17265. }
  17266. std::string msg;
  17267. while (ws.read(msg)) {
  17268. ws.send(msg);
  17269. }
  17270. });
  17271. svr.set_address_family(AF_UNIX);
  17272. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17273. auto se = detail::scope_exit([&] {
  17274. svr.stop();
  17275. t.join();
  17276. std::remove(sock_path.c_str());
  17277. });
  17278. svr.wait_until_ready();
  17279. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17280. client.set_address_family(AF_UNIX);
  17281. ASSERT_TRUE(client.connect());
  17282. ASSERT_TRUE(client.send("hello"));
  17283. std::string msg;
  17284. ASSERT_TRUE(client.read(msg));
  17285. client.close();
  17286. {
  17287. std::lock_guard<std::mutex> lock(mtx);
  17288. // There is no host:port for a Unix socket, so the same "localhost"
  17289. // placeholder the HTTP client uses is expected.
  17290. EXPECT_EQ("localhost", received_host);
  17291. }
  17292. }
  17293. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17294. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17295. protected:
  17296. void SetUp() override {
  17297. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17298. SERVER_PRIVATE_KEY_FILE);
  17299. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17300. std::string msg;
  17301. ws::ReadResult ret;
  17302. while ((ret = ws.read(msg))) {
  17303. if (ret == ws::Binary) {
  17304. ws.send(msg.data(), msg.size());
  17305. } else {
  17306. ws.send(msg);
  17307. }
  17308. }
  17309. });
  17310. port_ = server_->bind_to_any_port(HOST);
  17311. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17312. server_->wait_until_ready();
  17313. }
  17314. void TearDown() override {
  17315. server_->stop();
  17316. if (server_thread_.joinable()) { server_thread_.join(); }
  17317. }
  17318. std::unique_ptr<SSLServer> server_;
  17319. std::thread server_thread_;
  17320. int port_ = 0;
  17321. };
  17322. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17323. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17324. "/ws-echo");
  17325. client.enable_server_certificate_verification(false);
  17326. ASSERT_TRUE(client.connect());
  17327. ASSERT_TRUE(client.is_open());
  17328. ASSERT_TRUE(client.send("Hello WSS"));
  17329. std::string msg;
  17330. EXPECT_EQ(ws::Text, client.read(msg));
  17331. EXPECT_EQ("Hello WSS", msg);
  17332. client.close();
  17333. }
  17334. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17335. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17336. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17337. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17338. // client (without calling close() first) is the only path that runs
  17339. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17340. // bug exactly.
  17341. //
  17342. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17343. // when linked against an instrumented libssl; run under Valgrind to catch it
  17344. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17345. // suite (the freed session otherwise stalls on the close handshake) — this test
  17346. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17347. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17348. {
  17349. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17350. "/ws-echo");
  17351. client.enable_server_certificate_verification(false);
  17352. client.set_read_timeout(2, 0);
  17353. client.set_write_timeout(2, 0);
  17354. ASSERT_TRUE(client.connect());
  17355. ASSERT_TRUE(client.is_open());
  17356. ASSERT_TRUE(client.send("still open"));
  17357. // Intentionally do NOT call client.close(): leaving scope runs
  17358. // shutdown_and_close() with the WebSocket still open, which must send the
  17359. // close frame while the TLS session is still alive.
  17360. }
  17361. }
  17362. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17363. // shutdown_and_close() at the start of connect(), reproducing the same
  17364. // use-after-free within the test body rather than at scope exit. The second
  17365. // connect must succeed and echo, proving the close handshake ran over a live
  17366. // session. See the note above about memory-tool requirements.
  17367. TEST_F(WebSocketSSLIntegrationTest,
  17368. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17369. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17370. "/ws-echo");
  17371. client.enable_server_certificate_verification(false);
  17372. client.set_read_timeout(2, 0);
  17373. client.set_write_timeout(2, 0);
  17374. ASSERT_TRUE(client.connect());
  17375. ASSERT_TRUE(client.is_open());
  17376. ASSERT_TRUE(client.send("still open"));
  17377. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17378. // the still-open connection, which must not touch a freed TLS session.
  17379. ASSERT_TRUE(client.connect());
  17380. ASSERT_TRUE(client.is_open());
  17381. ASSERT_TRUE(client.send("after reconnect"));
  17382. std::string msg;
  17383. EXPECT_EQ(ws::Text, client.read(msg));
  17384. EXPECT_EQ("after reconnect", msg);
  17385. client.close();
  17386. }
  17387. #endif
  17388. #ifdef CPPHTTPLIB_SSL_ENABLED
  17389. class WebSocketSSLCATest : public ::testing::Test {
  17390. protected:
  17391. void SetUp() override {
  17392. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17393. SERVER_PRIVATE_KEY_FILE);
  17394. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17395. std::string msg;
  17396. while (ws.read(msg)) {
  17397. ws.send(msg);
  17398. }
  17399. });
  17400. port_ = server_->bind_to_any_port("127.0.0.1");
  17401. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17402. server_->wait_until_ready();
  17403. }
  17404. void TearDown() override {
  17405. server_->stop();
  17406. if (server_thread_.joinable()) { server_thread_.join(); }
  17407. }
  17408. std::string url() const {
  17409. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17410. }
  17411. std::unique_ptr<SSLServer> server_;
  17412. std::thread server_thread_;
  17413. int port_ = 0;
  17414. };
  17415. // A custom CA loaded as PEM verifies the server with full certificate
  17416. // verification enabled
  17417. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17418. ws::WebSocketClient client(url());
  17419. std::string cert;
  17420. read_file(SERVER_CERT2_FILE, cert);
  17421. client.load_ca_cert_store(cert.c_str(), cert.size());
  17422. ASSERT_TRUE(client.connect());
  17423. ASSERT_TRUE(client.send("hello"));
  17424. std::string msg;
  17425. EXPECT_EQ(ws::Text, client.read(msg));
  17426. EXPECT_EQ("hello", msg);
  17427. client.close();
  17428. }
  17429. // A custom CA that does not cover the server must fail verification (the
  17430. // custom CA is exclusive; system certs are not loaded alongside it)
  17431. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17432. ws::WebSocketClient client(url());
  17433. std::string cert;
  17434. read_file(CLIENT_CA_CERT_FILE, cert);
  17435. client.load_ca_cert_store(cert.c_str(), cert.size());
  17436. ASSERT_FALSE(client.connect());
  17437. }
  17438. // Regression test: reconnecting with a native custom CA store used to reuse
  17439. // a store handle the previous TLS context had already freed (use-after-free
  17440. // under the OpenSSL backend). The context now lives as long as the client.
  17441. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17442. ws::WebSocketClient client(url());
  17443. std::string cert;
  17444. read_file(SERVER_CERT2_FILE, cert);
  17445. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17446. ASSERT_TRUE(client.connect());
  17447. client.close();
  17448. ASSERT_TRUE(client.connect());
  17449. ASSERT_TRUE(client.send("again"));
  17450. std::string msg;
  17451. EXPECT_EQ(ws::Text, client.read(msg));
  17452. EXPECT_EQ("again", msg);
  17453. client.close();
  17454. }
  17455. // Regression test: a certificate with a trusted chain but no identity match
  17456. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17457. // verification entirely for IP hosts, so this connection succeeded there.
  17458. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17459. // chain verification while the identity check must still fail.
  17460. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17462. ASSERT_TRUE(svr.is_valid());
  17463. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17464. std::string msg;
  17465. while (ws.read(msg)) {
  17466. ws.send(msg);
  17467. }
  17468. });
  17469. auto port = svr.bind_to_any_port("127.0.0.1");
  17470. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17471. auto se = detail::scope_exit([&] {
  17472. svr.stop();
  17473. t.join();
  17474. });
  17475. svr.wait_until_ready();
  17476. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17477. "/echo");
  17478. std::string cert;
  17479. read_file(SERVER_CERT_FILE, cert);
  17480. client.load_ca_cert_store(cert.c_str(), cert.size());
  17481. ASSERT_FALSE(client.connect());
  17482. }
  17483. #endif
  17484. #if !defined(_WIN32)
  17485. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17486. auto secret_dir = std::string("./symlink_test_secret");
  17487. auto served_dir = std::string("./symlink_test_served");
  17488. auto secret_file = secret_dir + "/secret.txt";
  17489. auto symlink_path = served_dir + "/escape";
  17490. // Setup: create directories and files
  17491. mkdir(secret_dir.c_str(), 0755);
  17492. mkdir(served_dir.c_str(), 0755);
  17493. {
  17494. std::ofstream ofs(secret_file);
  17495. ofs << "SECRET_DATA";
  17496. }
  17497. // Create symlink using absolute path so it resolves correctly
  17498. #ifdef PATH_MAX
  17499. char abs_secret[PATH_MAX];
  17500. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17501. #else
  17502. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17503. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17504. ASSERT_NE(nullptr, abs_secret);
  17505. #endif
  17506. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17507. auto se = detail::scope_exit([&] {
  17508. unlink(symlink_path.c_str());
  17509. unlink(secret_file.c_str());
  17510. rmdir(served_dir.c_str());
  17511. rmdir(secret_dir.c_str());
  17512. });
  17513. Server svr;
  17514. svr.set_mount_point("/", served_dir);
  17515. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17516. auto se2 = detail::scope_exit([&] {
  17517. svr.stop();
  17518. listen_thread.join();
  17519. });
  17520. svr.wait_until_ready();
  17521. Client cli("localhost", PORT);
  17522. // Symlink pointing outside base dir should be blocked
  17523. auto res = cli.Get("/escape/secret.txt");
  17524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17525. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17526. }
  17527. #endif
  17528. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17529. // A GET request with Content-Length to a static file handler must have its
  17530. // body drained before the keep-alive connection is reused. Otherwise the
  17531. // unread body bytes are interpreted as the next HTTP request.
  17532. //
  17533. // The body is sent AFTER receiving the first response (as in the original
  17534. // PoC) so that the stream_line_reader cannot buffer it together with the
  17535. // headers of the first request.
  17536. Server svr;
  17537. svr.set_mount_point("/", "./www");
  17538. std::atomic<int> smuggled_count(0);
  17539. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17540. smuggled_count++;
  17541. res.set_content("oops", "text/plain");
  17542. });
  17543. auto port = svr.bind_to_any_port("localhost");
  17544. thread t = thread([&] { svr.listen_after_bind(); });
  17545. auto se = detail::scope_exit([&] {
  17546. svr.stop();
  17547. t.join();
  17548. });
  17549. svr.wait_until_ready();
  17550. auto error = Error::Success;
  17551. auto sock = detail::create_client_socket(
  17552. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17553. /*connection_timeout_sec=*/2, 0,
  17554. /*read_timeout_sec=*/2, 0,
  17555. /*write_timeout_sec=*/2, 0, std::string(), error);
  17556. ASSERT_NE(INVALID_SOCKET, sock);
  17557. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17558. // The "smuggled" request will be sent as the body of the outer GET
  17559. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17560. "Host: localhost\r\n"
  17561. "Connection: close\r\n"
  17562. "\r\n";
  17563. // Step 1: Send only the outer request headers (no body yet)
  17564. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17565. "Host: localhost\r\n"
  17566. "Content-Length: " +
  17567. std::to_string(smuggled.size()) +
  17568. "\r\n"
  17569. "\r\n";
  17570. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17571. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17572. // Step 2: Read the first response (server serves file without reading body)
  17573. std::string first_response;
  17574. char buf[4096];
  17575. for (;;) {
  17576. auto n = recv(sock, buf, sizeof(buf), 0);
  17577. if (n <= 0) break;
  17578. first_response.append(buf, static_cast<size_t>(n));
  17579. // Stop once we have a complete response (headers + body)
  17580. auto hdr_end = first_response.find("\r\n\r\n");
  17581. if (hdr_end != std::string::npos) {
  17582. // Check for Content-Length to know when the body is complete
  17583. auto cl_pos = first_response.find("Content-Length:");
  17584. if (cl_pos != std::string::npos) {
  17585. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17586. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17587. auto cl = std::stoul(
  17588. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17589. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17590. } else {
  17591. break; // No Content-Length, assume headers-only response
  17592. }
  17593. }
  17594. }
  17595. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17596. // Step 3: Now send the body, which looks like a new HTTP request.
  17597. // On a vulnerable server the keep-alive loop reads this as a second request.
  17598. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17599. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17600. // Step 4: Try to read a second response (should NOT exist after fix)
  17601. std::string second_response;
  17602. for (;;) {
  17603. auto n = recv(sock, buf, sizeof(buf), 0);
  17604. if (n <= 0) break;
  17605. second_response.append(buf, static_cast<size_t>(n));
  17606. }
  17607. // The smuggled request must NOT have been processed
  17608. EXPECT_EQ(0, smuggled_count.load());
  17609. }
  17610. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17611. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17612. // must be rejected with 400 Bad Request.
  17613. Server svr;
  17614. svr.Post("/test", [&](const Request &, Response &res) {
  17615. res.set_content("ok", "text/plain");
  17616. });
  17617. thread t = thread([&] { svr.listen(HOST, PORT); });
  17618. auto se = detail::scope_exit([&] {
  17619. svr.stop();
  17620. t.join();
  17621. ASSERT_FALSE(svr.is_running());
  17622. });
  17623. svr.wait_until_ready();
  17624. // Exact "chunked"
  17625. {
  17626. auto req = "POST /test HTTP/1.1\r\n"
  17627. "Host: localhost\r\n"
  17628. "Content-Length: 5\r\n"
  17629. "Transfer-Encoding: chunked\r\n"
  17630. "Connection: close\r\n"
  17631. "\r\n"
  17632. "hello";
  17633. std::string response;
  17634. ASSERT_TRUE(send_request(1, req, &response));
  17635. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17636. response.substr(0, response.find("\r\n")));
  17637. }
  17638. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17639. {
  17640. auto req = "POST /test HTTP/1.1\r\n"
  17641. "Host: localhost\r\n"
  17642. "Content-Length: 5\r\n"
  17643. "Transfer-Encoding: gzip, chunked\r\n"
  17644. "Connection: close\r\n"
  17645. "\r\n"
  17646. "hello";
  17647. std::string response;
  17648. ASSERT_TRUE(send_request(1, req, &response));
  17649. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17650. response.substr(0, response.find("\r\n")));
  17651. }
  17652. }
  17653. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  17654. Server svr;
  17655. svr.Post("/test", [&](const Request &, Response &res) {
  17656. res.set_content("ok", "text/plain");
  17657. });
  17658. thread t = thread([&] { svr.listen(HOST, PORT); });
  17659. auto se = detail::scope_exit([&] {
  17660. svr.stop();
  17661. t.join();
  17662. ASSERT_FALSE(svr.is_running());
  17663. });
  17664. svr.wait_until_ready();
  17665. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  17666. // length cannot be determined, so the server must answer 400 and close
  17667. // rather than treat the request as bodyless and leave the body in the
  17668. // socket for the next request to pick up.
  17669. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  17670. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  17671. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  17672. std::string response;
  17673. ASSERT_TRUE(send_request(1, req, &response));
  17674. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17675. response.substr(0, response.find("\r\n")))
  17676. << transfer_encoding;
  17677. }
  17678. // RFC 9110 5.3: the codings may also be split across several
  17679. // Transfer-Encoding lines, which combine in the order they were received.
  17680. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  17681. // just like the single-line "chunked, gzip" above.
  17682. {
  17683. auto req = "POST /test HTTP/1.1\r\n"
  17684. "Host: localhost\r\n"
  17685. "Transfer-Encoding: chunked\r\n"
  17686. "Transfer-Encoding: gzip\r\n"
  17687. "\r\n"
  17688. "0\r\n\r\n";
  17689. std::string response;
  17690. ASSERT_TRUE(send_request(1, req, &response));
  17691. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17692. response.substr(0, response.find("\r\n")));
  17693. }
  17694. // A sequence ending in chunked stays valid.
  17695. auto req = "POST /test HTTP/1.1\r\n"
  17696. "Host: localhost\r\n"
  17697. "Transfer-Encoding: gzip, chunked\r\n"
  17698. "Connection: close\r\n"
  17699. "\r\n"
  17700. "0\r\n\r\n";
  17701. std::string response;
  17702. ASSERT_TRUE(send_request(1, req, &response));
  17703. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17704. // ...including when it is spread over several lines.
  17705. auto split_req = "POST /test HTTP/1.1\r\n"
  17706. "Host: localhost\r\n"
  17707. "Transfer-Encoding: gzip\r\n"
  17708. "Transfer-Encoding: chunked\r\n"
  17709. "Connection: close\r\n"
  17710. "\r\n"
  17711. "0\r\n\r\n";
  17712. std::string split_response;
  17713. ASSERT_TRUE(send_request(1, split_req, &split_response));
  17714. EXPECT_EQ("HTTP/1.1 200 OK",
  17715. split_response.substr(0, split_response.find("\r\n")));
  17716. }
  17717. // Regression for issue #2450: a DELETE without Content-Length on a
  17718. // keep-alive connection must not let the post-response drain consume the
  17719. // next request's bytes.
  17720. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17721. Server svr;
  17722. std::atomic<int> delete_count(0);
  17723. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17724. delete_count++;
  17725. res.status = StatusCode::NoContent_204;
  17726. });
  17727. auto port = svr.bind_to_any_port(HOST);
  17728. thread t = thread([&] { svr.listen_after_bind(); });
  17729. auto se = detail::scope_exit([&] {
  17730. svr.stop();
  17731. t.join();
  17732. });
  17733. svr.wait_until_ready();
  17734. auto error = Error::Success;
  17735. auto sock = detail::create_client_socket(
  17736. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17737. /*connection_timeout_sec=*/2, 0,
  17738. /*read_timeout_sec=*/2, 0,
  17739. /*write_timeout_sec=*/2, 0, std::string(), error);
  17740. ASSERT_NE(INVALID_SOCKET, sock);
  17741. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17742. auto send_request_and_read_response = [&](const std::string &req,
  17743. std::string &out) -> bool {
  17744. auto sent = send(sock, req.data(), req.size(), 0);
  17745. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17746. char buf[4096];
  17747. for (;;) {
  17748. auto n = recv(sock, buf, sizeof(buf), 0);
  17749. if (n <= 0) { return !out.empty(); }
  17750. out.append(buf, static_cast<size_t>(n));
  17751. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17752. }
  17753. };
  17754. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17755. "Host: localhost\r\n"
  17756. "\r\n";
  17757. std::string resp1;
  17758. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17759. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17760. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17761. "Host: localhost\r\n"
  17762. "Connection: close\r\n"
  17763. "\r\n";
  17764. std::string resp2;
  17765. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17766. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17767. EXPECT_EQ(2, delete_count.load());
  17768. }
  17769. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17770. Server svr;
  17771. svr.Post("/ingest", [&](const Request &, Response &res,
  17772. const ContentReader &content_reader) {
  17773. auto consumed = content_reader([](const char *, size_t) { return false; });
  17774. EXPECT_FALSE(consumed);
  17775. res.status = StatusCode::Conflict_409;
  17776. res.set_header("Connection", "close");
  17777. });
  17778. auto port = svr.bind_to_any_port(HOST);
  17779. thread t = thread([&] { svr.listen_after_bind(); });
  17780. auto se = detail::scope_exit([&] {
  17781. svr.stop();
  17782. t.join();
  17783. });
  17784. svr.wait_until_ready();
  17785. auto error = Error::Success;
  17786. auto sock = detail::create_client_socket(
  17787. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17788. /*connection_timeout_sec=*/2, 0,
  17789. /*read_timeout_sec=*/1, 0,
  17790. /*write_timeout_sec=*/2, 0, std::string(), error);
  17791. ASSERT_NE(INVALID_SOCKET, sock);
  17792. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17793. std::string request = "POST /ingest HTTP/1.1\r\n"
  17794. "Host: localhost\r\n"
  17795. "Transfer-Encoding: chunked\r\n"
  17796. "\r\n"
  17797. "4\r\n"
  17798. "data\r\n";
  17799. auto sent = send(sock, request.data(), request.size(), 0);
  17800. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17801. std::string response;
  17802. ssize_t received = 0;
  17803. do {
  17804. char buf[4096];
  17805. received = recv(sock, buf, sizeof(buf), 0);
  17806. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17807. } while (received > 0);
  17808. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17809. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17810. EXPECT_EQ(0, received);
  17811. }
  17812. namespace no_proxy_test {
  17813. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17814. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17815. // calling listen().
  17816. class ScopedServer {
  17817. public:
  17818. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17819. ~ScopedServer() {
  17820. svr_.stop();
  17821. if (th_.joinable()) { th_.join(); }
  17822. }
  17823. Server &svr() { return svr_; }
  17824. int port() const { return port_; }
  17825. void listen() {
  17826. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17827. svr_.wait_until_ready();
  17828. }
  17829. private:
  17830. Server svr_;
  17831. std::thread th_;
  17832. int port_ = 0;
  17833. };
  17834. class ProxyAndTargetServers {
  17835. public:
  17836. ProxyAndTargetServers() {
  17837. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17838. proxy_hits_++;
  17839. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17840. res.set_content("via-proxy", "text/plain");
  17841. });
  17842. target_.Get(".*", [this](const Request &req, Response &res) {
  17843. target_hits_++;
  17844. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17845. res.set_content("direct", "text/plain");
  17846. });
  17847. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17848. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17849. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17850. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17851. proxy_mock_.wait_until_ready();
  17852. target_.wait_until_ready();
  17853. }
  17854. ~ProxyAndTargetServers() {
  17855. proxy_mock_.stop();
  17856. target_.stop();
  17857. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17858. if (target_thread_.joinable()) { target_thread_.join(); }
  17859. }
  17860. Server &proxy_mock() { return proxy_mock_; }
  17861. Server &target() { return target_; }
  17862. int proxy_port() const { return proxy_port_; }
  17863. int target_port() const { return target_port_; }
  17864. int proxy_hits() const { return proxy_hits_.load(); }
  17865. int target_hits() const { return target_hits_.load(); }
  17866. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17867. void reset_counters() {
  17868. proxy_hits_ = 0;
  17869. target_hits_ = 0;
  17870. last_had_proxy_authz_ = false;
  17871. }
  17872. private:
  17873. Server proxy_mock_;
  17874. Server target_;
  17875. std::thread proxy_thread_;
  17876. std::thread target_thread_;
  17877. int proxy_port_ = 0;
  17878. int target_port_ = 0;
  17879. std::atomic<int> proxy_hits_{0};
  17880. std::atomic<int> target_hits_{0};
  17881. std::atomic<bool> last_had_proxy_authz_{false};
  17882. };
  17883. inline std::unique_ptr<Client> make_client(const std::string &host,
  17884. ProxyAndTargetServers &s) {
  17885. auto cli = detail::make_unique<Client>(host, s.target_port());
  17886. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17887. cli->set_proxy("127.0.0.1", s.proxy_port());
  17888. return cli;
  17889. }
  17890. } // namespace no_proxy_test
  17891. using no_proxy_test::make_client;
  17892. using no_proxy_test::ProxyAndTargetServers;
  17893. TEST(NoProxyTest, ExactHostnameBypasses) {
  17894. ProxyAndTargetServers s;
  17895. auto cli = make_client("example.com", s);
  17896. cli->set_no_proxy({"example.com"});
  17897. auto res = cli->Get("/");
  17898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17899. EXPECT_EQ(0, s.proxy_hits());
  17900. EXPECT_EQ(1, s.target_hits());
  17901. }
  17902. TEST(NoProxyTest, SubdomainBypasses) {
  17903. ProxyAndTargetServers s;
  17904. auto cli = make_client("foo.example.com", s);
  17905. cli->set_no_proxy({"example.com"});
  17906. auto res = cli->Get("/");
  17907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17908. EXPECT_EQ(0, s.proxy_hits());
  17909. EXPECT_EQ(1, s.target_hits());
  17910. }
  17911. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17912. // Regression guard: "evilexample.com" must not be considered a subdomain
  17913. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17914. // check would let traffic bypass the proxy and leak credentials direct
  17915. // to the attacker host.
  17916. ProxyAndTargetServers s;
  17917. auto cli = make_client("evilexample.com", s);
  17918. cli->set_no_proxy({"example.com"});
  17919. auto res = cli->Get("/");
  17920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17921. EXPECT_GE(s.proxy_hits(), 1);
  17922. EXPECT_EQ(0, s.target_hits());
  17923. }
  17924. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17925. ProxyAndTargetServers s;
  17926. auto cli = make_client("example.com.evil.com", s);
  17927. cli->set_no_proxy({"example.com"});
  17928. auto res = cli->Get("/");
  17929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17930. EXPECT_GE(s.proxy_hits(), 1);
  17931. EXPECT_EQ(0, s.target_hits());
  17932. }
  17933. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17934. ProxyAndTargetServers s;
  17935. auto cli = make_client("example.com", s);
  17936. cli->set_no_proxy({".example.com"});
  17937. auto res = cli->Get("/");
  17938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17939. EXPECT_EQ(0, s.proxy_hits());
  17940. EXPECT_EQ(1, s.target_hits());
  17941. }
  17942. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17943. ProxyAndTargetServers s;
  17944. auto cli = make_client("Example.COM", s);
  17945. cli->set_no_proxy({"EXAMPLE.com"});
  17946. auto res = cli->Get("/");
  17947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17948. EXPECT_EQ(0, s.proxy_hits());
  17949. EXPECT_EQ(1, s.target_hits());
  17950. }
  17951. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17952. ProxyAndTargetServers s;
  17953. auto cli = make_client("example.com.", s);
  17954. cli->set_no_proxy({"example.com"});
  17955. auto res = cli->Get("/");
  17956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17957. EXPECT_EQ(0, s.proxy_hits());
  17958. EXPECT_EQ(1, s.target_hits());
  17959. }
  17960. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17961. // Trailing dots must be normalized on BOTH sides — host and entry.
  17962. // An implementation that only strips the host-side trailing dot would
  17963. // fail to match host "example.com" against entry "example.com." because
  17964. // a literal substring search would compare 11 chars against 12.
  17965. ProxyAndTargetServers s;
  17966. auto cli = make_client("example.com", s);
  17967. cli->set_no_proxy({"example.com."});
  17968. auto res = cli->Get("/");
  17969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17970. EXPECT_EQ(0, s.proxy_hits());
  17971. EXPECT_EQ(1, s.target_hits());
  17972. }
  17973. TEST(NoProxyTest, WildcardBypassesEverything) {
  17974. ProxyAndTargetServers s;
  17975. auto cli = make_client("anything.invalid.test", s);
  17976. cli->set_no_proxy({"*"});
  17977. auto res = cli->Get("/");
  17978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17979. EXPECT_EQ(0, s.proxy_hits());
  17980. EXPECT_EQ(1, s.target_hits());
  17981. }
  17982. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17983. ProxyAndTargetServers s;
  17984. Client cli("127.0.0.1", s.target_port());
  17985. cli.set_proxy("127.0.0.1", s.proxy_port());
  17986. cli.set_no_proxy({"127.0.0.1"});
  17987. auto res = cli.Get("/");
  17988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17989. EXPECT_EQ(0, s.proxy_hits());
  17990. EXPECT_EQ(1, s.target_hits());
  17991. }
  17992. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17993. ProxyAndTargetServers s;
  17994. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17995. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17996. cli.set_proxy("127.0.0.1", s.proxy_port());
  17997. cli.set_no_proxy({"::1"});
  17998. auto res = cli.Get("/");
  17999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18000. EXPECT_EQ(0, s.proxy_hits());
  18001. EXPECT_EQ(1, s.target_hits());
  18002. }
  18003. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18004. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18005. // must still be recognized as IPv6 for CIDR matching. Implementations
  18006. // that detect IPv6 only when the host begins with '[' would parse the
  18007. // host as a hostname and miss the match.
  18008. ProxyAndTargetServers s;
  18009. Client cli("fe80::1", s.target_port());
  18010. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18011. cli.set_proxy("127.0.0.1", s.proxy_port());
  18012. cli.set_no_proxy({"fe80::/10"});
  18013. auto res = cli.Get("/");
  18014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18015. EXPECT_EQ(0, s.proxy_hits());
  18016. EXPECT_EQ(1, s.target_hits());
  18017. }
  18018. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18019. ProxyAndTargetServers s;
  18020. Client cli("::1", s.target_port());
  18021. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18022. cli.set_proxy("127.0.0.1", s.proxy_port());
  18023. cli.set_no_proxy({"[::1]"});
  18024. auto res = cli.Get("/");
  18025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18026. EXPECT_EQ(0, s.proxy_hits());
  18027. EXPECT_EQ(1, s.target_hits());
  18028. }
  18029. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18030. ProxyAndTargetServers s;
  18031. Client cli("fe80::1", s.target_port());
  18032. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18033. cli.set_proxy("127.0.0.1", s.proxy_port());
  18034. cli.set_no_proxy({"[fe80::]/10"});
  18035. auto res = cli.Get("/");
  18036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18037. EXPECT_EQ(0, s.proxy_hits());
  18038. EXPECT_EQ(1, s.target_hits());
  18039. }
  18040. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18041. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18042. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18043. // tricks via address-family conversion.
  18044. ProxyAndTargetServers s;
  18045. Client cli("::ffff:127.0.0.1", s.target_port());
  18046. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18047. cli.set_proxy("127.0.0.1", s.proxy_port());
  18048. cli.set_no_proxy({"127.0.0.1"});
  18049. auto res = cli.Get("/");
  18050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18051. EXPECT_GE(s.proxy_hits(), 1);
  18052. EXPECT_EQ(0, s.target_hits());
  18053. }
  18054. TEST(NoProxyTest, IPv4CidrMatch) {
  18055. ProxyAndTargetServers s;
  18056. Client cli("127.0.0.1", s.target_port());
  18057. cli.set_proxy("127.0.0.1", s.proxy_port());
  18058. cli.set_no_proxy({"127.0.0.0/8"});
  18059. auto res = cli.Get("/");
  18060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18061. EXPECT_EQ(0, s.proxy_hits());
  18062. EXPECT_EQ(1, s.target_hits());
  18063. }
  18064. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18065. ProxyAndTargetServers s;
  18066. Client cli("127.0.0.1", s.target_port());
  18067. cli.set_proxy("127.0.0.1", s.proxy_port());
  18068. cli.set_no_proxy({"10.0.0.0/8"});
  18069. auto res = cli.Get("/");
  18070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18071. EXPECT_GE(s.proxy_hits(), 1);
  18072. EXPECT_EQ(0, s.target_hits());
  18073. }
  18074. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18075. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18076. // IPv4 target matches.
  18077. ProxyAndTargetServers s;
  18078. Client cli("127.0.0.1", s.target_port());
  18079. cli.set_proxy("127.0.0.1", s.proxy_port());
  18080. cli.set_no_proxy({"0.0.0.0/0"});
  18081. auto res = cli.Get("/");
  18082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18083. EXPECT_EQ(0, s.proxy_hits());
  18084. EXPECT_EQ(1, s.target_hits());
  18085. }
  18086. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18087. ProxyAndTargetServers s;
  18088. Client cli("127.0.0.1", s.target_port());
  18089. cli.set_proxy("127.0.0.1", s.proxy_port());
  18090. cli.set_no_proxy({"127.0.0.1"});
  18091. auto res = cli.Get("/");
  18092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18093. EXPECT_EQ(0, s.proxy_hits());
  18094. EXPECT_EQ(1, s.target_hits());
  18095. }
  18096. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18097. ProxyAndTargetServers s;
  18098. Client cli("127.0.0.1", s.target_port());
  18099. cli.set_proxy("127.0.0.1", s.proxy_port());
  18100. cli.set_no_proxy({"127.0.0.0/33"});
  18101. auto res = cli.Get("/");
  18102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18103. EXPECT_GE(s.proxy_hits(), 1);
  18104. EXPECT_EQ(0, s.target_hits());
  18105. }
  18106. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18107. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18108. ProxyAndTargetServers s;
  18109. Client cli("127.0.0.1", s.target_port());
  18110. cli.set_proxy("127.0.0.1", s.proxy_port());
  18111. cli.set_no_proxy({"127.0.0.1/"});
  18112. auto res = cli.Get("/");
  18113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18114. EXPECT_GE(s.proxy_hits(), 1);
  18115. EXPECT_EQ(0, s.target_hits());
  18116. }
  18117. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18118. ProxyAndTargetServers s;
  18119. auto cli = make_client("internal.corp", s);
  18120. cli->set_proxy_basic_auth("u", "p");
  18121. cli->set_no_proxy({"internal.corp"});
  18122. auto res = cli->Get("/");
  18123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18124. EXPECT_EQ(1, s.target_hits());
  18125. EXPECT_EQ(0, s.proxy_hits());
  18126. EXPECT_FALSE(s.last_had_proxy_authz())
  18127. << "Proxy-Authorization must not be sent direct to the target";
  18128. }
  18129. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18130. ProxyAndTargetServers s;
  18131. auto cli = make_client("public.example", s);
  18132. cli->set_proxy_basic_auth("u", "p");
  18133. cli->set_no_proxy({"internal.corp"}); // does not match
  18134. auto res = cli->Get("/");
  18135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18136. EXPECT_GE(s.proxy_hits(), 1);
  18137. EXPECT_TRUE(s.last_had_proxy_authz());
  18138. }
  18139. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18140. ProxyAndTargetServers s;
  18141. auto cli = make_client("anything.test", s);
  18142. auto res = cli->Get("/");
  18143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18144. EXPECT_GE(s.proxy_hits(), 1);
  18145. EXPECT_EQ(0, s.target_hits());
  18146. }
  18147. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18148. ProxyAndTargetServers s;
  18149. auto cli = make_client("example.com", s);
  18150. cli->set_no_proxy({"example.com:8080"});
  18151. auto res = cli->Get("/");
  18152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18153. EXPECT_GE(s.proxy_hits(), 1);
  18154. EXPECT_EQ(0, s.target_hits());
  18155. }
  18156. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18157. ProxyAndTargetServers s;
  18158. auto cli = make_client("anything.test", s);
  18159. cli->set_no_proxy({"", " ", "\t"});
  18160. auto res = cli->Get("/");
  18161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18162. EXPECT_GE(s.proxy_hits(), 1);
  18163. EXPECT_EQ(0, s.target_hits());
  18164. }
  18165. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18166. // An entry with leading/trailing whitespace must still match — env-style
  18167. // values are commonly pasted with stray spaces and an implementation
  18168. // that feeds the raw token directly to inet_pton would fail to match
  18169. // valid CIDRs because of the spaces.
  18170. ProxyAndTargetServers s;
  18171. Client cli("127.0.0.1", s.target_port());
  18172. cli.set_proxy("127.0.0.1", s.proxy_port());
  18173. cli.set_no_proxy({" 127.0.0.0/8 "});
  18174. auto res = cli.Get("/");
  18175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18176. EXPECT_EQ(0, s.proxy_hits());
  18177. EXPECT_EQ(1, s.target_hits());
  18178. }
  18179. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18180. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18181. // go direct and must NOT carry Proxy-Authorization.
  18182. std::atomic<int> proxy_hits{0};
  18183. std::atomic<int> target_hits{0};
  18184. std::atomic<bool> target_saw_authz{false};
  18185. no_proxy_test::ScopedServer proxy_mock, target;
  18186. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18187. proxy_hits++;
  18188. res.status = 302;
  18189. res.set_header("Location", "http://127.0.0.1:" +
  18190. std::to_string(target.port()) + "/landed");
  18191. });
  18192. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18193. target_hits++;
  18194. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18195. res.set_content("direct", "text/plain");
  18196. });
  18197. proxy_mock.listen();
  18198. target.listen();
  18199. Client cli("public.example", target.port());
  18200. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18201. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18202. cli.set_proxy_basic_auth("u", "p");
  18203. cli.set_no_proxy({"127.0.0.1"});
  18204. cli.set_follow_location(true);
  18205. auto res = cli.Get("/redir");
  18206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18207. EXPECT_GE(proxy_hits.load(), 1);
  18208. EXPECT_GE(target_hits.load(), 1);
  18209. EXPECT_FALSE(target_saw_authz.load());
  18210. }
  18211. #ifdef CPPHTTPLIB_SSL_ENABLED
  18212. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18213. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18214. // proxy creds would be sent to the (possibly hostile) origin.
  18215. std::atomic<int> target_hits{0};
  18216. std::atomic<bool> target_saw_proxy_authz{false};
  18217. no_proxy_test::ScopedServer target;
  18218. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18219. target_hits++;
  18220. if (req.has_header("Proxy-Authorization")) {
  18221. target_saw_proxy_authz = true;
  18222. }
  18223. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18224. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18225. "nonce=\"abc\", algorithm=MD5");
  18226. });
  18227. target.listen();
  18228. // The proxy address is set to the target's port: the bypass MUST kick in;
  18229. // if it doesn't, the test still routes "via proxy" to the same server and
  18230. // the Proxy-Authorization assertion below catches the leak.
  18231. Client cli("evil.example", target.port());
  18232. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18233. cli.set_proxy("127.0.0.1", target.port());
  18234. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18235. cli.set_no_proxy({"evil.example"});
  18236. auto res = cli.Get("/x");
  18237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18238. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18239. EXPECT_EQ(1, target_hits.load());
  18240. EXPECT_FALSE(target_saw_proxy_authz.load());
  18241. }
  18242. #endif
  18243. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18244. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18245. std::atomic<int> proxy_hits{0};
  18246. std::atomic<int> bypass_hits{0};
  18247. std::atomic<bool> proxy_saw_c_url{false};
  18248. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18249. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18250. proxy_hits++;
  18251. if (req.path.find("/start") != std::string::npos) {
  18252. res.status = 302;
  18253. res.set_header("Location", "http://127.0.0.1:" +
  18254. std::to_string(bypass_server.port()) +
  18255. "/middle");
  18256. return;
  18257. }
  18258. if (req.path.find("/end") != std::string::npos) {
  18259. proxy_saw_c_url = true;
  18260. res.set_content("c-via-proxy", "text/plain");
  18261. return;
  18262. }
  18263. res.set_content("unexpected", "text/plain");
  18264. });
  18265. // public.example's "advertised" port is arbitrary (the request never lands
  18266. // there — it goes through the proxy), but use a dynamic value to stay
  18267. // friendly with sharded parallel runs.
  18268. int public_port = bypass_server.port();
  18269. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18270. bypass_hits++;
  18271. res.status = 302;
  18272. res.set_header("Location", "http://public.example:" +
  18273. std::to_string(public_port) + "/end");
  18274. });
  18275. proxy_mock.listen();
  18276. bypass_server.listen();
  18277. Client cli("public.example", public_port);
  18278. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18279. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18280. cli.set_no_proxy({"127.0.0.1"});
  18281. cli.set_follow_location(true);
  18282. auto res = cli.Get("/start");
  18283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18284. EXPECT_EQ(StatusCode::OK_200, res->status);
  18285. EXPECT_EQ("c-via-proxy", res->body);
  18286. EXPECT_GE(proxy_hits.load(), 2);
  18287. EXPECT_GE(bypass_hits.load(), 1);
  18288. EXPECT_TRUE(proxy_saw_c_url.load());
  18289. }
  18290. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18291. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18292. // request reconnects to the correct endpoint.
  18293. std::atomic<int> proxy_hits{0};
  18294. std::atomic<int> target_hits{0};
  18295. no_proxy_test::ScopedServer proxy_mock, target;
  18296. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18297. proxy_hits++;
  18298. res.set_content("via-proxy", "text/plain");
  18299. });
  18300. target.svr().Get(".*", [&](const Request &, Response &res) {
  18301. target_hits++;
  18302. res.set_content("direct", "text/plain");
  18303. });
  18304. proxy_mock.listen();
  18305. target.listen();
  18306. Client cli("public.example", target.port());
  18307. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18308. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18309. cli.set_keep_alive(true);
  18310. auto res1 = cli.Get("/a");
  18311. ASSERT_TRUE(res1);
  18312. EXPECT_EQ("via-proxy", res1->body);
  18313. EXPECT_EQ(1, proxy_hits.load());
  18314. EXPECT_EQ(0, target_hits.load());
  18315. cli.set_no_proxy({"public.example"});
  18316. auto res2 = cli.Get("/b");
  18317. ASSERT_TRUE(res2);
  18318. EXPECT_EQ("direct", res2->body);
  18319. EXPECT_EQ(1, proxy_hits.load());
  18320. EXPECT_EQ(1, target_hits.load());
  18321. }
  18322. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18323. namespace proxy_tunnel_test {
  18324. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18325. class ScopedSSLServer {
  18326. public:
  18327. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18328. port_ = svr_.bind_to_any_port("127.0.0.1");
  18329. }
  18330. ~ScopedSSLServer() {
  18331. svr_.stop();
  18332. if (th_.joinable()) { th_.join(); }
  18333. }
  18334. SSLServer &svr() { return svr_; }
  18335. int port() const { return port_; }
  18336. void listen() {
  18337. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18338. svr_.wait_until_ready();
  18339. }
  18340. private:
  18341. SSLServer svr_;
  18342. std::thread th_;
  18343. int port_ = 0;
  18344. };
  18345. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18346. class ScopedConnectProxy {
  18347. public:
  18348. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18349. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18350. if (listen_fd_ < 0) { return; }
  18351. int yes = 1;
  18352. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18353. sockaddr_in a{};
  18354. a.sin_family = AF_INET;
  18355. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18356. a.sin_port = 0;
  18357. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18358. return;
  18359. }
  18360. socklen_t alen = sizeof(a);
  18361. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18362. 0) {
  18363. return;
  18364. }
  18365. port_ = ntohs(a.sin_port);
  18366. if (::listen(listen_fd_, 1) != 0) { return; }
  18367. th_ = std::thread([this] { run(); });
  18368. }
  18369. ~ScopedConnectProxy() {
  18370. stop_ = true;
  18371. if (listen_fd_ >= 0) {
  18372. ::shutdown(listen_fd_, SHUT_RDWR);
  18373. ::close(listen_fd_);
  18374. }
  18375. if (th_.joinable()) { th_.join(); }
  18376. }
  18377. int port() const { return port_; }
  18378. int connect_hits() const { return connect_hits_.load(); }
  18379. private:
  18380. void run() {
  18381. while (!stop_.load()) {
  18382. fd_set rfds;
  18383. FD_ZERO(&rfds);
  18384. FD_SET(listen_fd_, &rfds);
  18385. timeval tv{0, 100 * 1000};
  18386. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18387. if (sel <= 0) { continue; }
  18388. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18389. if (client_fd < 0) { continue; }
  18390. std::string req;
  18391. char buf[2048];
  18392. while (req.find("\r\n\r\n") == std::string::npos) {
  18393. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18394. if (n <= 0) { break; }
  18395. req.append(buf, static_cast<size_t>(n));
  18396. }
  18397. if (req.compare(0, 7, "CONNECT") != 0) {
  18398. ::close(client_fd);
  18399. continue;
  18400. }
  18401. connect_hits_++;
  18402. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18403. ::send(client_fd, ok, std::strlen(ok), 0);
  18404. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18405. sockaddr_in o{};
  18406. o.sin_family = AF_INET;
  18407. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18408. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18409. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18410. 0) {
  18411. ::close(client_fd);
  18412. ::close(origin_fd);
  18413. continue;
  18414. }
  18415. auto forward = [](int from, int to) {
  18416. char b[8192];
  18417. for (;;) {
  18418. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18419. if (n <= 0) { break; }
  18420. ssize_t off = 0;
  18421. while (off < n) {
  18422. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18423. if (s <= 0) {
  18424. off = n;
  18425. break;
  18426. }
  18427. off += s;
  18428. }
  18429. }
  18430. ::shutdown(to, SHUT_WR);
  18431. };
  18432. std::thread t1([&] { forward(client_fd, origin_fd); });
  18433. std::thread t2([&] { forward(origin_fd, client_fd); });
  18434. t1.join();
  18435. t2.join();
  18436. ::close(client_fd);
  18437. ::close(origin_fd);
  18438. }
  18439. }
  18440. int forward_port_ = -1;
  18441. int listen_fd_ = -1;
  18442. int port_ = 0;
  18443. std::thread th_;
  18444. std::atomic<bool> stop_{false};
  18445. std::atomic<int> connect_hits_{0};
  18446. };
  18447. } // namespace proxy_tunnel_test
  18448. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18449. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18450. // retry; otherwise proxy creds would be sent to the origin.
  18451. std::atomic<int> origin_hits{0};
  18452. std::atomic<bool> origin_saw_proxy_authz{false};
  18453. proxy_tunnel_test::ScopedSSLServer origin;
  18454. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18455. origin_hits++;
  18456. if (req.has_header("Proxy-Authorization")) {
  18457. origin_saw_proxy_authz = true;
  18458. }
  18459. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18460. res.set_header("Proxy-Authenticate",
  18461. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18462. "algorithm=MD5");
  18463. });
  18464. origin.listen();
  18465. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18466. ASSERT_NE(0, proxy.port());
  18467. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18468. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18469. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18470. // and answer with its own status, making this test flaky.
  18471. SSLClient cli("127.0.0.1", origin.port());
  18472. cli.enable_server_certificate_verification(false);
  18473. cli.set_proxy("127.0.0.1", proxy.port());
  18474. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18475. auto res = cli.Get("/x");
  18476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18477. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18478. EXPECT_EQ(1, origin_hits.load());
  18479. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18480. EXPECT_EQ(1, proxy.connect_hits());
  18481. }
  18482. #endif