test.cc 642 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744
  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 <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  47. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  48. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  49. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  50. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  51. #ifdef CPPHTTPLIB_SSL_ENABLED
  52. namespace httplib {
  53. namespace tls {
  54. // Declared here for the split build, where the TLS abstraction declarations
  55. // live below the split border; the definition is linked from httplib.cc.
  56. ca_store_t create_ca_store(const char *pem, size_t len);
  57. } // namespace tls
  58. } // namespace httplib
  59. #endif
  60. using namespace std;
  61. using namespace httplib;
  62. const char *HOST = "localhost";
  63. static int get_base_port() {
  64. const char *shard = getenv("GTEST_SHARD_INDEX");
  65. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  66. }
  67. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  68. // New standalone tests MUST use svr.bind_to_any_port() instead.
  69. const int PORT = get_base_port();
  70. const string LONG_QUERY_VALUE = string(25000, '@');
  71. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  72. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  73. const string TOO_LONG_QUERY_URL =
  74. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  75. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  76. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  77. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  78. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  79. return file.name == key;
  80. });
  81. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  82. return *it;
  83. #else
  84. if (it != items.end()) { return *it; }
  85. throw std::runtime_error("invalid multipart form data name error");
  86. #endif
  87. }
  88. static void read_file(const std::string &path, std::string &out) {
  89. std::ifstream fs(path, std::ios_base::binary);
  90. if (!fs) {
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return;
  93. #else
  94. throw std::runtime_error("File not found: " + path);
  95. #endif
  96. }
  97. fs.seekg(0, std::ios_base::end);
  98. auto size = fs.tellg();
  99. fs.seekg(0);
  100. out.resize(static_cast<size_t>(size));
  101. fs.read(&out[0], static_cast<std::streamsize>(size));
  102. }
  103. class UnixSocketTest : public ::testing::Test {
  104. protected:
  105. void TearDown() override { std::remove(pathname_.c_str()); }
  106. void client_GET(const std::string &addr) {
  107. httplib::Client cli{addr};
  108. cli.set_address_family(AF_UNIX);
  109. ASSERT_TRUE(cli.is_valid());
  110. const auto &result = cli.Get(pattern_);
  111. ASSERT_TRUE(result) << "error: " << result.error();
  112. const auto &resp = result.value();
  113. EXPECT_EQ(resp.status, StatusCode::OK_200);
  114. EXPECT_EQ(resp.body, content_);
  115. }
  116. static std::string make_sock_path() {
  117. const char *shard = getenv("GTEST_SHARD_INDEX");
  118. return shard ? std::string("./httplib-server-") + shard + ".sock"
  119. : "./httplib-server.sock";
  120. }
  121. const std::string pathname_{make_sock_path()};
  122. const std::string pattern_{"/hi"};
  123. const std::string content_{"Hello World!"};
  124. };
  125. TEST_F(UnixSocketTest, pathname) {
  126. httplib::Server svr;
  127. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  128. res.set_content(content_, "text/plain");
  129. });
  130. std::thread t{[&] {
  131. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  132. }};
  133. auto se = detail::scope_exit([&] {
  134. svr.stop();
  135. t.join();
  136. ASSERT_FALSE(svr.is_running());
  137. });
  138. svr.wait_until_ready();
  139. ASSERT_TRUE(svr.is_running());
  140. client_GET(pathname_);
  141. }
  142. #if defined(__linux__) || \
  143. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  144. TEST_F(UnixSocketTest, PeerPid) {
  145. httplib::Server svr;
  146. std::string remote_port_val;
  147. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  148. res.set_content(content_, "text/plain");
  149. remote_port_val = std::to_string(req.remote_port);
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  163. }
  164. #endif
  165. #ifdef __linux__
  166. TEST_F(UnixSocketTest, abstract) {
  167. constexpr char svr_path[]{"\x00httplib-server.sock"};
  168. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  169. httplib::Server svr;
  170. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  171. res.set_content(content_, "text/plain");
  172. });
  173. std::thread t{[&] {
  174. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  175. }};
  176. auto se = detail::scope_exit([&] {
  177. svr.stop();
  178. t.join();
  179. ASSERT_FALSE(svr.is_running());
  180. });
  181. svr.wait_until_ready();
  182. ASSERT_TRUE(svr.is_running());
  183. client_GET(abstract_addr);
  184. }
  185. #endif
  186. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  187. httplib::Server svr;
  188. std::string received_host_header;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. // Capture the Host header sent by the client
  191. auto host_iter = req.headers.find("Host");
  192. if (host_iter != req.headers.end()) {
  193. received_host_header = host_iter->second;
  194. }
  195. res.set_content(content_, "text/plain");
  196. });
  197. std::thread t{[&] {
  198. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  199. }};
  200. auto se = detail::scope_exit([&] {
  201. svr.stop();
  202. t.join();
  203. ASSERT_FALSE(svr.is_running());
  204. });
  205. svr.wait_until_ready();
  206. ASSERT_TRUE(svr.is_running());
  207. // Test that Host header is automatically set to "localhost" for Unix socket
  208. // connections
  209. httplib::Client cli{pathname_};
  210. cli.set_address_family(AF_UNIX);
  211. ASSERT_TRUE(cli.is_valid());
  212. const auto &result = cli.Get(pattern_);
  213. ASSERT_TRUE(result) << "error: " << result.error();
  214. const auto &resp = result.value();
  215. EXPECT_EQ(resp.status, StatusCode::OK_200);
  216. EXPECT_EQ(resp.body, content_);
  217. // Verify that Host header was automatically set to "localhost"
  218. EXPECT_EQ(received_host_header, "localhost");
  219. }
  220. #ifndef _WIN32
  221. TEST(SocketStream, wait_writable_UNIX) {
  222. int fds[2];
  223. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(fds[0], [&](Stream &s0) {
  230. EXPECT_EQ(s0.socket(), fds[0]);
  231. EXPECT_TRUE(s0.wait_writable());
  232. EXPECT_TRUE(s0.is_peer_alive());
  233. EXPECT_EQ(0, close(fds[1]));
  234. EXPECT_FALSE(s0.is_peer_alive());
  235. return true;
  236. });
  237. EXPECT_EQ(0, close(fds[0]));
  238. }
  239. TEST(SocketStream, wait_writable_INET) {
  240. sockaddr_in addr;
  241. memset(&addr, 0, sizeof(addr));
  242. addr.sin_family = AF_INET;
  243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  245. int disconnected_svr_sock = -1;
  246. std::thread svr{[&] {
  247. const int s = socket(AF_INET, SOCK_STREAM, 0);
  248. ASSERT_LE(0, s);
  249. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  250. ASSERT_EQ(0, listen(s, 1));
  251. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  252. ASSERT_EQ(0, close(s));
  253. }};
  254. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  255. std::thread cli{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  259. ASSERT_EQ(0, close(s));
  260. }};
  261. cli.join();
  262. svr.join();
  263. ASSERT_NE(disconnected_svr_sock, -1);
  264. const auto asSocketStream = [&](socket_t fd,
  265. std::function<bool(Stream &)> func) {
  266. return detail::process_client_socket(
  267. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  268. };
  269. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  270. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  271. // wait_writable() returns true because select_write() only checks if the
  272. // send buffer has space. Peer disconnection is detected later by send().
  273. EXPECT_TRUE(ss.wait_writable());
  274. return true;
  275. });
  276. ASSERT_EQ(0, close(disconnected_svr_sock));
  277. }
  278. #endif // #ifndef _WIN32
  279. TEST(SetSocketOptTest, TcpNoDelay) {
  280. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  281. ASSERT_NE(sock, INVALID_SOCKET);
  282. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  283. int val = 0;
  284. socklen_t len = sizeof(val);
  285. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  286. reinterpret_cast<char *>(&val), &len));
  287. EXPECT_NE(val, 0);
  288. detail::close_socket(sock);
  289. }
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. U8("descrip=Gastos áéíóúñÑ 6"));
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(DecodePathTest, UnicodeEncoding) {
  319. // %u0041 = 'A' (1-byte UTF-8)
  320. EXPECT_EQ("A", decode_path_component("%u0041"));
  321. // %u00E9 = 'é' (2-byte UTF-8)
  322. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  323. // %u3042 = 'あ' (3-byte UTF-8)
  324. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  325. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  326. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  327. // %uD800 = surrogate (invalid, silently dropped)
  328. EXPECT_EQ("", decode_path_component("%uD800"));
  329. }
  330. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  331. // A sign or whitespace inside the two-character escape window must not be
  332. // accepted as a valid percent-encoding; the sequence is passed through
  333. // literally, matching decode_uri_component / decode_path_component.
  334. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  335. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  336. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  337. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  338. // Well-formed escapes still decode.
  339. EXPECT_EQ("-", decode_query_component("%2D", false));
  340. EXPECT_EQ("A", decode_query_component("%41", false));
  341. }
  342. TEST(SanitizeFilenameTest, VariousPatterns) {
  343. // Path traversal
  344. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  346. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  347. // Normal and edge cases
  348. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  349. EXPECT_EQ("filename.txt",
  350. httplib::sanitize_filename("/path/to/filename.txt"));
  351. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  352. EXPECT_EQ("", httplib::sanitize_filename(".."));
  353. EXPECT_EQ("", httplib::sanitize_filename(""));
  354. // Null bytes stripped
  355. EXPECT_EQ("safe.txt",
  356. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  357. // Whitespace-only rejected
  358. EXPECT_EQ("", httplib::sanitize_filename(" "));
  359. }
  360. // Forward declaration (see the base64_encode note below): split builds move the
  361. // definition into httplib.cc, so re-declaring it here lets the test link.
  362. namespace httplib {
  363. namespace detail {
  364. bool is_chunked_transfer_encoding(const Headers &headers);
  365. } // namespace detail
  366. } // namespace httplib
  367. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  368. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  369. auto make = [](std::initializer_list<const char *> lines) {
  370. Headers h;
  371. for (auto te : lines) {
  372. if (te) { h.emplace("Transfer-Encoding", te); }
  373. }
  374. return h;
  375. };
  376. // Sole coding, matched case-insensitively.
  377. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  378. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  379. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  380. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  381. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  382. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  383. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  384. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  385. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  386. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  387. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  388. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  389. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  390. // portable, so any line naming chunked is treated as chunked (fail safe).
  391. // The result must not depend on the order the lines were added.
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  395. }
  396. // Forward declaration: in split builds split.py strips `inline` and moves the
  397. // definition into httplib.cc, so detail::base64_encode is not visible from the
  398. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  399. // in both header-only and split builds.
  400. namespace httplib {
  401. namespace detail {
  402. std::string base64_encode(const std::string &in);
  403. } // namespace detail
  404. } // namespace httplib
  405. TEST(Base64EncodeTest, KnownAnswers) {
  406. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  407. // where the accumulator's top bit is already set before the next shift.
  408. EXPECT_EQ("", detail::base64_encode(""));
  409. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  410. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  411. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  412. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  413. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  414. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  415. // High bytes keep the top bit set across several rounds.
  416. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  417. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  418. }
  419. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  420. string unescapedCharacters = "-_.!~*'()";
  421. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  422. }
  423. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  424. string reservedCharacters = ";,/?:@&=+$";
  425. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  426. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  427. }
  428. TEST(ClientQueryOrder, PreserveOrder) {
  429. // This test reproduces Issue #2259: client may reorder query parameters
  430. // when sending a GET request. The expected behavior is that the client
  431. // preserves the original query string order when the caller supplied it
  432. // as part of the path.
  433. Server svr;
  434. svr.Get("/", [&](const Request &req, Response &res) {
  435. // Echo back the raw target so the test can assert ordering
  436. res.set_content(req.target, "text/plain");
  437. });
  438. std::thread t{[&] { svr.listen(HOST, PORT); }};
  439. auto se = detail::scope_exit([&] {
  440. svr.stop();
  441. t.join();
  442. ASSERT_FALSE(svr.is_running());
  443. });
  444. svr.wait_until_ready();
  445. Client cli(HOST, PORT);
  446. ASSERT_TRUE(cli.is_valid());
  447. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  448. auto res = cli.Get(original);
  449. ASSERT_TRUE(res);
  450. // Expect the echoed target to exactly match the original path (order
  451. // preserved)
  452. EXPECT_EQ(res->body, original);
  453. }
  454. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  455. string chineseCharacters = U8("中国語");
  456. string russianCharacters = U8("дом");
  457. string brazilianCharacters = U8("óculos");
  458. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  459. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  460. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  461. "%D0%B4%D0%BE%D0%BC");
  462. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  463. }
  464. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  465. string unescapedCharacters = "-_.!~*'()";
  466. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  467. }
  468. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  469. string reservedCharacters = ";,/?:@&=+$";
  470. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  471. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  472. }
  473. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  474. string chineseCharacters = U8("中国語");
  475. string russianCharacters = U8("дом");
  476. string brazilianCharacters = U8("óculos");
  477. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  478. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  479. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  480. "%D0%B4%D0%BE%D0%BC");
  481. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  482. }
  483. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  484. // Issue #2082 use case: encoding path component with ampersand
  485. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  486. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  487. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  488. }
  489. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  490. string unescapedCharacters = "-_.!~*'()";
  491. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  492. }
  493. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  494. string reservedCharacters = ";,/?:@&=+$#";
  495. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  496. }
  497. TEST(EncodeUriTest, TestUTF8Characters) {
  498. string chineseCharacters = U8("中国語");
  499. string russianCharacters = U8("дом");
  500. string brazilianCharacters = U8("óculos");
  501. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  502. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  503. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriTest, TestCompleteUri) {
  507. string uri =
  508. "https://example.com/path/to/resource?query=value&param=test#fragment";
  509. EXPECT_EQ(
  510. httplib::encode_uri(uri),
  511. "https://example.com/path/to/resource?query=value&param=test#fragment");
  512. }
  513. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  514. string uri =
  515. "https://example.com/path with spaces/file name.html?q=hello world";
  516. EXPECT_EQ(httplib::encode_uri(uri),
  517. "https://example.com/path%20with%20spaces/"
  518. "file%20name.html?q=hello%20world");
  519. }
  520. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  521. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  522. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  523. }
  524. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  525. string unescapedCharacters = "-_.!~*'()";
  526. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  527. }
  528. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  529. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  530. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  531. string encodedBrazilian = "%C3%B3culos";
  532. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  533. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  534. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  535. }
  536. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  537. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  538. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  539. "Piri Tommy Villiers - on & on");
  540. }
  541. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  542. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  543. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  544. }
  545. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  546. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  547. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  548. }
  549. TEST(DecodeUriTest, TestUTF8Characters) {
  550. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  551. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  552. string encodedBrazilian = "%C3%B3culos";
  553. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  554. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  555. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  556. }
  557. TEST(DecodeUriTest, TestCompleteUri) {
  558. string encodedUri = "https://example.com/path%20with%20spaces/"
  559. "file%20name.html?q=hello%20world";
  560. EXPECT_EQ(
  561. httplib::decode_uri(encodedUri),
  562. "https://example.com/path with spaces/file name.html?q=hello world");
  563. }
  564. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  565. string original =
  566. "https://example.com/path with spaces/file name.html?q=hello world";
  567. string encoded = httplib::encode_uri(original);
  568. string decoded = httplib::decode_uri(encoded);
  569. EXPECT_EQ(decoded, original);
  570. }
  571. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  572. string original = "Piri Tommy Villiers - on & on";
  573. string encoded = httplib::encode_uri_component(original);
  574. string decoded = httplib::decode_uri_component(encoded);
  575. EXPECT_EQ(decoded, original);
  576. }
  577. TEST(TrimTests, TrimStringTests) {
  578. EXPECT_EQ("abc", detail::trim_copy("abc"));
  579. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  580. EXPECT_TRUE(detail::trim_copy("").empty());
  581. }
  582. TEST(AsciiTest, LocaleIndependentClassification) {
  583. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  584. // which consult the global C locale: std::isalnum(0xC5) can return true
  585. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  586. // helpers must classify every byte by the ASCII grammar alone.
  587. for (int i = 0; i < 256; i++) {
  588. auto c = static_cast<char>(i);
  589. auto is_digit = i >= '0' && i <= '9';
  590. auto is_upper = i >= 'A' && i <= 'Z';
  591. auto is_lower = i >= 'a' && i <= 'z';
  592. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  593. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  594. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  595. << "byte " << i;
  596. }
  597. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  598. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  599. // Non-ASCII bytes must be percent-encoded, never passed through as
  600. // alphanumeric.
  601. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  602. }
  603. TEST(FromCharsTest, Double) {
  604. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  605. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  606. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  607. auto parse = [](const std::string &s, double &v) {
  608. return detail::from_chars(s.data(), s.data() + s.size(), v);
  609. };
  610. double v = -1.0;
  611. // Representative quality values.
  612. EXPECT_EQ(parse("0", v).ec, std::errc{});
  613. EXPECT_DOUBLE_EQ(v, 0.0);
  614. EXPECT_EQ(parse("1", v).ec, std::errc{});
  615. EXPECT_DOUBLE_EQ(v, 1.0);
  616. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  617. EXPECT_DOUBLE_EQ(v, 0.8);
  618. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.001);
  620. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 1.0);
  622. // A missing integer or fractional part is tolerated.
  623. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  624. EXPECT_DOUBLE_EQ(v, 0.5);
  625. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  626. EXPECT_DOUBLE_EQ(v, 5.0);
  627. // Values outside [0, 1] still parse; the caller range-checks them.
  628. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  629. EXPECT_DOUBLE_EQ(v, 123.456);
  630. // Stops at the first byte that is not part of the number and reports where.
  631. std::string trailing = "0.9, text/html";
  632. auto r = parse(trailing, v);
  633. EXPECT_EQ(r.ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 0.9);
  635. EXPECT_EQ(*r.ptr, ',');
  636. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  637. // outright, and an 'e'/'E' simply ends the number.
  638. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  639. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  640. std::string exp_input = "1.5e3";
  641. r = parse(exp_input, v);
  642. EXPECT_EQ(r.ec, std::errc{});
  643. EXPECT_DOUBLE_EQ(v, 1.5);
  644. EXPECT_EQ(*r.ptr, 'e');
  645. // Invalid inputs.
  646. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  647. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  648. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  649. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  650. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  651. // Pathological but well-formed inputs must stay bounded (no overflow, no
  652. // out-of-bounds table access) and stay within [0, 1] for the caller.
  653. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  654. std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.0);
  656. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  657. std::errc{});
  658. EXPECT_GE(v, 0.0);
  659. EXPECT_LE(v, 1.0);
  660. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  661. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  662. }
  663. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  664. // Simple case without quality values
  665. std::vector<std::string> result1;
  666. EXPECT_TRUE(detail::parse_accept_header(
  667. "text/html,application/json,text/plain", result1));
  668. EXPECT_EQ(result1.size(), 3U);
  669. EXPECT_EQ(result1[0], "text/html");
  670. EXPECT_EQ(result1[1], "application/json");
  671. EXPECT_EQ(result1[2], "text/plain");
  672. // With quality values
  673. std::vector<std::string> result2;
  674. EXPECT_TRUE(detail::parse_accept_header(
  675. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  676. EXPECT_EQ(result2.size(), 3U);
  677. EXPECT_EQ(result2[0], "application/json"); // highest q value
  678. EXPECT_EQ(result2[1], "text/html");
  679. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  680. }
  681. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  682. // Mixed with and without quality values
  683. std::vector<std::string> result;
  684. EXPECT_TRUE(detail::parse_accept_header(
  685. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  686. EXPECT_EQ(result.size(), 3U);
  687. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  688. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  689. EXPECT_EQ(result[2], "application/json"); // q=0.5
  690. }
  691. TEST(ParseAcceptHeaderTest, EdgeCases) {
  692. // Empty header
  693. std::vector<std::string> empty_result;
  694. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  695. EXPECT_TRUE(empty_result.empty());
  696. // Single type
  697. std::vector<std::string> single_result;
  698. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  699. EXPECT_EQ(single_result.size(), 1U);
  700. EXPECT_EQ(single_result[0], "application/json");
  701. // Wildcard types
  702. std::vector<std::string> wildcard_result;
  703. EXPECT_TRUE(detail::parse_accept_header(
  704. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  705. EXPECT_EQ(wildcard_result.size(), 3U);
  706. EXPECT_EQ(wildcard_result[0], "application/json");
  707. EXPECT_EQ(wildcard_result[1], "text/*");
  708. EXPECT_EQ(wildcard_result[2], "*/*");
  709. }
  710. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  711. // Common browser Accept header
  712. std::vector<std::string> browser_result;
  713. EXPECT_TRUE(
  714. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  715. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  716. browser_result));
  717. EXPECT_EQ(browser_result.size(), 6U);
  718. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  719. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  720. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  721. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  722. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  723. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  724. // API client header
  725. std::vector<std::string> api_result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  728. api_result));
  729. EXPECT_EQ(api_result.size(), 3U);
  730. EXPECT_EQ(api_result[0], "application/json");
  731. EXPECT_EQ(api_result[1], "application/xml");
  732. EXPECT_EQ(api_result[2], "text/plain");
  733. }
  734. TEST(ParseAcceptHeaderTest, SpecialCases) {
  735. // Quality value with 3 decimal places
  736. std::vector<std::string> decimal_result;
  737. EXPECT_TRUE(detail::parse_accept_header(
  738. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  739. EXPECT_EQ(decimal_result.size(), 2U);
  740. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  741. EXPECT_EQ(decimal_result[1], "text/html");
  742. // Zero quality (should still be included but with lowest priority)
  743. std::vector<std::string> zero_q_result;
  744. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  745. zero_q_result));
  746. EXPECT_EQ(zero_q_result.size(), 2U);
  747. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  748. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  749. // No spaces around commas
  750. std::vector<std::string> no_space_result;
  751. EXPECT_TRUE(detail::parse_accept_header(
  752. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  753. no_space_result));
  754. EXPECT_EQ(no_space_result.size(), 3U);
  755. EXPECT_EQ(no_space_result[0], "text/html");
  756. EXPECT_EQ(no_space_result[1], "application/json");
  757. EXPECT_EQ(no_space_result[2], "text/plain");
  758. }
  759. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  760. // Quality values always use '.' as the decimal separator, so parsing must
  761. // not depend on the process locale. An embedding application may have
  762. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  763. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  764. std::string saved = cur ? cur : "C";
  765. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  766. "fr_FR.UTF-8"};
  767. bool switched = false;
  768. for (const auto loc : comma_locales) {
  769. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  770. std::localeconv()->decimal_point[0] == ',') {
  771. switched = true;
  772. break;
  773. }
  774. }
  775. if (!switched) {
  776. std::setlocale(LC_NUMERIC, saved.c_str());
  777. GTEST_SKIP() << "no comma-decimal locale available on this host";
  778. }
  779. // The higher-weighted type appears later in the list, so a correct parse
  780. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  781. // sensitive parse reads both weights as 0 and leaves the original order.
  782. std::vector<std::string> result;
  783. EXPECT_TRUE(detail::parse_accept_header(
  784. "application/json;q=0.1,text/html;q=0.9", result));
  785. ASSERT_EQ(result.size(), 2U);
  786. EXPECT_EQ(result[0], "text/html");
  787. EXPECT_EQ(result[1], "application/json");
  788. std::setlocale(LC_NUMERIC, saved.c_str());
  789. }
  790. TEST(ParseAcceptHeaderTest, InvalidCases) {
  791. std::vector<std::string> result;
  792. // Invalid quality value (> 1.0)
  793. EXPECT_FALSE(
  794. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  795. // Invalid quality value (< 0.0)
  796. EXPECT_FALSE(
  797. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  798. // Invalid quality value (not a number)
  799. EXPECT_FALSE(detail::parse_accept_header(
  800. "text/html;q=invalid,application/json", result));
  801. // Empty quality value
  802. EXPECT_FALSE(
  803. detail::parse_accept_header("text/html;q=,application/json", result));
  804. // Invalid media type format (no slash and not wildcard)
  805. EXPECT_FALSE(
  806. detail::parse_accept_header("invalidtype,application/json", result));
  807. // Empty media type
  808. result.clear();
  809. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  810. // Only commas
  811. result.clear();
  812. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  813. // Valid cases should still work
  814. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  815. EXPECT_EQ(result.size(), 1U);
  816. EXPECT_EQ(result[0], "*/*");
  817. EXPECT_TRUE(detail::parse_accept_header("*", result));
  818. EXPECT_EQ(result.size(), 1U);
  819. EXPECT_EQ(result[0], "*");
  820. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  821. EXPECT_EQ(result.size(), 1U);
  822. EXPECT_EQ(result[0], "text/*");
  823. }
  824. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  825. Server svr;
  826. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  827. EXPECT_EQ(req.accept_content_types.size(), 3U);
  828. EXPECT_EQ(req.accept_content_types[0], "application/json");
  829. EXPECT_EQ(req.accept_content_types[1], "text/html");
  830. EXPECT_EQ(req.accept_content_types[2], "*/*");
  831. res.set_content("ok", "text/plain");
  832. });
  833. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  834. EXPECT_TRUE(false);
  835. res.set_content("bad request", "text/plain");
  836. });
  837. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  838. auto se = detail::scope_exit([&] {
  839. svr.stop();
  840. listen_thread.join();
  841. ASSERT_FALSE(svr.is_running());
  842. });
  843. svr.wait_until_ready();
  844. Client cli("localhost", PORT);
  845. {
  846. auto res = cli.Get(
  847. "/accept_ok",
  848. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  849. ASSERT_TRUE(res);
  850. EXPECT_EQ(StatusCode::OK_200, res->status);
  851. }
  852. {
  853. auto res = cli.Get("/accept_bad_request",
  854. Headers{{"Accept", "text/html;q=abc,application/json"}});
  855. ASSERT_TRUE(res);
  856. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  857. }
  858. }
  859. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  860. Server svr;
  861. svr.Get("/", [](const Request & /*req*/, Response &res) {
  862. res.set_content("ok", "text/plain");
  863. });
  864. std::atomic<int> start_count{0};
  865. std::atomic<bool> running_when_called{false};
  866. svr.set_start_handler([&]() {
  867. running_when_called = svr.is_running();
  868. start_count++;
  869. });
  870. auto port = svr.bind_to_any_port(HOST);
  871. std::thread t([&]() { svr.listen_after_bind(); });
  872. auto se = detail::scope_exit([&] {
  873. svr.stop();
  874. t.join();
  875. ASSERT_FALSE(svr.is_running());
  876. });
  877. svr.wait_until_ready();
  878. // A successful request proves the accept loop is running, which the start
  879. // handler precedes; so by now the handler must have run exactly once.
  880. Client cli(HOST, port);
  881. cli.set_connection_timeout(std::chrono::seconds(5));
  882. auto res = cli.Get("/");
  883. ASSERT_TRUE(res);
  884. EXPECT_EQ(StatusCode::OK_200, res->status);
  885. EXPECT_EQ(1, start_count.load());
  886. EXPECT_TRUE(running_when_called.load());
  887. }
  888. TEST(DivideTest, DivideStringTests) {
  889. auto divide = [](const std::string &str, char d) {
  890. std::string lhs;
  891. std::string rhs;
  892. detail::divide(str, d,
  893. [&](const char *lhs_data, std::size_t lhs_size,
  894. const char *rhs_data, std::size_t rhs_size) {
  895. lhs.assign(lhs_data, lhs_size);
  896. rhs.assign(rhs_data, rhs_size);
  897. });
  898. return std::make_pair(std::move(lhs), std::move(rhs));
  899. };
  900. {
  901. const auto res = divide("", '=');
  902. EXPECT_EQ(res.first, "");
  903. EXPECT_EQ(res.second, "");
  904. }
  905. {
  906. const auto res = divide("=", '=');
  907. EXPECT_EQ(res.first, "");
  908. EXPECT_EQ(res.second, "");
  909. }
  910. {
  911. const auto res = divide(" ", '=');
  912. EXPECT_EQ(res.first, " ");
  913. EXPECT_EQ(res.second, "");
  914. }
  915. {
  916. const auto res = divide("a", '=');
  917. EXPECT_EQ(res.first, "a");
  918. EXPECT_EQ(res.second, "");
  919. }
  920. {
  921. const auto res = divide("a=", '=');
  922. EXPECT_EQ(res.first, "a");
  923. EXPECT_EQ(res.second, "");
  924. }
  925. {
  926. const auto res = divide("=b", '=');
  927. EXPECT_EQ(res.first, "");
  928. EXPECT_EQ(res.second, "b");
  929. }
  930. {
  931. const auto res = divide("a=b", '=');
  932. EXPECT_EQ(res.first, "a");
  933. EXPECT_EQ(res.second, "b");
  934. }
  935. {
  936. const auto res = divide("a=b=", '=');
  937. EXPECT_EQ(res.first, "a");
  938. EXPECT_EQ(res.second, "b=");
  939. }
  940. {
  941. const auto res = divide("a=b=c", '=');
  942. EXPECT_EQ(res.first, "a");
  943. EXPECT_EQ(res.second, "b=c");
  944. }
  945. }
  946. TEST(SplitTest, ParseQueryString) {
  947. string s = "key1=val1&key2=val2&key3=val3";
  948. Params dic;
  949. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  950. [&](const char *b, const char *e) {
  951. string key, val;
  952. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  953. if (key.empty()) {
  954. key.assign(b2, e2);
  955. } else {
  956. val.assign(b2, e2);
  957. }
  958. });
  959. dic.emplace(key, val);
  960. });
  961. EXPECT_EQ("val1", dic.find("key1")->second);
  962. EXPECT_EQ("val2", dic.find("key2")->second);
  963. EXPECT_EQ("val3", dic.find("key3")->second);
  964. }
  965. TEST(SplitTest, ParseInvalidQueryTests) {
  966. {
  967. string s = " ";
  968. Params dict;
  969. detail::parse_query_text(s, dict);
  970. EXPECT_TRUE(dict.empty());
  971. }
  972. {
  973. string s = " = =";
  974. Params dict;
  975. detail::parse_query_text(s, dict);
  976. EXPECT_TRUE(dict.empty());
  977. }
  978. }
  979. TEST(ParseQueryTest, ParseQueryString) {
  980. {
  981. std::string s = "key1=val1&key2=val2&key3=val3";
  982. Params dic;
  983. detail::parse_query_text(s, dic);
  984. EXPECT_EQ("val1", dic.find("key1")->second);
  985. EXPECT_EQ("val2", dic.find("key2")->second);
  986. EXPECT_EQ("val3", dic.find("key3")->second);
  987. }
  988. {
  989. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  990. Params dic;
  991. detail::parse_query_text(s, dic);
  992. EXPECT_EQ("", dic.find("key1")->second);
  993. EXPECT_EQ("val1", dic.find("key2")->second);
  994. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  995. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  996. }
  997. }
  998. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  999. Params dic;
  1000. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1001. dic.emplace("key1", "val1");
  1002. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1003. dic.emplace("key2", "val2");
  1004. dic.emplace("key3", "val3");
  1005. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1006. }
  1007. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1008. string content_type = "multipart/form-data; boundary=something";
  1009. string boundary;
  1010. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1011. EXPECT_TRUE(ret);
  1012. EXPECT_EQ(boundary, "something");
  1013. }
  1014. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1015. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1016. string boundary;
  1017. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1018. EXPECT_TRUE(ret);
  1019. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1020. }
  1021. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1022. string content_type =
  1023. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1024. string boundary;
  1025. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1026. EXPECT_TRUE(ret);
  1027. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1028. }
  1029. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1030. string content_type =
  1031. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1032. string boundary;
  1033. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1034. EXPECT_TRUE(ret);
  1035. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1036. }
  1037. TEST(GetHeaderValueTest, DefaultValue) {
  1038. Headers headers = {{"Dummy", "Dummy"}};
  1039. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1040. EXPECT_STREQ("text/plain", val);
  1041. }
  1042. TEST(GetHeaderValueTest, DefaultValueInt) {
  1043. Headers headers = {{"Dummy", "Dummy"}};
  1044. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1045. EXPECT_EQ(100ull, val);
  1046. }
  1047. TEST(GetHeaderValueTest, RegularValue) {
  1048. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1049. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1050. EXPECT_STREQ("text/html", val);
  1051. }
  1052. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1053. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1054. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1055. EXPECT_STREQ("text/html", val);
  1056. }
  1057. TEST(GetHeaderValueTest, SetContent) {
  1058. Response res;
  1059. res.set_content("html", "text/html");
  1060. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1061. res.set_content("text", "text/plain");
  1062. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1063. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1064. }
  1065. TEST(GetHeaderValueTest, RegularValueInt) {
  1066. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1067. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1068. EXPECT_EQ(100ull, val);
  1069. }
  1070. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1071. Headers headers = {{"Content-Length", "x"}};
  1072. auto is_invalid_value = false;
  1073. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1074. is_invalid_value);
  1075. EXPECT_EQ(0ull, val);
  1076. EXPECT_TRUE(is_invalid_value);
  1077. }
  1078. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1079. // An all-digit value that overflows size_t must be reported as invalid, not
  1080. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1081. // a large length to a small one on 32-bit builds, leaving the framing length
  1082. // wrong while is_invalid_value stayed false.
  1083. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1084. auto is_invalid_value = false;
  1085. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1086. is_invalid_value);
  1087. EXPECT_TRUE(is_invalid_value);
  1088. // A well-formed length is unaffected.
  1089. Headers ok = {{"Content-Length", "1234"}};
  1090. is_invalid_value = false;
  1091. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1092. is_invalid_value);
  1093. EXPECT_EQ(1234ull, val);
  1094. EXPECT_FALSE(is_invalid_value);
  1095. }
  1096. TEST(GetHeaderValueTest, Range) {
  1097. {
  1098. Headers headers = {make_range_header({{1, -1}})};
  1099. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1100. EXPECT_STREQ("bytes=1-", val);
  1101. }
  1102. {
  1103. Headers headers = {make_range_header({{-1, 1}})};
  1104. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1105. EXPECT_STREQ("bytes=-1", val);
  1106. }
  1107. {
  1108. Headers headers = {make_range_header({{1, 10}})};
  1109. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1110. EXPECT_STREQ("bytes=1-10", val);
  1111. }
  1112. {
  1113. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1114. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1115. EXPECT_STREQ("bytes=1-10, 100-", val);
  1116. }
  1117. {
  1118. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1119. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1120. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1121. }
  1122. {
  1123. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1124. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1125. EXPECT_STREQ("bytes=0-0, -1", val);
  1126. }
  1127. }
  1128. TEST(ParseHeaderValueTest, Range) {
  1129. {
  1130. Ranges ranges;
  1131. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1132. EXPECT_TRUE(ret);
  1133. EXPECT_EQ(1u, ranges.size());
  1134. EXPECT_EQ(1u, ranges[0].first);
  1135. EXPECT_EQ(-1, ranges[0].second);
  1136. }
  1137. {
  1138. Ranges ranges;
  1139. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1140. EXPECT_TRUE(ret);
  1141. EXPECT_EQ(1u, ranges.size());
  1142. EXPECT_EQ(-1, ranges[0].first);
  1143. EXPECT_EQ(1u, ranges[0].second);
  1144. }
  1145. {
  1146. Ranges ranges;
  1147. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1148. EXPECT_TRUE(ret);
  1149. EXPECT_EQ(1u, ranges.size());
  1150. EXPECT_EQ(1u, ranges[0].first);
  1151. EXPECT_EQ(10u, ranges[0].second);
  1152. }
  1153. {
  1154. Ranges ranges;
  1155. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1156. EXPECT_FALSE(ret);
  1157. }
  1158. {
  1159. Ranges ranges;
  1160. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1161. EXPECT_TRUE(ret);
  1162. EXPECT_EQ(2u, ranges.size());
  1163. EXPECT_EQ(1u, ranges[0].first);
  1164. EXPECT_EQ(10u, ranges[0].second);
  1165. EXPECT_EQ(100u, ranges[1].first);
  1166. EXPECT_EQ(-1, ranges[1].second);
  1167. }
  1168. {
  1169. Ranges ranges;
  1170. auto ret =
  1171. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1172. EXPECT_TRUE(ret);
  1173. EXPECT_EQ(3u, ranges.size());
  1174. EXPECT_EQ(1u, ranges[0].first);
  1175. EXPECT_EQ(10u, ranges[0].second);
  1176. EXPECT_EQ(100u, ranges[1].first);
  1177. EXPECT_EQ(200u, ranges[1].second);
  1178. EXPECT_EQ(300u, ranges[2].first);
  1179. EXPECT_EQ(400u, ranges[2].second);
  1180. }
  1181. {
  1182. Ranges ranges;
  1183. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1184. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1185. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1186. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1187. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1188. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1189. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1190. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1191. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1192. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1193. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1194. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1195. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1196. EXPECT_TRUE(ranges.empty());
  1197. }
  1198. }
  1199. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1200. Request req;
  1201. req.set_header("Accept-Encoding", "gzip");
  1202. Response res;
  1203. res.set_header("Content-Type", "text/plain");
  1204. auto ret = detail::encoding_type(req, res);
  1205. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1206. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1207. #else
  1208. EXPECT_TRUE(ret == detail::EncodingType::None);
  1209. #endif
  1210. }
  1211. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1212. Request req;
  1213. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1214. Response res;
  1215. res.set_header("Content-Type", "text/plain");
  1216. auto ret = detail::encoding_type(req, res);
  1217. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1218. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1219. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1220. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1221. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1222. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1223. #else
  1224. EXPECT_TRUE(ret == detail::EncodingType::None);
  1225. #endif
  1226. }
  1227. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1228. Request req;
  1229. req.set_header("Accept-Encoding",
  1230. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1231. Response res;
  1232. res.set_header("Content-Type", "text/plain");
  1233. auto ret = detail::encoding_type(req, res);
  1234. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1235. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1236. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1237. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1238. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1239. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1240. #else
  1241. EXPECT_TRUE(ret == detail::EncodingType::None);
  1242. #endif
  1243. }
  1244. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1245. // All supported encodings rejected with q=0 should return None
  1246. Request req;
  1247. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1248. Response res;
  1249. res.set_header("Content-Type", "text/plain");
  1250. auto ret = detail::encoding_type(req, res);
  1251. EXPECT_TRUE(ret == detail::EncodingType::None);
  1252. }
  1253. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1254. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1255. Request req;
  1256. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1257. Response res;
  1258. res.set_header("Content-Type", "text/plain");
  1259. auto ret = detail::encoding_type(req, res);
  1260. EXPECT_TRUE(ret == detail::EncodingType::None);
  1261. }
  1262. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1263. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1264. Request req;
  1265. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1266. Response res;
  1267. res.set_header("Content-Type", "text/plain");
  1268. auto ret = detail::encoding_type(req, res);
  1269. EXPECT_TRUE(ret == detail::EncodingType::None);
  1270. }
  1271. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1272. // RFC 7231: Accept-Encoding values are case-insensitive
  1273. Request req;
  1274. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1275. Response res;
  1276. res.set_header("Content-Type", "text/plain");
  1277. auto ret = detail::encoding_type(req, res);
  1278. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1279. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1280. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1281. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1282. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1283. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1284. #else
  1285. EXPECT_TRUE(ret == detail::EncodingType::None);
  1286. #endif
  1287. }
  1288. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1289. // q value should determine priority, not hardcoded order
  1290. Request req;
  1291. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1292. Response res;
  1293. res.set_header("Content-Type", "text/plain");
  1294. auto ret = detail::encoding_type(req, res);
  1295. // gzip has highest q=1.0, so it should be selected even though
  1296. // br and zstd are also supported
  1297. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1298. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1299. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1300. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1301. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1302. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1303. #else
  1304. EXPECT_TRUE(ret == detail::EncodingType::None);
  1305. #endif
  1306. }
  1307. TEST(BufferStreamTest, read) {
  1308. detail::BufferStream strm1;
  1309. Stream &strm = strm1;
  1310. EXPECT_EQ(5, strm.write("hello"));
  1311. char buf[512];
  1312. EXPECT_EQ(2, strm.read(buf, 2));
  1313. EXPECT_EQ('h', buf[0]);
  1314. EXPECT_EQ('e', buf[1]);
  1315. EXPECT_EQ(2, strm.read(buf, 2));
  1316. EXPECT_EQ('l', buf[0]);
  1317. EXPECT_EQ('l', buf[1]);
  1318. EXPECT_EQ(1, strm.read(buf, 1));
  1319. EXPECT_EQ('o', buf[0]);
  1320. EXPECT_EQ(0, strm.read(buf, 1));
  1321. }
  1322. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1323. auto host = "www.httpwatch.com";
  1324. auto ip = hosted_at(host);
  1325. EXPECT_EQ("23.96.13.243", ip);
  1326. std::vector<std::string> addrs;
  1327. hosted_at(host, addrs);
  1328. EXPECT_EQ(1u, addrs.size());
  1329. }
  1330. #if 0 // It depends on each test environment...
  1331. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1332. auto host = "www.youtube.com";
  1333. std::vector<std::string> addrs;
  1334. hosted_at(host, addrs);
  1335. EXPECT_EQ(20u, addrs.size());
  1336. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1337. EXPECT_TRUE(it != addrs.end());
  1338. }
  1339. #endif
  1340. class ChunkedEncodingTest : public ::testing::Test {
  1341. protected:
  1342. ChunkedEncodingTest()
  1343. : cli_(HOST, PORT)
  1344. #ifdef CPPHTTPLIB_SSL_ENABLED
  1345. ,
  1346. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1347. #endif
  1348. {
  1349. cli_.set_connection_timeout(2);
  1350. #ifdef CPPHTTPLIB_SSL_ENABLED
  1351. cli_.enable_server_certificate_verification(false);
  1352. #endif
  1353. }
  1354. virtual void SetUp() {
  1355. read_file("./image.jpg", image_data_);
  1356. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1357. res.set_content("Hello World!", "text/plain");
  1358. });
  1359. svr_.Get(
  1360. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1361. res.set_chunked_content_provider(
  1362. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1363. size_t remaining = image_data_.size() - offset;
  1364. if (remaining == 0) {
  1365. sink.done();
  1366. } else {
  1367. constexpr size_t CHUNK_SIZE = 1024;
  1368. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1369. sink.write(&image_data_[offset], send_size);
  1370. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1371. }
  1372. return true;
  1373. });
  1374. });
  1375. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1376. svr_.wait_until_ready();
  1377. }
  1378. virtual void TearDown() {
  1379. svr_.stop();
  1380. if (!request_threads_.empty()) {
  1381. std::this_thread::sleep_for(std::chrono::seconds(1));
  1382. for (auto &t : request_threads_) {
  1383. t.join();
  1384. }
  1385. }
  1386. t_.join();
  1387. }
  1388. #ifdef CPPHTTPLIB_SSL_ENABLED
  1389. SSLClient cli_;
  1390. SSLServer svr_;
  1391. #else
  1392. Client cli_;
  1393. Server svr_;
  1394. #endif
  1395. thread t_;
  1396. std::vector<thread> request_threads_;
  1397. std::string image_data_;
  1398. };
  1399. TEST_F(ChunkedEncodingTest, NormalGet) {
  1400. auto res = cli_.Get("/chunked");
  1401. ASSERT_TRUE(res);
  1402. std::string out;
  1403. read_file("./image.jpg", out);
  1404. EXPECT_EQ(StatusCode::OK_200, res->status);
  1405. EXPECT_EQ(out, res->body);
  1406. }
  1407. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1408. std::string body;
  1409. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1410. body.append(data, data_length);
  1411. return true;
  1412. });
  1413. ASSERT_TRUE(res);
  1414. std::string out;
  1415. read_file("./image.jpg", out);
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. EXPECT_EQ(out, body);
  1418. }
  1419. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1420. std::string body;
  1421. auto res = cli_.Get(
  1422. "/chunked",
  1423. [&](const Response &response) {
  1424. EXPECT_EQ(StatusCode::OK_200, response.status);
  1425. return true;
  1426. },
  1427. [&](const char *data, size_t data_length) {
  1428. body.append(data, data_length);
  1429. return true;
  1430. });
  1431. ASSERT_TRUE(res);
  1432. std::string out;
  1433. read_file("./image.jpg", out);
  1434. EXPECT_EQ(StatusCode::OK_200, res->status);
  1435. EXPECT_EQ(out, body);
  1436. }
  1437. TEST(RangeTest, FromHTTPBin_Online) {
  1438. auto host = "httpbingo.org";
  1439. auto path = std::string{"/range/32"};
  1440. #ifdef CPPHTTPLIB_SSL_ENABLED
  1441. auto port = 443;
  1442. SSLClient cli(host, port);
  1443. #else
  1444. auto port = 80;
  1445. Client cli(host, port);
  1446. #endif
  1447. cli.set_connection_timeout(5);
  1448. {
  1449. auto res = cli.Get(path);
  1450. ASSERT_TRUE(res);
  1451. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1452. EXPECT_EQ(StatusCode::OK_200, res->status);
  1453. }
  1454. {
  1455. Headers headers = {make_range_header({{1, -1}})};
  1456. auto res = cli.Get(path, headers);
  1457. ASSERT_TRUE(res);
  1458. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1460. }
  1461. {
  1462. Headers headers = {make_range_header({{1, 10}})};
  1463. auto res = cli.Get(path, headers);
  1464. ASSERT_TRUE(res);
  1465. EXPECT_EQ("bcdefghijk", res->body);
  1466. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1467. }
  1468. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1469. // entire resource, while the original httpbin returned 200. Both are
  1470. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1471. {
  1472. Headers headers = {make_range_header({{0, 31}})};
  1473. auto res = cli.Get(path, headers);
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1477. res->status == StatusCode::PartialContent_206);
  1478. }
  1479. {
  1480. Headers headers = {make_range_header({{0, -1}})};
  1481. auto res = cli.Get(path, headers);
  1482. ASSERT_TRUE(res);
  1483. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1484. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1485. res->status == StatusCode::PartialContent_206);
  1486. }
  1487. // go-httpbin returns 206 with clamped range for over-range requests,
  1488. // while the original httpbin returned 416. Both behaviors are observed
  1489. // in real servers, so we only verify the request succeeds.
  1490. {
  1491. Headers headers = {make_range_header({{0, 32}})};
  1492. auto res = cli.Get(path, headers);
  1493. ASSERT_TRUE(res);
  1494. }
  1495. }
  1496. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1497. auto host = "unresolvableaddress.local";
  1498. auto path = std::string{"/"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(1);
  1507. {
  1508. auto res = cli.Get(path);
  1509. ASSERT_FALSE(res);
  1510. }
  1511. std::this_thread::sleep_for(std::chrono::seconds(8));
  1512. }
  1513. #if defined(__linux__) && defined(__GLIBC__) && \
  1514. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1515. // Forward declaration: in split builds split.py strips `inline` and moves the
  1516. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1517. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1518. // against the symbol in both header-only and split builds.
  1519. namespace httplib {
  1520. namespace detail {
  1521. int getaddrinfo_with_timeout(const char *node, const char *service,
  1522. const struct addrinfo *hints,
  1523. struct addrinfo **res, time_t timeout_sec);
  1524. } // namespace detail
  1525. } // namespace httplib
  1526. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1527. //
  1528. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1529. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1530. // gai_suspend() call hits the connection timeout the function calls
  1531. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1532. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1533. // still alive and still references the now-destroyed stack frame.
  1534. //
  1535. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1536. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1537. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1538. // and runs them in a container.
  1539. namespace {
  1540. bool should_run_issue_2431_tests() {
  1541. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1542. return v && *v && std::string(v) != "0";
  1543. }
  1544. std::string unique_unresolvable_host(int n) {
  1545. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1546. // glibc still asks the configured nameserver — which is exactly the path
  1547. // we want to exercise. A unique label per call avoids the resolver cache.
  1548. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1549. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1550. std::to_string(n) + ".invalid";
  1551. }
  1552. } // namespace
  1553. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1554. if (!should_run_issue_2431_tests()) {
  1555. GTEST_SKIP()
  1556. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1557. }
  1558. for (int i = 0; i < 8; ++i) {
  1559. struct addrinfo hints;
  1560. memset(&hints, 0, sizeof(hints));
  1561. hints.ai_family = AF_UNSPEC;
  1562. hints.ai_socktype = SOCK_STREAM;
  1563. auto host = unique_unresolvable_host(i);
  1564. struct addrinfo *result = nullptr;
  1565. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1566. &result, /*timeout_sec=*/1);
  1567. if (rc == 0 && result) { freeaddrinfo(result); }
  1568. }
  1569. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1570. // stack region they still believe holds their gaicb.
  1571. std::this_thread::sleep_for(std::chrono::seconds(3));
  1572. }
  1573. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1574. if (!should_run_issue_2431_tests()) {
  1575. GTEST_SKIP()
  1576. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1577. }
  1578. std::atomic<bool> stop{false};
  1579. std::vector<std::thread> threads;
  1580. for (int t = 0; t < 8; ++t) {
  1581. threads.emplace_back([t, &stop] {
  1582. int i = 0;
  1583. while (!stop.load(std::memory_order_relaxed)) {
  1584. struct addrinfo hints;
  1585. memset(&hints, 0, sizeof(hints));
  1586. hints.ai_family = AF_UNSPEC;
  1587. hints.ai_socktype = SOCK_STREAM;
  1588. auto host = unique_unresolvable_host(t * 100000 + i++);
  1589. struct addrinfo *result = nullptr;
  1590. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1591. &result, /*timeout_sec=*/1);
  1592. if (rc == 0 && result) { freeaddrinfo(result); }
  1593. }
  1594. });
  1595. }
  1596. std::this_thread::sleep_for(std::chrono::seconds(8));
  1597. stop.store(true, std::memory_order_relaxed);
  1598. for (auto &th : threads) {
  1599. th.join();
  1600. }
  1601. std::this_thread::sleep_for(std::chrono::seconds(3));
  1602. }
  1603. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1604. if (!should_run_issue_2431_tests()) {
  1605. GTEST_SKIP()
  1606. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1607. }
  1608. std::atomic<bool> stop{false};
  1609. std::vector<std::thread> threads;
  1610. for (int t = 0; t < 8; ++t) {
  1611. threads.emplace_back([t, &stop] {
  1612. int i = 0;
  1613. while (!stop.load(std::memory_order_relaxed)) {
  1614. auto host = unique_unresolvable_host(t * 100000 + i++);
  1615. Client cli(host, 80);
  1616. cli.set_connection_timeout(1, 0);
  1617. cli.set_read_timeout(1, 0);
  1618. cli.set_write_timeout(1, 0);
  1619. (void)cli.Get("/");
  1620. }
  1621. });
  1622. }
  1623. std::this_thread::sleep_for(std::chrono::seconds(8));
  1624. stop.store(true, std::memory_order_relaxed);
  1625. for (auto &th : threads) {
  1626. th.join();
  1627. }
  1628. std::this_thread::sleep_for(std::chrono::seconds(3));
  1629. }
  1630. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1631. TEST(ConnectionErrorTest, InvalidHost) {
  1632. auto host = "-abcde.com";
  1633. #ifdef CPPHTTPLIB_SSL_ENABLED
  1634. auto port = 443;
  1635. SSLClient cli(host, port);
  1636. #else
  1637. auto port = 80;
  1638. Client cli(host, port);
  1639. #endif
  1640. cli.set_connection_timeout(std::chrono::seconds(2));
  1641. auto res = cli.Get("/");
  1642. ASSERT_TRUE(!res);
  1643. EXPECT_EQ(Error::Connection, res.error());
  1644. }
  1645. TEST(ConnectionErrorTest, InvalidHost2) {
  1646. auto host = "httpcan.org/";
  1647. #ifdef CPPHTTPLIB_SSL_ENABLED
  1648. SSLClient cli(host);
  1649. #else
  1650. Client cli(host);
  1651. #endif
  1652. cli.set_connection_timeout(std::chrono::seconds(2));
  1653. auto res = cli.Get("/");
  1654. ASSERT_TRUE(!res);
  1655. EXPECT_EQ(Error::Connection, res.error());
  1656. }
  1657. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1658. auto host = "httpcan.org/";
  1659. #ifdef CPPHTTPLIB_SSL_ENABLED
  1660. SSLClient cli(host);
  1661. #else
  1662. Client cli(host);
  1663. #endif
  1664. cli.set_connection_timeout(std::chrono::seconds(2));
  1665. auto res = cli.Get("/");
  1666. ASSERT_TRUE(!res);
  1667. stringstream s;
  1668. s << "error code: " << res.error();
  1669. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1670. }
  1671. TEST(ConnectionErrorTest, InvalidPort) {
  1672. auto host = "localhost";
  1673. auto port = 44380;
  1674. #ifdef CPPHTTPLIB_SSL_ENABLED
  1675. SSLClient cli(host, port);
  1676. #else
  1677. Client cli(host, port);
  1678. #endif
  1679. cli.set_connection_timeout(std::chrono::seconds(2));
  1680. auto res = cli.Get("/");
  1681. ASSERT_TRUE(!res);
  1682. EXPECT_TRUE(Error::Connection == res.error() ||
  1683. Error::ConnectionTimeout == res.error());
  1684. }
  1685. TEST(ConnectionErrorTest, Timeout_Online) {
  1686. auto host = "google.com";
  1687. #ifdef CPPHTTPLIB_SSL_ENABLED
  1688. auto port = 44380;
  1689. SSLClient cli(host, port);
  1690. #else
  1691. auto port = 8080;
  1692. Client cli(host, port);
  1693. #endif
  1694. cli.set_connection_timeout(std::chrono::seconds(2));
  1695. // only probe one address type so that the error reason
  1696. // correlates to the timed-out IPv4, not the unsupported
  1697. // IPv6 connection attempt
  1698. cli.set_address_family(AF_INET);
  1699. auto res = cli.Get("/");
  1700. ASSERT_TRUE(!res);
  1701. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1702. }
  1703. TEST(CancelTest, NoCancel_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(std::chrono::seconds(5));
  1714. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1715. ASSERT_TRUE(res);
  1716. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1717. EXPECT_EQ(StatusCode::OK_200, res->status);
  1718. }
  1719. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1720. // Use /bytes with a large payload so that the DownloadProgress callback
  1721. // (which only fires for Content-Length responses) is invoked before the
  1722. // entire body is received, giving cancellation a chance to fire.
  1723. auto host = "httpbingo.org";
  1724. auto path = std::string{"/bytes/524288"};
  1725. #ifdef CPPHTTPLIB_SSL_ENABLED
  1726. auto port = 443;
  1727. SSLClient cli(host, port);
  1728. #else
  1729. auto port = 80;
  1730. Client cli(host, port);
  1731. #endif
  1732. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1733. cli.set_connection_timeout(std::chrono::seconds(5));
  1734. ASSERT_TRUE(!res);
  1735. EXPECT_EQ(Error::Canceled, res.error());
  1736. }
  1737. TEST(CancelTest, WithCancelLargePayload_Online) {
  1738. auto host = "httpbingo.org";
  1739. auto path = std::string{"/bytes/524288"};
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. auto port = 443;
  1742. SSLClient cli(host, port);
  1743. #else
  1744. auto port = 80;
  1745. Client cli(host, port);
  1746. #endif
  1747. cli.set_connection_timeout(std::chrono::seconds(5));
  1748. uint32_t count = 0;
  1749. auto res =
  1750. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1751. ASSERT_TRUE(!res);
  1752. EXPECT_EQ(Error::Canceled, res.error());
  1753. }
  1754. TEST(CancelTest, NoCancelPost) {
  1755. Server svr;
  1756. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1757. res.set_content("Hello World!", "text/plain");
  1758. });
  1759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1760. auto se = detail::scope_exit([&] {
  1761. svr.stop();
  1762. thread.join();
  1763. ASSERT_FALSE(svr.is_running());
  1764. });
  1765. svr.wait_until_ready();
  1766. Client cli(HOST, PORT);
  1767. cli.set_connection_timeout(std::chrono::seconds(5));
  1768. auto res =
  1769. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1770. "application/json", [](uint64_t, uint64_t) { return true; });
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ("Hello World!", res->body);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. }
  1775. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1776. Server svr;
  1777. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1778. res.set_content("Hello World!", "text/plain");
  1779. });
  1780. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1781. auto se = detail::scope_exit([&] {
  1782. svr.stop();
  1783. thread.join();
  1784. ASSERT_FALSE(svr.is_running());
  1785. });
  1786. svr.wait_until_ready();
  1787. Client cli(HOST, PORT);
  1788. cli.set_connection_timeout(std::chrono::seconds(5));
  1789. auto res =
  1790. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1791. "application/json", [](uint64_t, uint64_t) { return false; });
  1792. ASSERT_TRUE(!res);
  1793. EXPECT_EQ(Error::Canceled, res.error());
  1794. }
  1795. TEST(CancelTest, WithCancelLargePayloadPost) {
  1796. Server svr;
  1797. svr.set_payload_max_length(200 * 1024 * 1024);
  1798. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1799. res.set_content(LARGE_DATA, "text/plain");
  1800. });
  1801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1802. auto se = detail::scope_exit([&] {
  1803. svr.stop();
  1804. thread.join();
  1805. ASSERT_FALSE(svr.is_running());
  1806. });
  1807. svr.wait_until_ready();
  1808. Client cli(HOST, PORT);
  1809. cli.set_payload_max_length(200 * 1024 * 1024);
  1810. cli.set_connection_timeout(std::chrono::seconds(5));
  1811. auto res =
  1812. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1813. "application/json", [](uint64_t, uint64_t) { return false; });
  1814. ASSERT_TRUE(!res);
  1815. EXPECT_EQ(Error::Canceled, res.error());
  1816. }
  1817. TEST(CancelTest, NoCancelPut) {
  1818. Server svr;
  1819. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1820. res.set_content("Hello World!", "text/plain");
  1821. });
  1822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1823. auto se = detail::scope_exit([&] {
  1824. svr.stop();
  1825. thread.join();
  1826. ASSERT_FALSE(svr.is_running());
  1827. });
  1828. svr.wait_until_ready();
  1829. Client cli(HOST, PORT);
  1830. cli.set_connection_timeout(std::chrono::seconds(5));
  1831. auto res =
  1832. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1833. "application/json", [](uint64_t, uint64_t) { return true; });
  1834. ASSERT_TRUE(res);
  1835. EXPECT_EQ("Hello World!", res->body);
  1836. EXPECT_EQ(StatusCode::OK_200, res->status);
  1837. }
  1838. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1839. Server svr;
  1840. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1841. res.set_content("Hello World!", "text/plain");
  1842. });
  1843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1844. auto se = detail::scope_exit([&] {
  1845. svr.stop();
  1846. thread.join();
  1847. ASSERT_FALSE(svr.is_running());
  1848. });
  1849. svr.wait_until_ready();
  1850. Client cli(HOST, PORT);
  1851. cli.set_connection_timeout(std::chrono::seconds(5));
  1852. auto res =
  1853. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1854. "application/json", [](uint64_t, uint64_t) { return false; });
  1855. ASSERT_TRUE(!res);
  1856. EXPECT_EQ(Error::Canceled, res.error());
  1857. }
  1858. TEST(CancelTest, WithCancelLargePayloadPut) {
  1859. Server svr;
  1860. svr.set_payload_max_length(200 * 1024 * 1024);
  1861. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1862. res.set_content(LARGE_DATA, "text/plain");
  1863. });
  1864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1865. auto se = detail::scope_exit([&] {
  1866. svr.stop();
  1867. thread.join();
  1868. ASSERT_FALSE(svr.is_running());
  1869. });
  1870. svr.wait_until_ready();
  1871. Client cli(HOST, PORT);
  1872. cli.set_payload_max_length(200 * 1024 * 1024);
  1873. cli.set_connection_timeout(std::chrono::seconds(5));
  1874. auto res =
  1875. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1876. "application/json", [](uint64_t, uint64_t) { return false; });
  1877. ASSERT_TRUE(!res);
  1878. EXPECT_EQ(Error::Canceled, res.error());
  1879. }
  1880. TEST(CancelTest, NoCancelPatch) {
  1881. Server svr;
  1882. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1883. res.set_content("Hello World!", "text/plain");
  1884. });
  1885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1886. auto se = detail::scope_exit([&] {
  1887. svr.stop();
  1888. thread.join();
  1889. ASSERT_FALSE(svr.is_running());
  1890. });
  1891. svr.wait_until_ready();
  1892. Client cli(HOST, PORT);
  1893. cli.set_connection_timeout(std::chrono::seconds(5));
  1894. auto res =
  1895. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1896. "application/json", [](uint64_t, uint64_t) { return true; });
  1897. ASSERT_TRUE(res);
  1898. EXPECT_EQ("Hello World!", res->body);
  1899. EXPECT_EQ(StatusCode::OK_200, res->status);
  1900. }
  1901. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1902. Server svr;
  1903. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1904. res.set_content("Hello World!", "text/plain");
  1905. });
  1906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1907. auto se = detail::scope_exit([&] {
  1908. svr.stop();
  1909. thread.join();
  1910. ASSERT_FALSE(svr.is_running());
  1911. });
  1912. svr.wait_until_ready();
  1913. Client cli(HOST, PORT);
  1914. cli.set_connection_timeout(std::chrono::seconds(5));
  1915. auto res =
  1916. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1917. "application/json", [](uint64_t, uint64_t) { return false; });
  1918. ASSERT_TRUE(!res);
  1919. EXPECT_EQ(Error::Canceled, res.error());
  1920. }
  1921. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1922. Server svr;
  1923. svr.set_payload_max_length(200 * 1024 * 1024);
  1924. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1925. res.set_content(LARGE_DATA, "text/plain");
  1926. });
  1927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1928. auto se = detail::scope_exit([&] {
  1929. svr.stop();
  1930. thread.join();
  1931. ASSERT_FALSE(svr.is_running());
  1932. });
  1933. svr.wait_until_ready();
  1934. Client cli(HOST, PORT);
  1935. cli.set_payload_max_length(200 * 1024 * 1024);
  1936. cli.set_connection_timeout(std::chrono::seconds(5));
  1937. auto res =
  1938. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1939. "application/json", [](uint64_t, uint64_t) { return false; });
  1940. ASSERT_TRUE(!res);
  1941. EXPECT_EQ(Error::Canceled, res.error());
  1942. }
  1943. TEST(CancelTest, NoCancelDelete) {
  1944. Server svr;
  1945. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1946. res.set_content("Hello World!", "text/plain");
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. Client cli(HOST, PORT);
  1956. cli.set_connection_timeout(std::chrono::seconds(5));
  1957. auto res =
  1958. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1959. "application/json", [](uint64_t, uint64_t) { return true; });
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ("Hello World!", res->body);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1965. Server svr;
  1966. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1967. res.set_content("Hello World!", "text/plain");
  1968. });
  1969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1970. auto se = detail::scope_exit([&] {
  1971. svr.stop();
  1972. thread.join();
  1973. ASSERT_FALSE(svr.is_running());
  1974. });
  1975. svr.wait_until_ready();
  1976. Client cli(HOST, PORT);
  1977. cli.set_connection_timeout(std::chrono::seconds(5));
  1978. auto res =
  1979. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1980. "application/json", [](uint64_t, uint64_t) { return false; });
  1981. ASSERT_TRUE(!res);
  1982. EXPECT_EQ(Error::Canceled, res.error());
  1983. }
  1984. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1985. Server svr;
  1986. svr.set_payload_max_length(200 * 1024 * 1024);
  1987. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1988. res.set_content(LARGE_DATA, "text/plain");
  1989. });
  1990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. Client cli(HOST, PORT);
  1998. cli.set_payload_max_length(200 * 1024 * 1024);
  1999. cli.set_connection_timeout(std::chrono::seconds(5));
  2000. auto res =
  2001. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2002. "application/json", [](uint64_t, uint64_t) { return false; });
  2003. ASSERT_TRUE(!res);
  2004. EXPECT_EQ(Error::Canceled, res.error());
  2005. }
  2006. static std::string remove_whitespace(const std::string &input) {
  2007. std::string output;
  2008. output.reserve(input.size());
  2009. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2010. [](unsigned char c) { return !std::isspace(c); });
  2011. return output;
  2012. }
  2013. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/basic-auth/hello/world"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. {
  2024. auto res = cli.Get(path);
  2025. ASSERT_TRUE(res);
  2026. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2027. }
  2028. {
  2029. auto res = cli.Get(
  2030. path, Headers{make_basic_authentication_header("hello", "world")});
  2031. ASSERT_TRUE(res);
  2032. auto body = remove_whitespace(res->body);
  2033. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2034. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2035. EXPECT_EQ(StatusCode::OK_200, res->status);
  2036. }
  2037. {
  2038. cli.set_basic_auth("hello", "world");
  2039. auto res = cli.Get(path);
  2040. ASSERT_TRUE(res);
  2041. auto body = remove_whitespace(res->body);
  2042. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2043. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2044. EXPECT_EQ(StatusCode::OK_200, res->status);
  2045. }
  2046. {
  2047. cli.set_basic_auth("hello", "bad");
  2048. auto res = cli.Get(path);
  2049. ASSERT_TRUE(res);
  2050. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2051. }
  2052. {
  2053. cli.set_basic_auth("bad", "world");
  2054. auto res = cli.Get(path);
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2057. }
  2058. }
  2059. #ifdef CPPHTTPLIB_SSL_ENABLED
  2060. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2061. auto host = "httpbingo.org";
  2062. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2063. auto paths = std::vector<std::string>{
  2064. "/digest-auth/auth/hello/world/MD5",
  2065. "/digest-auth/auth/hello/world/SHA-256",
  2066. };
  2067. auto port = 443;
  2068. SSLClient cli(host, port);
  2069. {
  2070. auto res = cli.Get(unauth_path);
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2073. }
  2074. {
  2075. cli.set_digest_auth("hello", "world");
  2076. for (const auto &path : paths) {
  2077. auto res = cli.Get(path.c_str());
  2078. ASSERT_TRUE(res);
  2079. auto body = remove_whitespace(res->body);
  2080. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2081. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. cli.set_digest_auth("hello", "bad");
  2085. for (const auto &path : paths) {
  2086. auto res = cli.Get(path.c_str());
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2089. }
  2090. }
  2091. }
  2092. #endif
  2093. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2094. auto host = "google.com";
  2095. auto another_host = "example.com";
  2096. auto wrong_ip = "0.0.0.0";
  2097. #ifdef CPPHTTPLIB_SSL_ENABLED
  2098. SSLClient cli(host);
  2099. #else
  2100. Client cli(host);
  2101. #endif
  2102. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2103. auto res = cli.Get("/");
  2104. ASSERT_TRUE(res);
  2105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2106. }
  2107. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2108. auto host = "google.com";
  2109. auto wrong_ip = "0.0.0.0";
  2110. #ifdef CPPHTTPLIB_SSL_ENABLED
  2111. SSLClient cli(host);
  2112. #else
  2113. Client cli(host);
  2114. #endif
  2115. cli.set_hostname_addr_map({{host, wrong_ip}});
  2116. auto res = cli.Get("/");
  2117. ASSERT_TRUE(!res);
  2118. EXPECT_EQ(Error::Connection, res.error());
  2119. }
  2120. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2121. auto host = "httpbingo.org";
  2122. auto path = std::string{"/absolute-redirect/3"};
  2123. #ifdef CPPHTTPLIB_SSL_ENABLED
  2124. SSLClient cli(host);
  2125. #else
  2126. Client cli(host);
  2127. #endif
  2128. cli.set_follow_location(true);
  2129. auto res = cli.Get(path);
  2130. ASSERT_TRUE(res);
  2131. EXPECT_EQ(StatusCode::OK_200, res->status);
  2132. }
  2133. TEST(RedirectTest, Redirect_Online) {
  2134. auto host = "httpbingo.org";
  2135. auto path = std::string{"/redirect/3"};
  2136. #ifdef CPPHTTPLIB_SSL_ENABLED
  2137. SSLClient cli(host);
  2138. #else
  2139. Client cli(host);
  2140. #endif
  2141. cli.set_follow_location(true);
  2142. auto res = cli.Get(path);
  2143. ASSERT_TRUE(res);
  2144. EXPECT_EQ(StatusCode::OK_200, res->status);
  2145. }
  2146. TEST(RelativeRedirectTest, Redirect_Online) {
  2147. auto host = "httpbingo.org";
  2148. auto path = std::string{"/relative-redirect/3"};
  2149. #ifdef CPPHTTPLIB_SSL_ENABLED
  2150. SSLClient cli(host);
  2151. #else
  2152. Client cli(host);
  2153. #endif
  2154. cli.set_follow_location(true);
  2155. auto res = cli.Get(path);
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::OK_200, res->status);
  2158. }
  2159. TEST(TooManyRedirectTest, Redirect_Online) {
  2160. auto host = "httpbingo.org";
  2161. auto path = std::string{"/redirect/21"};
  2162. #ifdef CPPHTTPLIB_SSL_ENABLED
  2163. SSLClient cli(host);
  2164. #else
  2165. Client cli(host);
  2166. #endif
  2167. cli.set_follow_location(true);
  2168. auto res = cli.Get(path);
  2169. ASSERT_TRUE(!res);
  2170. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2171. }
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. TEST(YahooRedirectTest, Redirect_Online) {
  2174. Client cli("yahoo.com");
  2175. auto res = cli.Get("/");
  2176. ASSERT_TRUE(res);
  2177. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2178. cli.set_follow_location(true);
  2179. res = cli.Get("/");
  2180. ASSERT_TRUE(res);
  2181. EXPECT_EQ(StatusCode::OK_200, res->status);
  2182. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2183. }
  2184. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2185. #define REDIR_HOST "httpbingo.org"
  2186. #define REDIR_PATH "/redirect-to"
  2187. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2188. SSLClient cli(REDIR_HOST);
  2189. cli.set_follow_location(true);
  2190. auto res =
  2191. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2192. ASSERT_TRUE(res);
  2193. EXPECT_EQ(StatusCode::OK_200, res->status);
  2194. }
  2195. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2196. SSLClient cli(REDIR_HOST);
  2197. cli.set_follow_location(true);
  2198. Params params;
  2199. params.emplace("url", "http://example.com");
  2200. params.emplace("status_code", "302");
  2201. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2202. ASSERT_TRUE(res);
  2203. EXPECT_EQ(StatusCode::OK_200, res->status);
  2204. }
  2205. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2206. SSLClient cli(REDIR_HOST);
  2207. cli.set_follow_location(true);
  2208. Params params;
  2209. params.emplace("url", "http://example.com");
  2210. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2211. ASSERT_TRUE(res);
  2212. EXPECT_EQ(StatusCode::OK_200, res->status);
  2213. }
  2214. TEST(UrlWithSpace, Redirect_Online) {
  2215. SSLClient cli("edge.forgecdn.net");
  2216. cli.set_follow_location(true);
  2217. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2218. ASSERT_TRUE(res);
  2219. EXPECT_EQ(StatusCode::OK_200, res->status);
  2220. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2221. }
  2222. #endif
  2223. #if !defined(_WIN32) && !defined(_WIN64)
  2224. TEST(ReceiveSignals, Signal) {
  2225. auto setupSignalHandlers = []() {
  2226. struct sigaction act;
  2227. sigemptyset(&act.sa_mask);
  2228. act.sa_flags = SA_SIGINFO;
  2229. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2230. switch (sig) {
  2231. case SIGINT:
  2232. default: break;
  2233. }
  2234. };
  2235. ::sigaction(SIGINT, &act, nullptr);
  2236. };
  2237. Server svr;
  2238. int port = 0;
  2239. auto thread = std::thread([&]() {
  2240. setupSignalHandlers();
  2241. port = svr.bind_to_any_port(HOST);
  2242. svr.listen_after_bind();
  2243. });
  2244. auto se = detail::scope_exit([&] {
  2245. svr.stop();
  2246. thread.join();
  2247. ASSERT_FALSE(svr.is_running());
  2248. });
  2249. svr.wait_until_ready();
  2250. ASSERT_TRUE(svr.is_running());
  2251. pthread_kill(thread.native_handle(), SIGINT);
  2252. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2253. ASSERT_TRUE(svr.is_running());
  2254. }
  2255. #endif
  2256. TEST(RedirectToDifferentPort, Redirect) {
  2257. Server svr1;
  2258. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2259. res.set_content("Hello World!", "text/plain");
  2260. });
  2261. int svr1_port = 0;
  2262. auto thread1 = std::thread([&]() {
  2263. svr1_port = svr1.bind_to_any_port(HOST);
  2264. svr1.listen_after_bind();
  2265. });
  2266. Server svr2;
  2267. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2268. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2269. });
  2270. int svr2_port = 0;
  2271. auto thread2 = std::thread([&]() {
  2272. svr2_port = svr2.bind_to_any_port(HOST);
  2273. svr2.listen_after_bind();
  2274. });
  2275. auto se = detail::scope_exit([&] {
  2276. svr2.stop();
  2277. thread2.join();
  2278. svr1.stop();
  2279. thread1.join();
  2280. ASSERT_FALSE(svr2.is_running());
  2281. ASSERT_FALSE(svr1.is_running());
  2282. });
  2283. svr1.wait_until_ready();
  2284. svr2.wait_until_ready();
  2285. Client cli("localhost", svr2_port);
  2286. cli.set_follow_location(true);
  2287. auto res = cli.Get("/2");
  2288. ASSERT_TRUE(res);
  2289. EXPECT_EQ(StatusCode::OK_200, res->status);
  2290. EXPECT_EQ("Hello World!", res->body);
  2291. }
  2292. static void
  2293. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2294. Server svr1;
  2295. std::string captured_authorization;
  2296. svr1.Get("/target", [&](const Request &req, Response &res) {
  2297. captured_authorization = req.get_header_value("Authorization");
  2298. res.set_content("OK", "text/plain");
  2299. });
  2300. int svr1_port = 0;
  2301. auto thread1 = std::thread([&]() {
  2302. svr1_port = svr1.bind_to_any_port(HOST);
  2303. svr1.listen_after_bind();
  2304. });
  2305. Server svr2;
  2306. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2307. res.set_redirect(
  2308. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2309. });
  2310. int svr2_port = 0;
  2311. auto thread2 = std::thread([&]() {
  2312. svr2_port = svr2.bind_to_any_port(HOST);
  2313. svr2.listen_after_bind();
  2314. });
  2315. auto se = detail::scope_exit([&] {
  2316. svr2.stop();
  2317. thread2.join();
  2318. svr1.stop();
  2319. thread1.join();
  2320. ASSERT_FALSE(svr2.is_running());
  2321. ASSERT_FALSE(svr1.is_running());
  2322. });
  2323. svr1.wait_until_ready();
  2324. svr2.wait_until_ready();
  2325. Client cli("localhost", svr2_port);
  2326. cli.set_follow_location(true);
  2327. set_auth(cli);
  2328. auto res = cli.Get("/redir");
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(StatusCode::OK_200, res->status);
  2331. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2332. EXPECT_TRUE(captured_authorization.empty());
  2333. }
  2334. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2335. TestDoNotForwardCredentialsOnRedirect(
  2336. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2337. }
  2338. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2339. TestDoNotForwardCredentialsOnRedirect(
  2340. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2341. }
  2342. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2343. Server svr1;
  2344. std::string captured_cookie;
  2345. bool target_hit = false;
  2346. svr1.Get("/target", [&](const Request &req, Response &res) {
  2347. captured_cookie = req.get_header_value("Cookie");
  2348. target_hit = true;
  2349. res.set_content("OK", "text/plain");
  2350. });
  2351. int svr1_port = 0;
  2352. auto thread1 = std::thread([&]() {
  2353. svr1_port = svr1.bind_to_any_port(HOST);
  2354. svr1.listen_after_bind();
  2355. });
  2356. Server svr2;
  2357. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2358. res.set_redirect(
  2359. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2360. });
  2361. int svr2_port = 0;
  2362. auto thread2 = std::thread([&]() {
  2363. svr2_port = svr2.bind_to_any_port(HOST);
  2364. svr2.listen_after_bind();
  2365. });
  2366. auto se = detail::scope_exit([&] {
  2367. svr2.stop();
  2368. thread2.join();
  2369. svr1.stop();
  2370. thread1.join();
  2371. ASSERT_FALSE(svr2.is_running());
  2372. ASSERT_FALSE(svr1.is_running());
  2373. });
  2374. svr1.wait_until_ready();
  2375. svr2.wait_until_ready();
  2376. Client cli("localhost", svr2_port);
  2377. cli.set_follow_location(true);
  2378. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2379. auto res = cli.Get("/redir", headers);
  2380. ASSERT_TRUE(res);
  2381. EXPECT_EQ(StatusCode::OK_200, res->status);
  2382. EXPECT_TRUE(target_hit);
  2383. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2384. EXPECT_TRUE(captured_cookie.empty());
  2385. }
  2386. TEST(RedirectToSamePort, ForwardCookie) {
  2387. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2388. // header so that ordinary session flows keep working.
  2389. Server svr;
  2390. std::string captured_cookie;
  2391. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2392. res.set_redirect("/target", 302);
  2393. });
  2394. svr.Get("/target", [&](const Request &req, Response &res) {
  2395. captured_cookie = req.get_header_value("Cookie");
  2396. res.set_content("OK", "text/plain");
  2397. });
  2398. auto port = svr.bind_to_any_port(HOST);
  2399. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2400. auto se = detail::scope_exit([&] {
  2401. svr.stop();
  2402. thread.join();
  2403. ASSERT_FALSE(svr.is_running());
  2404. });
  2405. svr.wait_until_ready();
  2406. Client cli(HOST, port);
  2407. cli.set_follow_location(true);
  2408. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2409. auto res = cli.Get("/redir", headers);
  2410. ASSERT_TRUE(res);
  2411. EXPECT_EQ(StatusCode::OK_200, res->status);
  2412. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2413. }
  2414. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2415. Server svr;
  2416. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2417. // Port number that overflows int — should not crash
  2418. res.set_redirect("http://localhost:99999999999999999999/target");
  2419. });
  2420. auto port = svr.bind_to_any_port(HOST);
  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_follow_location(true);
  2430. auto res = cli.Get("/redir");
  2431. // Should fail gracefully, not crash (no valid response due to bad port)
  2432. EXPECT_FALSE(res);
  2433. }
  2434. TEST(RedirectFromPageWithContent, Redirect) {
  2435. Server svr;
  2436. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2437. res.set_content("___", "text/plain");
  2438. res.set_redirect("/2");
  2439. });
  2440. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2441. res.set_content("Hello World!", "text/plain");
  2442. });
  2443. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2444. auto se = detail::scope_exit([&] {
  2445. svr.stop();
  2446. th.join();
  2447. ASSERT_FALSE(svr.is_running());
  2448. });
  2449. svr.wait_until_ready();
  2450. {
  2451. Client cli("localhost", PORT);
  2452. cli.set_follow_location(true);
  2453. std::string body;
  2454. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2455. body.append(data, data_length);
  2456. return true;
  2457. });
  2458. ASSERT_TRUE(res);
  2459. EXPECT_EQ(StatusCode::OK_200, res->status);
  2460. EXPECT_EQ("Hello World!", body);
  2461. }
  2462. {
  2463. Client cli("localhost", PORT);
  2464. std::string body;
  2465. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2466. body.append(data, data_length);
  2467. return true;
  2468. });
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::Found_302, res->status);
  2471. EXPECT_EQ("___", body);
  2472. }
  2473. }
  2474. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2475. Server svr;
  2476. auto port_str = std::to_string(PORT);
  2477. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2478. auto expected_host = "[::1]:" + port_str;
  2479. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2480. res.set_content("___", "text/plain");
  2481. // res.set_redirect("/2");
  2482. res.set_redirect(redirect_url);
  2483. });
  2484. svr.Get("/2", [&](const Request &req, Response &res) {
  2485. auto host_header = req.headers.find("Host");
  2486. ASSERT_TRUE(host_header != req.headers.end());
  2487. EXPECT_EQ(expected_host, host_header->second);
  2488. res.set_content("Hello World!", "text/plain");
  2489. });
  2490. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2491. auto se = detail::scope_exit([&] {
  2492. svr.stop();
  2493. th.join();
  2494. ASSERT_FALSE(svr.is_running());
  2495. });
  2496. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2497. // actually starts anything, so the condition !svr.is_running() will
  2498. // always remain true, and the loop never stops.
  2499. // This basically counts how many milliseconds have passed since the
  2500. // call to svr.listen(), and if after 5 seconds nothing started yet
  2501. // aborts the test.
  2502. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2503. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2504. ASSERT_LT(milliseconds, 5000U);
  2505. }
  2506. {
  2507. Client cli("::1", PORT);
  2508. cli.set_follow_location(true);
  2509. std::string body;
  2510. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2511. body.append(data, data_length);
  2512. return true;
  2513. });
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::OK_200, res->status);
  2516. EXPECT_EQ("Hello World!", body);
  2517. }
  2518. {
  2519. Client cli("::1", PORT);
  2520. std::string body;
  2521. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2522. body.append(data, data_length);
  2523. return true;
  2524. });
  2525. ASSERT_TRUE(res);
  2526. EXPECT_EQ(StatusCode::Found_302, res->status);
  2527. EXPECT_EQ("___", body);
  2528. }
  2529. }
  2530. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2531. Server svr;
  2532. svr.Get("/foo", [](const Request &req, Response &res) {
  2533. auto a = req.params.find("a");
  2534. if (a != req.params.end()) {
  2535. res.set_content((*a).second, "text/plain");
  2536. res.status = StatusCode::OK_200;
  2537. } else {
  2538. res.status = StatusCode::BadRequest_400;
  2539. }
  2540. });
  2541. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2542. auto se = detail::scope_exit([&] {
  2543. svr.stop();
  2544. thread.join();
  2545. ASSERT_FALSE(svr.is_running());
  2546. });
  2547. svr.wait_until_ready();
  2548. {
  2549. Client cli(HOST, PORT);
  2550. cli.set_path_encode(false);
  2551. auto res = cli.Get("/foo?a=explicitly+encoded");
  2552. ASSERT_TRUE(res);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. // This expects it back with a space, as the `+` won't have been
  2555. // url-encoded, and server-side the params get decoded turning `+`
  2556. // into spaces.
  2557. EXPECT_EQ("explicitly encoded", res->body);
  2558. }
  2559. }
  2560. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2561. // When path encoding is disabled the client must transmit the supplied
  2562. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2563. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2564. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2565. // than a space (0x20). Assert on the raw wire target to catch this.
  2566. Server svr;
  2567. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2568. svr.Get("/foo", [&](const Request &req, Response &res) {
  2569. EXPECT_EQ(expected_target, req.target);
  2570. res.status = StatusCode::OK_200;
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. Client cli(HOST, PORT);
  2581. cli.set_path_encode(false);
  2582. auto res = cli.Get(expected_target.c_str());
  2583. ASSERT_TRUE(res);
  2584. EXPECT_EQ(StatusCode::OK_200, res->status);
  2585. }
  2586. }
  2587. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2588. Server svr;
  2589. svr.Get("/", [](const Request &req, Response &) {
  2590. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. {
  2600. Client cli(HOST, PORT);
  2601. cli.set_path_encode(false);
  2602. auto res = cli.Get("/?something=%0A");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. }
  2606. }
  2607. TEST(BindServerTest, BindDualStack) {
  2608. Server svr;
  2609. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2610. res.set_content("Hello World!", "text/plain");
  2611. });
  2612. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2613. auto se = detail::scope_exit([&] {
  2614. svr.stop();
  2615. thread.join();
  2616. ASSERT_FALSE(svr.is_running());
  2617. });
  2618. svr.wait_until_ready();
  2619. {
  2620. Client cli("127.0.0.1", PORT);
  2621. auto res = cli.Get("/1");
  2622. ASSERT_TRUE(res);
  2623. EXPECT_EQ(StatusCode::OK_200, res->status);
  2624. EXPECT_EQ("Hello World!", res->body);
  2625. }
  2626. {
  2627. Client cli("::1", PORT);
  2628. auto res = cli.Get("/1");
  2629. ASSERT_TRUE(res);
  2630. EXPECT_EQ(StatusCode::OK_200, res->status);
  2631. EXPECT_EQ("Hello World!", res->body);
  2632. }
  2633. }
  2634. TEST(BindServerTest, BindAndListenSeparately) {
  2635. Server svr;
  2636. int port = svr.bind_to_any_port("0.0.0.0");
  2637. ASSERT_TRUE(svr.is_valid());
  2638. ASSERT_TRUE(port > 0);
  2639. svr.stop();
  2640. }
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2644. CLIENT_CA_CERT_DIR);
  2645. int port = svr.bind_to_any_port("0.0.0.0");
  2646. ASSERT_TRUE(svr.is_valid());
  2647. ASSERT_TRUE(port > 0);
  2648. svr.stop();
  2649. }
  2650. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2651. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2652. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2653. int port = svr.bind_to_any_port("0.0.0.0");
  2654. ASSERT_TRUE(svr.is_valid());
  2655. ASSERT_TRUE(port > 0);
  2656. svr.stop();
  2657. }
  2658. TEST(BindServerTest, UpdateCertsPem) {
  2659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2660. int port = svr.bind_to_any_port("0.0.0.0");
  2661. ASSERT_TRUE(svr.is_valid());
  2662. ASSERT_TRUE(port > 0);
  2663. // Read PEM files
  2664. std::string cert_pem, key_pem, ca_pem;
  2665. read_file(SERVER_CERT_FILE, cert_pem);
  2666. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2667. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2668. // Update server certificates using PEM API
  2669. ASSERT_TRUE(
  2670. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2671. ASSERT_TRUE(svr.is_valid());
  2672. svr.stop();
  2673. }
  2674. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2675. // Start server with client CA (enables client auth)
  2676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2677. ASSERT_TRUE(svr.is_valid());
  2678. bool handler_called = false;
  2679. svr.Get("/test", [&](const Request &req, Response &res) {
  2680. handler_called = true;
  2681. // Verify client certificate is present
  2682. auto cert = req.peer_cert();
  2683. EXPECT_TRUE(static_cast<bool>(cert));
  2684. res.set_content("ok", "text/plain");
  2685. });
  2686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2687. auto se = detail::scope_exit([&] {
  2688. svr.stop();
  2689. t.join();
  2690. ASSERT_FALSE(svr.is_running());
  2691. });
  2692. svr.wait_until_ready();
  2693. // Read PEM files
  2694. std::string cert_pem, key_pem, ca_pem;
  2695. read_file(SERVER_CERT_FILE, cert_pem);
  2696. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2697. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2698. // Update server certificates and client CA using PEM API while server running
  2699. ASSERT_TRUE(
  2700. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2701. // Connect with client certificate
  2702. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2703. cli.enable_server_certificate_verification(false);
  2704. cli.set_connection_timeout(30);
  2705. auto res = cli.Get("/test");
  2706. ASSERT_TRUE(res);
  2707. ASSERT_EQ(StatusCode::OK_200, res->status);
  2708. ASSERT_TRUE(handler_called);
  2709. EXPECT_EQ("ok", res->body);
  2710. }
  2711. #endif
  2712. TEST(ErrorHandlerTest, ContentLength) {
  2713. Server svr;
  2714. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2715. res.status = StatusCode::OK_200;
  2716. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2717. "text/html"); // <= Content-Length still 13
  2718. });
  2719. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2720. res.set_content("Hello World!\n", "text/plain");
  2721. res.status = 524;
  2722. });
  2723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2724. auto se = detail::scope_exit([&] {
  2725. svr.stop();
  2726. thread.join();
  2727. ASSERT_FALSE(svr.is_running());
  2728. });
  2729. svr.wait_until_ready();
  2730. {
  2731. Client cli(HOST, PORT);
  2732. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2733. ASSERT_TRUE(res);
  2734. EXPECT_EQ(StatusCode::OK_200, res->status);
  2735. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2736. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2737. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2738. }
  2739. }
  2740. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2741. TEST(ExceptionTest, WithoutExceptionHandler) {
  2742. Server svr;
  2743. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2744. throw std::runtime_error("exception...");
  2745. });
  2746. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2747. throw std::runtime_error("exception\r\n...");
  2748. });
  2749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. listen_thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli("localhost", PORT);
  2757. {
  2758. auto res = cli.Get("/exception");
  2759. ASSERT_TRUE(res);
  2760. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2761. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2762. }
  2763. {
  2764. auto res = cli.Get("/unknown");
  2765. ASSERT_TRUE(res);
  2766. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2767. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2768. }
  2769. }
  2770. TEST(ExceptionTest, WithExceptionHandler) {
  2771. Server svr;
  2772. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2773. std::exception_ptr ep) {
  2774. EXPECT_FALSE(ep == nullptr);
  2775. try {
  2776. std::rethrow_exception(ep);
  2777. } catch (std::exception &e) {
  2778. EXPECT_EQ("abc", std::string(e.what()));
  2779. } catch (...) {}
  2780. res.status = StatusCode::InternalServerError_500;
  2781. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2782. "text/html"); // <= Content-Length still 13 at this point
  2783. });
  2784. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2785. res.set_content("Hello World!\n", "text/plain");
  2786. throw std::runtime_error("abc");
  2787. });
  2788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2789. auto se = detail::scope_exit([&] {
  2790. svr.stop();
  2791. thread.join();
  2792. ASSERT_FALSE(svr.is_running());
  2793. });
  2794. svr.wait_until_ready();
  2795. for (size_t i = 0; i < 10; i++) {
  2796. Client cli(HOST, PORT);
  2797. for (size_t j = 0; j < 100; j++) {
  2798. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2799. ASSERT_TRUE(res);
  2800. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2801. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2802. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2803. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2804. }
  2805. cli.set_keep_alive(true);
  2806. for (size_t j = 0; j < 100; j++) {
  2807. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2808. ASSERT_TRUE(res);
  2809. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2810. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2811. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2812. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2813. }
  2814. }
  2815. }
  2816. TEST(ExceptionTest, AndErrorHandler) {
  2817. Server svr;
  2818. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2819. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2820. });
  2821. svr.set_exception_handler(
  2822. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2823. EXPECT_FALSE(ep == nullptr);
  2824. try {
  2825. std::rethrow_exception(ep);
  2826. } catch (std::exception &e) {
  2827. res.set_content(e.what(), "text/html");
  2828. } catch (...) {}
  2829. res.status = StatusCode::InternalServerError_500;
  2830. });
  2831. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2832. throw std::runtime_error("EXCEPTION");
  2833. });
  2834. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2835. res.set_content("ERROR", "text/html");
  2836. res.status = StatusCode::InternalServerError_500;
  2837. });
  2838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2839. auto se = detail::scope_exit([&] {
  2840. svr.stop();
  2841. thread.join();
  2842. ASSERT_FALSE(svr.is_running());
  2843. });
  2844. svr.wait_until_ready();
  2845. Client cli(HOST, PORT);
  2846. {
  2847. auto res = cli.Get("/exception");
  2848. ASSERT_TRUE(res);
  2849. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2850. EXPECT_EQ("EXCEPTION", res->body);
  2851. }
  2852. {
  2853. auto res = cli.Get("/error");
  2854. ASSERT_TRUE(res);
  2855. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2856. EXPECT_EQ("ERROR", res->body);
  2857. }
  2858. {
  2859. auto res = cli.Get("/invalid");
  2860. ASSERT_TRUE(res);
  2861. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2862. EXPECT_EQ("NOT_FOUND", res->body);
  2863. }
  2864. }
  2865. #endif
  2866. TEST(NoContentTest, ContentLength) {
  2867. Server svr;
  2868. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2869. res.status = StatusCode::NoContent_204;
  2870. });
  2871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2872. auto se = detail::scope_exit([&] {
  2873. svr.stop();
  2874. thread.join();
  2875. ASSERT_FALSE(svr.is_running());
  2876. });
  2877. svr.wait_until_ready();
  2878. {
  2879. Client cli(HOST, PORT);
  2880. auto res = cli.Get("/hi");
  2881. ASSERT_TRUE(res);
  2882. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2883. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2884. }
  2885. }
  2886. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2887. #ifdef CPPHTTPLIB_SSL_ENABLED
  2888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2889. ASSERT_TRUE(svr.is_valid());
  2890. #else
  2891. Server svr;
  2892. #endif
  2893. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2894. if (req.path == "/routing_handler") {
  2895. res.set_header("PRE_ROUTING", "on");
  2896. res.set_content("Routing Handler", "text/plain");
  2897. return httplib::Server::HandlerResponse::Handled;
  2898. }
  2899. return httplib::Server::HandlerResponse::Unhandled;
  2900. });
  2901. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2902. res.set_content("Error", "text/html");
  2903. });
  2904. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2905. if (req.path == "/routing_handler") {
  2906. res.set_header("POST_ROUTING", "on");
  2907. }
  2908. });
  2909. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2910. res.set_content("Hello World!\n", "text/plain");
  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. #ifdef CPPHTTPLIB_SSL_ENABLED
  2921. SSLClient cli(HOST, PORT);
  2922. cli.enable_server_certificate_verification(false);
  2923. #else
  2924. Client cli(HOST, PORT);
  2925. #endif
  2926. auto res = cli.Get("/routing_handler");
  2927. ASSERT_TRUE(res);
  2928. EXPECT_EQ(StatusCode::OK_200, res->status);
  2929. EXPECT_EQ("Routing Handler", res->body);
  2930. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2931. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2932. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2933. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2934. }
  2935. {
  2936. #ifdef CPPHTTPLIB_SSL_ENABLED
  2937. SSLClient cli(HOST, PORT);
  2938. cli.enable_server_certificate_verification(false);
  2939. #else
  2940. Client cli(HOST, PORT);
  2941. #endif
  2942. auto res = cli.Get("/hi");
  2943. ASSERT_TRUE(res);
  2944. EXPECT_EQ(StatusCode::OK_200, res->status);
  2945. EXPECT_EQ("Hello World!\n", res->body);
  2946. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2947. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2948. }
  2949. {
  2950. #ifdef CPPHTTPLIB_SSL_ENABLED
  2951. SSLClient cli(HOST, PORT);
  2952. cli.enable_server_certificate_verification(false);
  2953. #else
  2954. Client cli(HOST, PORT);
  2955. #endif
  2956. auto res = cli.Get("/aaa");
  2957. ASSERT_TRUE(res);
  2958. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2959. EXPECT_EQ("Error", res->body);
  2960. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2961. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2962. }
  2963. }
  2964. TEST(RequestHandlerTest, PreRequestHandler) {
  2965. auto route_path = "/user/:user";
  2966. Server svr;
  2967. svr.Get("/hi", [](const Request &, Response &res) {
  2968. res.set_content("hi", "text/plain");
  2969. });
  2970. svr.Get(route_path, [](const Request &req, Response &res) {
  2971. res.set_content(req.path_params.at("user"), "text/plain");
  2972. });
  2973. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2974. if (req.matched_route == route_path) {
  2975. auto user = req.path_params.at("user");
  2976. if (user != "john") {
  2977. res.status = StatusCode::Forbidden_403;
  2978. res.set_content("error", "text/html");
  2979. return Server::HandlerResponse::Handled;
  2980. }
  2981. }
  2982. return Server::HandlerResponse::Unhandled;
  2983. });
  2984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2985. auto se = detail::scope_exit([&] {
  2986. svr.stop();
  2987. thread.join();
  2988. ASSERT_FALSE(svr.is_running());
  2989. });
  2990. svr.wait_until_ready();
  2991. Client cli(HOST, PORT);
  2992. {
  2993. auto res = cli.Get("/hi");
  2994. ASSERT_TRUE(res);
  2995. EXPECT_EQ(StatusCode::OK_200, res->status);
  2996. EXPECT_EQ("hi", res->body);
  2997. }
  2998. {
  2999. auto res = cli.Get("/user/john");
  3000. ASSERT_TRUE(res);
  3001. EXPECT_EQ(StatusCode::OK_200, res->status);
  3002. EXPECT_EQ("john", res->body);
  3003. }
  3004. {
  3005. auto res = cli.Get("/user/invalid-user");
  3006. ASSERT_TRUE(res);
  3007. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3008. EXPECT_EQ("error", res->body);
  3009. }
  3010. }
  3011. // The pre-request handler must run before the request body is read, so a
  3012. // rejected request never forces the server to buffer a (potentially large)
  3013. // body. Here the posted body is larger than the payload limit: if the body
  3014. // were read first the server would answer 413, but because the pre-request
  3015. // handler runs first it answers 403 and the body is never read.
  3016. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3017. Server svr;
  3018. svr.set_payload_max_length(8);
  3019. auto handler_ran = false;
  3020. svr.Post("/reject", [&](const Request &req, Response &res) {
  3021. handler_ran = true;
  3022. res.set_content(req.body, "text/plain");
  3023. });
  3024. svr.Post("/accept", [](const Request &req, Response &res) {
  3025. res.set_content(req.body, "text/plain");
  3026. });
  3027. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3028. if (req.matched_route == "/reject") {
  3029. res.status = StatusCode::Forbidden_403;
  3030. res.set_content("denied", "text/plain");
  3031. return Server::HandlerResponse::Handled;
  3032. }
  3033. return Server::HandlerResponse::Unhandled;
  3034. });
  3035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. Client cli(HOST, PORT);
  3043. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3044. // rejects with 403 before the body is read, so 413 is never reached.
  3045. {
  3046. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3047. ASSERT_TRUE(res);
  3048. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3049. EXPECT_EQ("denied", res->body);
  3050. EXPECT_FALSE(handler_ran);
  3051. }
  3052. // An approved route still reads the body and enforces the payload limit.
  3053. {
  3054. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3055. ASSERT_TRUE(res);
  3056. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3057. }
  3058. }
  3059. TEST(UserDataTest, BasicOperations) {
  3060. httplib::UserData ud;
  3061. // Initially empty
  3062. EXPECT_FALSE(ud.has("key"));
  3063. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3064. // set and get
  3065. ud.set("key", 42);
  3066. EXPECT_TRUE(ud.has("key"));
  3067. auto *p = ud.get<int>("key");
  3068. ASSERT_NE(nullptr, p);
  3069. EXPECT_EQ(42, *p);
  3070. // Type mismatch → nullptr
  3071. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3072. // Overwrite with different type
  3073. ud.set("key", std::string("hello"));
  3074. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3075. auto *s = ud.get<std::string>("key");
  3076. ASSERT_NE(nullptr, s);
  3077. EXPECT_EQ("hello", *s);
  3078. // erase
  3079. ud.erase("key");
  3080. EXPECT_FALSE(ud.has("key"));
  3081. // clear
  3082. ud.set("a", 1);
  3083. ud.set("b", 2);
  3084. ud.clear();
  3085. EXPECT_FALSE(ud.has("a"));
  3086. EXPECT_FALSE(ud.has("b"));
  3087. }
  3088. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3089. struct AuthCtx {
  3090. std::string user_id;
  3091. };
  3092. Server svr;
  3093. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3094. res.user_data.set("auth", AuthCtx{"alice"});
  3095. return Server::HandlerResponse::Unhandled;
  3096. });
  3097. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3098. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3099. ASSERT_NE(nullptr, ctx);
  3100. res.set_content("Hello " + ctx->user_id, "text/plain");
  3101. });
  3102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3103. auto se = detail::scope_exit([&] {
  3104. svr.stop();
  3105. thread.join();
  3106. ASSERT_FALSE(svr.is_running());
  3107. });
  3108. svr.wait_until_ready();
  3109. Client cli(HOST, PORT);
  3110. auto res = cli.Get("/me");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. EXPECT_EQ("Hello alice", res->body);
  3114. }
  3115. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3116. struct RoleCtx {
  3117. std::string role;
  3118. };
  3119. Server svr;
  3120. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3121. res.user_data.set("role", RoleCtx{"admin"});
  3122. return Server::HandlerResponse::Unhandled;
  3123. });
  3124. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3125. auto *ctx = res.user_data.get<RoleCtx>("role");
  3126. ASSERT_NE(nullptr, ctx);
  3127. res.set_content(ctx->role, "text/plain");
  3128. });
  3129. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3130. auto se = detail::scope_exit([&] {
  3131. svr.stop();
  3132. thread.join();
  3133. ASSERT_FALSE(svr.is_running());
  3134. });
  3135. svr.wait_until_ready();
  3136. Client cli(HOST, PORT);
  3137. auto res = cli.Get("/role");
  3138. ASSERT_TRUE(res);
  3139. EXPECT_EQ(StatusCode::OK_200, res->status);
  3140. EXPECT_EQ("admin", res->body);
  3141. }
  3142. TEST(InvalidFormatTest, StatusCode) {
  3143. Server svr;
  3144. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3145. res.set_content("Hello World!\n", "text/plain");
  3146. res.status = 9999; // Status should be a three-digit code...
  3147. });
  3148. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3149. auto se = detail::scope_exit([&] {
  3150. svr.stop();
  3151. thread.join();
  3152. ASSERT_FALSE(svr.is_running());
  3153. });
  3154. svr.wait_until_ready();
  3155. {
  3156. Client cli(HOST, PORT);
  3157. auto res = cli.Get("/hi");
  3158. ASSERT_FALSE(res);
  3159. }
  3160. }
  3161. TEST(URLFragmentTest, WithFragment) {
  3162. Server svr;
  3163. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3164. EXPECT_TRUE(req.target == "/hi");
  3165. });
  3166. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3167. auto se = detail::scope_exit([&] {
  3168. svr.stop();
  3169. thread.join();
  3170. ASSERT_FALSE(svr.is_running());
  3171. });
  3172. svr.wait_until_ready();
  3173. {
  3174. Client cli(HOST, PORT);
  3175. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3176. EXPECT_TRUE(res);
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. res = cli.Get("/hi%23key1=val1=key2=val2");
  3179. EXPECT_TRUE(res);
  3180. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3181. }
  3182. }
  3183. TEST(HeaderWriter, SetHeaderWriter) {
  3184. Server svr;
  3185. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3186. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3187. return detail::write_headers(strm, hdrs);
  3188. });
  3189. svr.Get("/hi", [](const Request &req, Response &res) {
  3190. auto it = req.headers.find("CustomClientHeader");
  3191. EXPECT_TRUE(it != req.headers.end());
  3192. EXPECT_EQ(it->second, "CustomClientValue");
  3193. res.set_content("Hello World!\n", "text/plain");
  3194. });
  3195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3196. auto se = detail::scope_exit([&] {
  3197. svr.stop();
  3198. thread.join();
  3199. ASSERT_FALSE(svr.is_running());
  3200. });
  3201. svr.wait_until_ready();
  3202. {
  3203. Client cli(HOST, PORT);
  3204. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3205. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3206. return detail::write_headers(strm, hdrs);
  3207. });
  3208. auto res = cli.Get("/hi");
  3209. EXPECT_TRUE(res);
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. auto it = res->headers.find("CustomServerHeader");
  3212. EXPECT_TRUE(it != res->headers.end());
  3213. EXPECT_EQ(it->second, "CustomServerValue");
  3214. }
  3215. }
  3216. class ServerTest : public ::testing::Test {
  3217. protected:
  3218. ServerTest()
  3219. : cli_(HOST, PORT)
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. ,
  3222. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3223. #endif
  3224. {
  3225. #ifdef CPPHTTPLIB_SSL_ENABLED
  3226. cli_.enable_server_certificate_verification(false);
  3227. #endif
  3228. // Allow LARGE_DATA (100MB) responses
  3229. cli_.set_payload_max_length(200 * 1024 * 1024);
  3230. }
  3231. virtual void SetUp() {
  3232. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3233. svr_.set_payload_max_length(200 * 1024 * 1024);
  3234. svr_.set_mount_point("/", "./www");
  3235. svr_.set_mount_point("/mount", "./www2");
  3236. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3237. svr_.Get("/hi",
  3238. [&](const Request & /*req*/, Response &res) {
  3239. res.set_content("Hello World!", "text/plain");
  3240. })
  3241. .Get("/file_content",
  3242. [&](const Request & /*req*/, Response &res) {
  3243. res.set_file_content("./www/dir/test.html");
  3244. })
  3245. .Get("/file_content_with_content_type",
  3246. [&](const Request & /*req*/, Response &res) {
  3247. res.set_file_content("./www/file", "text/plain");
  3248. })
  3249. .Get("/invalid_file_content",
  3250. [&](const Request & /*req*/, Response &res) {
  3251. res.set_file_content("./www/dir/invalid_file_path");
  3252. })
  3253. .Get("/http_response_splitting",
  3254. [&](const Request & /*req*/, Response &res) {
  3255. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3256. EXPECT_EQ(0U, res.headers.size());
  3257. EXPECT_FALSE(res.has_header("a"));
  3258. res.set_header("a", "1\nSet-Cookie: a=1");
  3259. EXPECT_EQ(0U, res.headers.size());
  3260. EXPECT_FALSE(res.has_header("a"));
  3261. res.set_header("a", "1\rSet-Cookie: a=1");
  3262. EXPECT_EQ(0U, res.headers.size());
  3263. EXPECT_FALSE(res.has_header("a"));
  3264. res.set_header("a\r\nb", "0");
  3265. EXPECT_EQ(0U, res.headers.size());
  3266. EXPECT_FALSE(res.has_header("a"));
  3267. res.set_header("a\rb", "0");
  3268. EXPECT_EQ(0U, res.headers.size());
  3269. EXPECT_FALSE(res.has_header("a"));
  3270. res.set_header("a\nb", "0");
  3271. EXPECT_EQ(0U, res.headers.size());
  3272. EXPECT_FALSE(res.has_header("a"));
  3273. res.set_redirect("1\r\nSet-Cookie: a=1");
  3274. EXPECT_EQ(0U, res.headers.size());
  3275. EXPECT_FALSE(res.has_header("Location"));
  3276. })
  3277. .Get("/slow",
  3278. [&](const Request & /*req*/, Response &res) {
  3279. std::this_thread::sleep_for(std::chrono::seconds(4));
  3280. res.set_content("slow", "text/plain");
  3281. })
  3282. #if 0
  3283. .Post("/slowpost",
  3284. [&](const Request & /*req*/, Response &res) {
  3285. std::this_thread::sleep_for(std::chrono::seconds(2));
  3286. res.set_content("slow", "text/plain");
  3287. })
  3288. #endif
  3289. .Get("/remote_addr",
  3290. [&](const Request &req, Response &res) {
  3291. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3292. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3293. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3294. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3295. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3296. #endif
  3297. res.set_content(req.remote_addr, "text/plain");
  3298. })
  3299. .Get("/local_addr",
  3300. [&](const Request &req, Response &res) {
  3301. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3302. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3303. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3304. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3305. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3306. #endif
  3307. auto local_addr = req.local_addr;
  3308. auto local_port = std::to_string(req.local_port);
  3309. res.set_content(local_addr.append(":").append(local_port),
  3310. "text/plain");
  3311. })
  3312. .Get("/endwith%",
  3313. [&](const Request & /*req*/, Response &res) {
  3314. res.set_content("Hello World!", "text/plain");
  3315. })
  3316. .Get("/a\\+\\+b",
  3317. [&](const Request &req, Response &res) {
  3318. ASSERT_TRUE(req.has_param("a +b"));
  3319. auto val = req.get_param_value("a +b");
  3320. res.set_content(val, "text/plain");
  3321. })
  3322. .Get("/", [&](const Request & /*req*/,
  3323. Response &res) { res.set_redirect("/hi"); })
  3324. .Post("/1",
  3325. [](const Request & /*req*/, Response &res) {
  3326. res.set_redirect("/2", StatusCode::SeeOther_303);
  3327. })
  3328. .Get("/2",
  3329. [](const Request & /*req*/, Response &res) {
  3330. res.set_content("redirected.", "text/plain");
  3331. res.status = StatusCode::OK_200;
  3332. })
  3333. .Post("/person",
  3334. [&](const Request &req, Response &res) {
  3335. if (req.has_param("name") && req.has_param("note")) {
  3336. persons_[req.get_param_value("name")] =
  3337. req.get_param_value("note");
  3338. } else {
  3339. res.status = StatusCode::BadRequest_400;
  3340. }
  3341. })
  3342. .Put("/person",
  3343. [&](const Request &req, Response &res) {
  3344. if (req.has_param("name") && req.has_param("note")) {
  3345. persons_[req.get_param_value("name")] =
  3346. req.get_param_value("note");
  3347. } else {
  3348. res.status = StatusCode::BadRequest_400;
  3349. }
  3350. })
  3351. .Get("/person/(.*)",
  3352. [&](const Request &req, Response &res) {
  3353. string name = req.matches[1];
  3354. if (persons_.find(name) != persons_.end()) {
  3355. auto note = persons_[name];
  3356. res.set_content(note, "text/plain");
  3357. } else {
  3358. res.status = StatusCode::NotFound_404;
  3359. }
  3360. })
  3361. .Delete("/person",
  3362. [&](const Request &req, Response &res) {
  3363. if (req.has_param("name")) {
  3364. string name = req.get_param_value("name");
  3365. if (persons_.find(name) != persons_.end()) {
  3366. persons_.erase(name);
  3367. res.set_content("DELETED", "text/plain");
  3368. } else {
  3369. res.status = StatusCode::NotFound_404;
  3370. }
  3371. } else {
  3372. res.status = StatusCode::BadRequest_400;
  3373. }
  3374. })
  3375. .Post("/x-www-form-urlencoded-json",
  3376. [&](const Request &req, Response &res) {
  3377. auto json = req.get_param_value("json");
  3378. ASSERT_EQ(JSON_DATA, json);
  3379. res.set_content(json, "appliation/json");
  3380. res.status = StatusCode::OK_200;
  3381. })
  3382. .Get("/streamed-chunked",
  3383. [&](const Request & /*req*/, Response &res) {
  3384. res.set_chunked_content_provider(
  3385. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3386. sink.os << "123";
  3387. sink.os << "456";
  3388. sink.os << "789";
  3389. sink.done();
  3390. return true;
  3391. });
  3392. })
  3393. .Get("/streamed-chunked-with-prohibited-trailer",
  3394. [&](const Request & /*req*/, Response &res) {
  3395. auto i = new int(0);
  3396. // Declare both a prohibited trailer (Content-Length) and an
  3397. // allowed one
  3398. res.set_header("Trailer", "Content-Length, X-Allowed");
  3399. res.set_chunked_content_provider(
  3400. "text/plain",
  3401. [i](size_t /*offset*/, DataSink &sink) {
  3402. switch (*i) {
  3403. case 0: sink.os << "123"; break;
  3404. case 1: sink.os << "456"; break;
  3405. case 2: sink.os << "789"; break;
  3406. case 3: {
  3407. sink.done_with_trailer(
  3408. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3409. } break;
  3410. }
  3411. (*i)++;
  3412. return true;
  3413. },
  3414. [i](bool success) {
  3415. EXPECT_TRUE(success);
  3416. delete i;
  3417. });
  3418. })
  3419. .Get("/streamed-chunked2",
  3420. [&](const Request & /*req*/, Response &res) {
  3421. auto i = new int(0);
  3422. res.set_chunked_content_provider(
  3423. "text/plain",
  3424. [i](size_t /*offset*/, DataSink &sink) {
  3425. switch (*i) {
  3426. case 0: sink.os << "123"; break;
  3427. case 1: sink.os << "456"; break;
  3428. case 2: sink.os << "789"; break;
  3429. case 3: sink.done(); break;
  3430. }
  3431. (*i)++;
  3432. return true;
  3433. },
  3434. [i](bool success) {
  3435. EXPECT_TRUE(success);
  3436. delete i;
  3437. });
  3438. })
  3439. .Get("/streamed-chunked-with-trailer",
  3440. [&](const Request & /*req*/, Response &res) {
  3441. auto i = new int(0);
  3442. res.set_header("Trailer", "Dummy1, Dummy2");
  3443. res.set_chunked_content_provider(
  3444. "text/plain",
  3445. [i](size_t /*offset*/, DataSink &sink) {
  3446. switch (*i) {
  3447. case 0: sink.os << "123"; break;
  3448. case 1: sink.os << "456"; break;
  3449. case 2: sink.os << "789"; break;
  3450. case 3: {
  3451. sink.done_with_trailer(
  3452. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3453. } break;
  3454. }
  3455. (*i)++;
  3456. return true;
  3457. },
  3458. [i](bool success) {
  3459. EXPECT_TRUE(success);
  3460. delete i;
  3461. });
  3462. })
  3463. .Get("/streamed",
  3464. [&](const Request & /*req*/, Response &res) {
  3465. res.set_content_provider(
  3466. 6, "text/plain",
  3467. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3468. sink.os << (offset < 3 ? "a" : "b");
  3469. return true;
  3470. });
  3471. })
  3472. .Get("/streamed-without-length",
  3473. [&](const Request & /*req*/, Response &res) {
  3474. auto data = new std::string("abcdefg");
  3475. res.set_content_provider(
  3476. "text/plain",
  3477. [data](size_t offset, DataSink &sink) {
  3478. if (offset < data->size()) {
  3479. sink.os << data->substr(offset);
  3480. }
  3481. sink.done();
  3482. return true;
  3483. },
  3484. [data](bool success) {
  3485. EXPECT_TRUE(success);
  3486. delete data;
  3487. });
  3488. })
  3489. .Get("/streamed-with-range",
  3490. [&](const Request &req, Response &res) {
  3491. auto data = new std::string("abcdefg");
  3492. res.set_content_provider(
  3493. data->size(), "text/plain",
  3494. [data](size_t offset, size_t length, DataSink &sink) {
  3495. size_t DATA_CHUNK_SIZE = 4;
  3496. const auto &d = *data;
  3497. auto out_len =
  3498. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3499. auto ret =
  3500. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3501. EXPECT_TRUE(ret);
  3502. return true;
  3503. },
  3504. [data, &req](bool success) {
  3505. EXPECT_EQ(success, !req.has_param("error"));
  3506. delete data;
  3507. });
  3508. })
  3509. .Get("/streamed-cancel",
  3510. [&](const Request & /*req*/, Response &res) {
  3511. res.set_content_provider(
  3512. size_t(-1), "text/plain",
  3513. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3514. sink.os << "data_chunk";
  3515. return true;
  3516. });
  3517. })
  3518. .Get("/regex-with-delimiter",
  3519. [&](const Request &req, Response & /*res*/) {
  3520. ASSERT_TRUE(req.has_param("key"));
  3521. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3522. })
  3523. .Get("/with-range",
  3524. [&](const Request & /*req*/, Response &res) {
  3525. res.set_content("abcdefg", "text/plain");
  3526. })
  3527. .Get("/test-start-time",
  3528. [&](const Request &req, Response & /*res*/) {
  3529. EXPECT_NE(req.start_time_,
  3530. std::chrono::steady_clock::time_point::min());
  3531. })
  3532. .Get("/with-range-customized-response",
  3533. [&](const Request & /*req*/, Response &res) {
  3534. res.status = StatusCode::BadRequest_400;
  3535. res.set_content(JSON_DATA, "application/json");
  3536. })
  3537. .Post("/chunked",
  3538. [&](const Request &req, Response & /*res*/) {
  3539. EXPECT_EQ(req.body, "dechunked post body");
  3540. })
  3541. .Post("/large-chunked",
  3542. [&](const Request &req, Response & /*res*/) {
  3543. std::string expected(6 * 30 * 1024u, 'a');
  3544. EXPECT_EQ(req.body, expected);
  3545. })
  3546. .Post("/multipart",
  3547. [&](const Request &req, Response & /*res*/) {
  3548. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3549. req.form.get_field_count("text2") +
  3550. req.form.get_field_count("file3") +
  3551. req.form.get_field_count("file4"));
  3552. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3553. req.form.get_file_count("file2"));
  3554. ASSERT_TRUE(!req.form.has_file("???"));
  3555. ASSERT_TRUE(!req.form.has_field("???"));
  3556. ASSERT_TRUE(req.body.empty());
  3557. {
  3558. const auto &text = req.form.get_field("text1");
  3559. EXPECT_EQ("text default", text);
  3560. }
  3561. {
  3562. const auto &text = req.form.get_field("text2");
  3563. EXPECT_EQ("aωb", text);
  3564. }
  3565. {
  3566. const auto &file = req.form.get_file("file1");
  3567. EXPECT_EQ("hello.txt", file.filename);
  3568. EXPECT_EQ("text/plain", file.content_type);
  3569. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3570. }
  3571. {
  3572. const auto &file = req.form.get_file("file2");
  3573. EXPECT_EQ("world.json", file.filename);
  3574. EXPECT_EQ("application/json", file.content_type);
  3575. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3576. }
  3577. {
  3578. const auto &text = req.form.get_field("file3");
  3579. EXPECT_EQ(0u, text.size());
  3580. }
  3581. {
  3582. const auto &text = req.form.get_field("file4");
  3583. EXPECT_EQ(0u, text.size());
  3584. }
  3585. })
  3586. .Post("/multipart/multi_file_values",
  3587. [&](const Request &req, Response & /*res*/) {
  3588. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3589. req.form.get_field_count("multi_text1"));
  3590. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3591. ASSERT_TRUE(!req.form.has_file("???"));
  3592. ASSERT_TRUE(!req.form.has_field("???"));
  3593. ASSERT_TRUE(req.body.empty());
  3594. {
  3595. const auto &text = req.form.get_field("text");
  3596. EXPECT_EQ("default text", text);
  3597. }
  3598. {
  3599. const auto &text1_values = req.form.get_fields("multi_text1");
  3600. EXPECT_EQ(2u, text1_values.size());
  3601. EXPECT_EQ("aaaaa", text1_values[0]);
  3602. EXPECT_EQ("bbbbb", text1_values[1]);
  3603. }
  3604. {
  3605. const auto &file1_values = req.form.get_files("multi_file1");
  3606. EXPECT_EQ(2u, file1_values.size());
  3607. auto file1 = file1_values[0];
  3608. EXPECT_EQ(file1.filename, "hello.txt");
  3609. EXPECT_EQ(file1.content_type, "text/plain");
  3610. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3611. auto file2 = file1_values[1];
  3612. EXPECT_EQ(file2.filename, "world.json");
  3613. EXPECT_EQ(file2.content_type, "application/json");
  3614. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3615. }
  3616. })
  3617. .Post("/empty",
  3618. [&](const Request &req, Response &res) {
  3619. EXPECT_EQ(req.body, "");
  3620. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3621. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3622. res.set_content("empty", "text/plain");
  3623. })
  3624. .Post("/empty-no-content-type",
  3625. [&](const Request &req, Response &res) {
  3626. EXPECT_EQ(req.body, "");
  3627. EXPECT_FALSE(req.has_header("Content-Type"));
  3628. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3629. res.set_content("empty-no-content-type", "text/plain");
  3630. })
  3631. .Post("/path-only",
  3632. [&](const Request &req, Response &res) {
  3633. EXPECT_EQ(req.body, "");
  3634. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3636. res.set_content("path-only", "text/plain");
  3637. })
  3638. .Post("/path-headers-only",
  3639. [&](const Request &req, Response &res) {
  3640. EXPECT_EQ(req.body, "");
  3641. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3643. EXPECT_EQ("world", req.get_header_value("hello"));
  3644. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3645. res.set_content("path-headers-only", "text/plain");
  3646. })
  3647. .Post("/post-large",
  3648. [&](const Request &req, Response &res) {
  3649. EXPECT_EQ(req.body, LARGE_DATA);
  3650. res.set_content(req.body, "text/plain");
  3651. })
  3652. .Post("/post-loopback",
  3653. [&](const Request &, Response &res,
  3654. ContentReader const &content_reader) {
  3655. std::string body;
  3656. content_reader([&](const char *data, size_t data_length) {
  3657. body.append(data, data_length);
  3658. return true;
  3659. });
  3660. res.set_content(body, "text/plain");
  3661. })
  3662. .Put("/put-loopback",
  3663. [&](const Request &, Response &res,
  3664. ContentReader const &content_reader) {
  3665. std::string body;
  3666. content_reader([&](const char *data, size_t data_length) {
  3667. body.append(data, data_length);
  3668. return true;
  3669. });
  3670. res.set_content(body, "text/plain");
  3671. })
  3672. .Patch("/patch-loopback",
  3673. [&](const Request &, Response &res,
  3674. ContentReader const &content_reader) {
  3675. std::string body;
  3676. content_reader([&](const char *data, size_t data_length) {
  3677. body.append(data, data_length);
  3678. return true;
  3679. });
  3680. res.set_content(body, "text/plain");
  3681. })
  3682. .Put("/empty-no-content-type",
  3683. [&](const Request &req, Response &res) {
  3684. EXPECT_EQ(req.body, "");
  3685. EXPECT_FALSE(req.has_header("Content-Type"));
  3686. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3687. res.set_content("empty-no-content-type", "text/plain");
  3688. })
  3689. .Put("/put",
  3690. [&](const Request &req, Response &res) {
  3691. EXPECT_EQ(req.body, "PUT");
  3692. res.set_content(req.body, "text/plain");
  3693. })
  3694. .Put("/put-large",
  3695. [&](const Request &req, Response &res) {
  3696. EXPECT_EQ(req.body, LARGE_DATA);
  3697. res.set_content(req.body, "text/plain");
  3698. })
  3699. .Patch("/patch",
  3700. [&](const Request &req, Response &res) {
  3701. EXPECT_EQ(req.body, "PATCH");
  3702. res.set_content(req.body, "text/plain");
  3703. })
  3704. .Delete("/delete",
  3705. [&](const Request & /*req*/, Response &res) {
  3706. res.set_content("DELETE", "text/plain");
  3707. })
  3708. .Delete("/delete-body",
  3709. [&](const Request &req, Response &res) {
  3710. EXPECT_EQ(req.body, "content");
  3711. res.set_content(req.body, "text/plain");
  3712. })
  3713. .Options(R"(\*)",
  3714. [&](const Request & /*req*/, Response &res) {
  3715. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3716. })
  3717. .Get("/request-target",
  3718. [&](const Request &req, Response & /*res*/) {
  3719. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3720. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3721. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3722. })
  3723. .Get("/long-query-value",
  3724. [&](const Request &req, Response & /*res*/) {
  3725. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3726. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3727. })
  3728. .Get("/too-long-query-value",
  3729. [&](const Request &req, Response & /*res*/) {
  3730. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3731. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3732. })
  3733. .Get("/array-param",
  3734. [&](const Request &req, Response & /*res*/) {
  3735. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3736. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3737. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3738. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3739. })
  3740. .Get("/array-param-values",
  3741. [&](const Request &req, Response & /*res*/) {
  3742. auto values = req.get_param_values("array");
  3743. EXPECT_EQ(3u, values.size());
  3744. EXPECT_EQ("value1", values[0]);
  3745. EXPECT_EQ("value2", values[1]);
  3746. EXPECT_EQ("value3", values[2]);
  3747. auto empty = req.get_param_values("nonexistent");
  3748. EXPECT_TRUE(empty.empty());
  3749. })
  3750. .Post("/validate-no-multiple-headers",
  3751. [&](const Request &req, Response & /*res*/) {
  3752. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3753. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3754. })
  3755. .Post("/content_receiver",
  3756. [&](const Request &req, Response &res,
  3757. const ContentReader &content_reader) {
  3758. if (req.is_multipart_form_data()) {
  3759. std::vector<FormData> items;
  3760. content_reader(
  3761. [&](const FormData &file) {
  3762. items.push_back(file);
  3763. return true;
  3764. },
  3765. [&](const char *data, size_t data_length) {
  3766. items.back().content.append(data, data_length);
  3767. return true;
  3768. });
  3769. EXPECT_EQ(5u, items.size());
  3770. {
  3771. const auto &file = get_file_value(items, "text1");
  3772. EXPECT_TRUE(file.filename.empty());
  3773. EXPECT_EQ("text default", file.content);
  3774. }
  3775. {
  3776. const auto &file = get_file_value(items, "text2");
  3777. EXPECT_TRUE(file.filename.empty());
  3778. EXPECT_EQ("aωb", file.content);
  3779. }
  3780. {
  3781. const auto &file = get_file_value(items, "file1");
  3782. EXPECT_EQ("hello.txt", file.filename);
  3783. EXPECT_EQ("text/plain", file.content_type);
  3784. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3785. }
  3786. {
  3787. const auto &file = get_file_value(items, "file2");
  3788. EXPECT_EQ("world.json", file.filename);
  3789. EXPECT_EQ("application/json", file.content_type);
  3790. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3791. }
  3792. {
  3793. const auto &file = get_file_value(items, "file3");
  3794. EXPECT_TRUE(file.filename.empty());
  3795. EXPECT_EQ("application/octet-stream", file.content_type);
  3796. EXPECT_EQ(0u, file.content.size());
  3797. }
  3798. } else {
  3799. std::string body;
  3800. content_reader([&](const char *data, size_t data_length) {
  3801. EXPECT_EQ(7U, data_length);
  3802. body.append(data, data_length);
  3803. return true;
  3804. });
  3805. EXPECT_EQ(body, "content");
  3806. res.set_content(body, "text/plain");
  3807. }
  3808. })
  3809. .Put("/content_receiver",
  3810. [&](const Request & /*req*/, Response &res,
  3811. const ContentReader &content_reader) {
  3812. std::string body;
  3813. content_reader([&](const char *data, size_t data_length) {
  3814. body.append(data, data_length);
  3815. return true;
  3816. });
  3817. EXPECT_EQ(body, "content");
  3818. res.set_content(body, "text/plain");
  3819. })
  3820. .Patch("/content_receiver",
  3821. [&](const Request & /*req*/, Response &res,
  3822. const ContentReader &content_reader) {
  3823. std::string body;
  3824. content_reader([&](const char *data, size_t data_length) {
  3825. body.append(data, data_length);
  3826. return true;
  3827. });
  3828. EXPECT_EQ(body, "content");
  3829. res.set_content(body, "text/plain");
  3830. })
  3831. .Post("/query-string-and-body",
  3832. [&](const Request &req, Response & /*res*/) {
  3833. ASSERT_TRUE(req.has_param("key"));
  3834. EXPECT_EQ(req.get_param_value("key"), "value");
  3835. EXPECT_EQ(req.body, "content");
  3836. })
  3837. .Get("/last-request",
  3838. [&](const Request &req, Response & /*res*/) {
  3839. EXPECT_EQ("close", req.get_header_value("Connection"));
  3840. })
  3841. .Get(R"(/redirect/(\d+))",
  3842. [&](const Request &req, Response &res) {
  3843. auto num = std::stoi(req.matches[1]) + 1;
  3844. std::string url = "/redirect/" + std::to_string(num);
  3845. res.set_redirect(url);
  3846. })
  3847. .Post("/binary",
  3848. [&](const Request &req, Response &res) {
  3849. EXPECT_EQ(4U, req.body.size());
  3850. EXPECT_EQ("application/octet-stream",
  3851. req.get_header_value("Content-Type"));
  3852. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3853. res.set_content(req.body, "application/octet-stream");
  3854. })
  3855. .Put("/binary",
  3856. [&](const Request &req, Response &res) {
  3857. EXPECT_EQ(4U, req.body.size());
  3858. EXPECT_EQ("application/octet-stream",
  3859. req.get_header_value("Content-Type"));
  3860. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3861. res.set_content(req.body, "application/octet-stream");
  3862. })
  3863. .Patch("/binary",
  3864. [&](const Request &req, Response &res) {
  3865. EXPECT_EQ(4U, req.body.size());
  3866. EXPECT_EQ("application/octet-stream",
  3867. req.get_header_value("Content-Type"));
  3868. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3869. res.set_content(req.body, "application/octet-stream");
  3870. })
  3871. .Delete("/binary",
  3872. [&](const Request &req, Response &res) {
  3873. EXPECT_EQ(4U, req.body.size());
  3874. EXPECT_EQ("application/octet-stream",
  3875. req.get_header_value("Content-Type"));
  3876. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3877. res.set_content(req.body, "application/octet-stream");
  3878. })
  3879. .Get("/issue1772",
  3880. [&](const Request & /*req*/, Response &res) {
  3881. res.status = 401;
  3882. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3883. })
  3884. .Delete("/issue609",
  3885. [](const httplib::Request &, httplib::Response &res,
  3886. const httplib::ContentReader &) {
  3887. res.set_content("ok", "text/plain");
  3888. })
  3889. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3890. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3891. .Get("/compress",
  3892. [&](const Request & /*req*/, Response &res) {
  3893. res.set_content(
  3894. "12345678901234567890123456789012345678901234567890123456789"
  3895. "01234567890123456789012345678901234567890",
  3896. "text/plain");
  3897. })
  3898. .Get("/compress-with-charset",
  3899. [&](const Request & /*req*/, Response &res) {
  3900. res.set_content(
  3901. "12345678901234567890123456789012345678901234567890123456789"
  3902. "01234567890123456789012345678901234567890",
  3903. "application/json; charset=utf-8");
  3904. })
  3905. .Get("/nocompress",
  3906. [&](const Request & /*req*/, Response &res) {
  3907. res.set_content(
  3908. "12345678901234567890123456789012345678901234567890123456789"
  3909. "01234567890123456789012345678901234567890",
  3910. "application/octet-stream");
  3911. })
  3912. .Post("/compress-multipart",
  3913. [&](const Request &req, Response & /*res*/) {
  3914. EXPECT_EQ(2u, req.form.fields.size());
  3915. ASSERT_TRUE(!req.form.has_field("???"));
  3916. {
  3917. const auto &text = req.form.get_field("key1");
  3918. EXPECT_EQ("test", text);
  3919. }
  3920. {
  3921. const auto &text = req.form.get_field("key2");
  3922. EXPECT_EQ("--abcdefg123", text);
  3923. }
  3924. })
  3925. #endif
  3926. ;
  3927. persons_["john"] = "programmer";
  3928. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3929. svr_.wait_until_ready();
  3930. }
  3931. virtual void TearDown() {
  3932. svr_.stop();
  3933. if (!request_threads_.empty()) {
  3934. std::this_thread::sleep_for(std::chrono::seconds(1));
  3935. for (auto &t : request_threads_) {
  3936. t.join();
  3937. }
  3938. }
  3939. t_.join();
  3940. }
  3941. map<string, string> persons_;
  3942. #ifdef CPPHTTPLIB_SSL_ENABLED
  3943. SSLClient cli_;
  3944. SSLServer svr_;
  3945. #else
  3946. Client cli_;
  3947. Server svr_;
  3948. #endif
  3949. thread t_;
  3950. std::vector<thread> request_threads_;
  3951. };
  3952. TEST_F(ServerTest, GetMethod200) {
  3953. auto res = cli_.Get("/hi");
  3954. ASSERT_TRUE(res);
  3955. EXPECT_EQ("HTTP/1.1", res->version);
  3956. EXPECT_EQ(StatusCode::OK_200, res->status);
  3957. EXPECT_EQ("OK", res->reason);
  3958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3959. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3960. EXPECT_EQ("Hello World!", res->body);
  3961. }
  3962. TEST_F(ServerTest, GetEmptyFile) {
  3963. auto res = cli_.Get("/empty_file");
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3967. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3968. EXPECT_EQ("", res->body);
  3969. }
  3970. TEST_F(ServerTest, GetFileContent) {
  3971. auto res = cli_.Get("/file_content");
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::OK_200, res->status);
  3974. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3975. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3976. EXPECT_EQ("test.html", res->body);
  3977. }
  3978. TEST_F(ServerTest, GetFileContentWithRange) {
  3979. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3980. ASSERT_TRUE(res);
  3981. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3982. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3983. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3984. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3985. EXPECT_EQ("est", res->body);
  3986. }
  3987. TEST_F(ServerTest, GetFileContentWithContentType) {
  3988. auto res = cli_.Get("/file_content_with_content_type");
  3989. ASSERT_TRUE(res);
  3990. EXPECT_EQ(StatusCode::OK_200, res->status);
  3991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3992. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3993. EXPECT_EQ("file\n", res->body);
  3994. }
  3995. TEST_F(ServerTest, GetInvalidFileContent) {
  3996. auto res = cli_.Get("/invalid_file_content");
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3999. }
  4000. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4001. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4002. ASSERT_TRUE(res);
  4003. EXPECT_EQ("HTTP/1.1", res->version);
  4004. EXPECT_EQ(StatusCode::OK_200, res->status);
  4005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4006. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4007. EXPECT_EQ("Hello World!", res->body);
  4008. }
  4009. TEST_F(ServerTest, GetMethod302) {
  4010. auto res = cli_.Get("/");
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::Found_302, res->status);
  4013. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4014. }
  4015. TEST_F(ServerTest, GetMethod302Redirect) {
  4016. cli_.set_follow_location(true);
  4017. auto res = cli_.Get("/");
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::OK_200, res->status);
  4020. EXPECT_EQ("Hello World!", res->body);
  4021. EXPECT_EQ("/hi", res->location);
  4022. }
  4023. TEST_F(ServerTest, GetMethod404) {
  4024. auto res = cli_.Get("/invalid");
  4025. ASSERT_TRUE(res);
  4026. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4027. }
  4028. TEST_F(ServerTest, HeadMethod200) {
  4029. auto res = cli_.Head("/hi");
  4030. ASSERT_TRUE(res);
  4031. EXPECT_EQ(StatusCode::OK_200, res->status);
  4032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4033. EXPECT_TRUE(res->body.empty());
  4034. }
  4035. TEST_F(ServerTest, HeadMethod200Static) {
  4036. auto res = cli_.Head("/mount/dir/index.html");
  4037. ASSERT_TRUE(res);
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4040. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4041. EXPECT_TRUE(res->body.empty());
  4042. }
  4043. TEST_F(ServerTest, HeadMethod404) {
  4044. auto res = cli_.Head("/invalid");
  4045. ASSERT_TRUE(res);
  4046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4047. EXPECT_TRUE(res->body.empty());
  4048. }
  4049. TEST_F(ServerTest, GetMethodPersonJohn) {
  4050. auto res = cli_.Get("/person/john");
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4054. EXPECT_EQ("programmer", res->body);
  4055. }
  4056. TEST_F(ServerTest, PostMethod1) {
  4057. auto res = cli_.Get("/person/john1");
  4058. ASSERT_TRUE(res);
  4059. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4060. res = cli_.Post("/person", "name=john1&note=coder",
  4061. "application/x-www-form-urlencoded");
  4062. ASSERT_TRUE(res);
  4063. ASSERT_EQ(StatusCode::OK_200, res->status);
  4064. res = cli_.Get("/person/john1");
  4065. ASSERT_TRUE(res);
  4066. ASSERT_EQ(StatusCode::OK_200, res->status);
  4067. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4068. ASSERT_EQ("coder", res->body);
  4069. }
  4070. TEST_F(ServerTest, PostMethod2) {
  4071. auto res = cli_.Get("/person/john2");
  4072. ASSERT_TRUE(res);
  4073. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4074. Params params;
  4075. params.emplace("name", "john2");
  4076. params.emplace("note", "coder");
  4077. res = cli_.Post("/person", params);
  4078. ASSERT_TRUE(res);
  4079. ASSERT_EQ(StatusCode::OK_200, res->status);
  4080. res = cli_.Get("/person/john2");
  4081. ASSERT_TRUE(res);
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4084. ASSERT_EQ("coder", res->body);
  4085. }
  4086. TEST_F(ServerTest, PutMethod3) {
  4087. auto res = cli_.Get("/person/john3");
  4088. ASSERT_TRUE(res);
  4089. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4090. Params params;
  4091. params.emplace("name", "john3");
  4092. params.emplace("note", "coder");
  4093. res = cli_.Put("/person", params);
  4094. ASSERT_TRUE(res);
  4095. ASSERT_EQ(StatusCode::OK_200, res->status);
  4096. res = cli_.Get("/person/john3");
  4097. ASSERT_TRUE(res);
  4098. ASSERT_EQ(StatusCode::OK_200, res->status);
  4099. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4100. ASSERT_EQ("coder", res->body);
  4101. }
  4102. TEST_F(ServerTest, DeleteMethod1) {
  4103. auto res = cli_.Get("/person/john4");
  4104. ASSERT_TRUE(res);
  4105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4106. Params params;
  4107. params.emplace("name", "john4");
  4108. params.emplace("note", "coder");
  4109. res = cli_.Post("/person", params);
  4110. ASSERT_TRUE(res);
  4111. ASSERT_EQ(StatusCode::OK_200, res->status);
  4112. res = cli_.Get("/person/john4");
  4113. ASSERT_TRUE(res);
  4114. ASSERT_EQ(StatusCode::OK_200, res->status);
  4115. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4116. ASSERT_EQ("coder", res->body);
  4117. Params delete_params;
  4118. delete_params.emplace("name", "john4");
  4119. res = cli_.Delete("/person", delete_params);
  4120. ASSERT_TRUE(res);
  4121. ASSERT_EQ(StatusCode::OK_200, res->status);
  4122. ASSERT_EQ("DELETED", res->body);
  4123. res = cli_.Get("/person/john4");
  4124. ASSERT_TRUE(res);
  4125. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4126. }
  4127. TEST_F(ServerTest, DeleteMethod2) {
  4128. auto res = cli_.Get("/person/john5");
  4129. ASSERT_TRUE(res);
  4130. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4131. Params params;
  4132. params.emplace("name", "john5");
  4133. params.emplace("note", "developer");
  4134. res = cli_.Post("/person", params);
  4135. ASSERT_TRUE(res);
  4136. ASSERT_EQ(StatusCode::OK_200, res->status);
  4137. res = cli_.Get("/person/john5");
  4138. ASSERT_TRUE(res);
  4139. ASSERT_EQ(StatusCode::OK_200, res->status);
  4140. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4141. ASSERT_EQ("developer", res->body);
  4142. Params delete_params;
  4143. delete_params.emplace("name", "john5");
  4144. Headers headers;
  4145. headers.emplace("Custom-Header", "test-value");
  4146. res = cli_.Delete("/person", headers, delete_params);
  4147. ASSERT_TRUE(res);
  4148. ASSERT_EQ(StatusCode::OK_200, res->status);
  4149. ASSERT_EQ("DELETED", res->body);
  4150. res = cli_.Get("/person/john5");
  4151. ASSERT_TRUE(res);
  4152. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4153. }
  4154. TEST_F(ServerTest, DeleteMethod3) {
  4155. auto res = cli_.Get("/person/john6");
  4156. ASSERT_TRUE(res);
  4157. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4158. Params params;
  4159. params.emplace("name", "john6");
  4160. params.emplace("note", "tester");
  4161. res = cli_.Post("/person", params);
  4162. ASSERT_TRUE(res);
  4163. ASSERT_EQ(StatusCode::OK_200, res->status);
  4164. res = cli_.Get("/person/john6");
  4165. ASSERT_TRUE(res);
  4166. ASSERT_EQ(StatusCode::OK_200, res->status);
  4167. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4168. ASSERT_EQ("tester", res->body);
  4169. Params delete_params;
  4170. delete_params.emplace("name", "john6");
  4171. Headers headers;
  4172. headers.emplace("Custom-Header", "test-value");
  4173. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4174. ASSERT_TRUE(res);
  4175. ASSERT_EQ(StatusCode::OK_200, res->status);
  4176. ASSERT_EQ("DELETED", res->body);
  4177. res = cli_.Get("/person/john6");
  4178. ASSERT_TRUE(res);
  4179. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4180. }
  4181. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4182. Params params;
  4183. params.emplace("json", JSON_DATA);
  4184. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4185. ASSERT_TRUE(res);
  4186. ASSERT_EQ(StatusCode::OK_200, res->status);
  4187. ASSERT_EQ(JSON_DATA, res->body);
  4188. }
  4189. TEST_F(ServerTest, PostEmptyContent) {
  4190. auto res = cli_.Post("/empty", "", "text/plain");
  4191. ASSERT_TRUE(res);
  4192. ASSERT_EQ(StatusCode::OK_200, res->status);
  4193. ASSERT_EQ("empty", res->body);
  4194. }
  4195. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4196. auto res = cli_.Post("/empty-no-content-type");
  4197. ASSERT_TRUE(res);
  4198. ASSERT_EQ(StatusCode::OK_200, res->status);
  4199. ASSERT_EQ("empty-no-content-type", res->body);
  4200. }
  4201. TEST_F(ServerTest, PostPathOnly) {
  4202. auto res = cli_.Post("/path-only");
  4203. ASSERT_TRUE(res);
  4204. ASSERT_EQ(StatusCode::OK_200, res->status);
  4205. ASSERT_EQ("path-only", res->body);
  4206. }
  4207. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4208. auto res = cli_.Post("/path-headers-only",
  4209. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4210. ASSERT_TRUE(res);
  4211. ASSERT_EQ(StatusCode::OK_200, res->status);
  4212. ASSERT_EQ("path-headers-only", res->body);
  4213. }
  4214. TEST_F(ServerTest, PostLarge) {
  4215. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4216. ASSERT_TRUE(res);
  4217. ASSERT_EQ(StatusCode::OK_200, res->status);
  4218. EXPECT_EQ(LARGE_DATA, res->body);
  4219. }
  4220. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4221. auto res = cli_.Put("/empty-no-content-type");
  4222. ASSERT_TRUE(res);
  4223. ASSERT_EQ(StatusCode::OK_200, res->status);
  4224. ASSERT_EQ("empty-no-content-type", res->body);
  4225. }
  4226. TEST_F(ServerTest, GetMethodDir) {
  4227. auto res = cli_.Get("/dir/");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4231. auto body = R"(<html>
  4232. <head>
  4233. </head>
  4234. <body>
  4235. <a href="/dir/test.html">Test</a>
  4236. <a href="/hi">hi</a>
  4237. </body>
  4238. </html>
  4239. )";
  4240. EXPECT_EQ(body, res->body);
  4241. }
  4242. TEST_F(ServerTest, GetMethodDirTest) {
  4243. auto res = cli_.Get("/dir/test.html");
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::OK_200, res->status);
  4246. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4247. EXPECT_EQ("test.html", res->body);
  4248. }
  4249. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4250. auto res = cli_.Get("/dir/../dir/test.html");
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::OK_200, res->status);
  4253. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4254. EXPECT_EQ("test.html", res->body);
  4255. }
  4256. TEST_F(ServerTest, GetMethodInvalidPath) {
  4257. auto res = cli_.Get("/dir/../test.html");
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4260. }
  4261. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4262. auto res = cli_.Get("/../www/dir/test.html");
  4263. ASSERT_TRUE(res);
  4264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4265. }
  4266. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4267. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4270. }
  4271. TEST_F(ServerTest, GetMethodDirMountTest) {
  4272. auto res = cli_.Get("/mount/dir/test.html");
  4273. ASSERT_TRUE(res);
  4274. EXPECT_EQ(StatusCode::OK_200, res->status);
  4275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4276. EXPECT_EQ("test.html", res->body);
  4277. }
  4278. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4279. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::OK_200, res->status);
  4282. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4283. EXPECT_EQ("test.html", res->body);
  4284. }
  4285. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4286. auto res = cli_.Get("/mount/dir/../test.html");
  4287. ASSERT_TRUE(res);
  4288. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4289. }
  4290. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4291. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4294. }
  4295. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4296. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4297. ASSERT_TRUE(res);
  4298. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4299. }
  4300. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4301. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4304. }
  4305. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4306. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4307. ASSERT_TRUE(res);
  4308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4309. }
  4310. TEST_F(ServerTest, PostMethod303) {
  4311. auto res = cli_.Post("/1", "body", "text/plain");
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4314. EXPECT_EQ("/2", res->get_header_value("Location"));
  4315. }
  4316. TEST_F(ServerTest, PostMethod303Redirect) {
  4317. cli_.set_follow_location(true);
  4318. auto res = cli_.Post("/1", "body", "text/plain");
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. EXPECT_EQ("redirected.", res->body);
  4322. EXPECT_EQ("/2", res->location);
  4323. }
  4324. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4325. auto res = cli_.Get("/dir/test.abcde");
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4329. EXPECT_EQ("abcde", res->body);
  4330. }
  4331. TEST_F(ServerTest, StaticFileRange) {
  4332. auto res =
  4333. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4334. ASSERT_TRUE(res);
  4335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4336. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4337. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4338. EXPECT_EQ(true, res->has_header("Content-Range"));
  4339. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4340. EXPECT_EQ(std::string("cd"), res->body);
  4341. }
  4342. TEST_F(ServerTest, StaticFileRanges) {
  4343. auto res = cli_.Get("/dir/test.abcde",
  4344. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4347. EXPECT_TRUE(
  4348. res->get_header_value("Content-Type")
  4349. .find(
  4350. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4351. 0);
  4352. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4353. }
  4354. TEST_F(ServerTest, StaticFileRangeHead) {
  4355. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4356. ASSERT_TRUE(res);
  4357. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4358. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4359. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4360. EXPECT_EQ(true, res->has_header("Content-Range"));
  4361. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4362. }
  4363. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4364. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4365. ASSERT_TRUE(res);
  4366. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4368. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4369. EXPECT_EQ(true, res->has_header("Content-Range"));
  4370. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4371. res->get_header_value("Content-Range"));
  4372. EXPECT_EQ("LAST\n", res->body);
  4373. }
  4374. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4375. auto res =
  4376. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4377. ASSERT_TRUE(res);
  4378. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4379. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4380. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4381. EXPECT_EQ(true, res->has_header("Content-Range"));
  4382. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4383. }
  4384. TEST_F(ServerTest, StaticFileBigFile) {
  4385. auto res = cli_.Get("/dir/1MB.txt");
  4386. ASSERT_TRUE(res);
  4387. EXPECT_EQ(StatusCode::OK_200, res->status);
  4388. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4389. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4390. }
  4391. TEST_F(ServerTest, InvalidBaseDirMount) {
  4392. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4393. }
  4394. TEST_F(ServerTest, Binary) {
  4395. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4396. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4397. "application/octet-stream");
  4398. ASSERT_TRUE(res);
  4399. ASSERT_EQ(StatusCode::OK_200, res->status);
  4400. ASSERT_EQ(4U, res->body.size());
  4401. res = cli_.Put("/binary", binary.data(), binary.size(),
  4402. "application/octet-stream");
  4403. ASSERT_TRUE(res);
  4404. ASSERT_EQ(StatusCode::OK_200, res->status);
  4405. ASSERT_EQ(4U, res->body.size());
  4406. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4407. "application/octet-stream");
  4408. ASSERT_TRUE(res);
  4409. ASSERT_EQ(StatusCode::OK_200, res->status);
  4410. ASSERT_EQ(4U, res->body.size());
  4411. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4412. "application/octet-stream");
  4413. ASSERT_TRUE(res);
  4414. ASSERT_EQ(StatusCode::OK_200, res->status);
  4415. ASSERT_EQ(4U, res->body.size());
  4416. }
  4417. TEST_F(ServerTest, BinaryString) {
  4418. auto binary = std::string("\x00\x01\x02\x03", 4);
  4419. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4420. ASSERT_TRUE(res);
  4421. ASSERT_EQ(StatusCode::OK_200, res->status);
  4422. ASSERT_EQ(4U, res->body.size());
  4423. res = cli_.Put("/binary", binary, "application/octet-stream");
  4424. ASSERT_TRUE(res);
  4425. ASSERT_EQ(StatusCode::OK_200, res->status);
  4426. ASSERT_EQ(4U, res->body.size());
  4427. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4428. ASSERT_TRUE(res);
  4429. ASSERT_EQ(StatusCode::OK_200, res->status);
  4430. ASSERT_EQ(4U, res->body.size());
  4431. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4432. ASSERT_TRUE(res);
  4433. ASSERT_EQ(StatusCode::OK_200, res->status);
  4434. ASSERT_EQ(4U, res->body.size());
  4435. }
  4436. TEST_F(ServerTest, EmptyRequest) {
  4437. auto res = cli_.Get("");
  4438. ASSERT_TRUE(!res);
  4439. EXPECT_EQ(Error::Connection, res.error());
  4440. }
  4441. TEST_F(ServerTest, LongRequest) {
  4442. std::string request;
  4443. for (size_t i = 0; i < 545; i++) {
  4444. request += "/TooLongRequest";
  4445. }
  4446. request += "OK";
  4447. auto res = cli_.Get(request.c_str());
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4450. }
  4451. TEST_F(ServerTest, TooLongRequest) {
  4452. std::string request;
  4453. for (size_t i = 0; i < 546; i++) {
  4454. request += "/TooLongRequest";
  4455. }
  4456. request += "_NG";
  4457. auto start = std::chrono::high_resolution_clock::now();
  4458. cli_.set_keep_alive(true);
  4459. auto res = cli_.Get(request.c_str());
  4460. auto end = std::chrono::high_resolution_clock::now();
  4461. auto elapsed =
  4462. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4463. .count();
  4464. ASSERT_TRUE(res);
  4465. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4466. EXPECT_LE(elapsed, 1000);
  4467. EXPECT_EQ("close", res->get_header_value("Connection"));
  4468. EXPECT_FALSE(cli_.is_socket_open());
  4469. }
  4470. TEST_F(ServerTest, AlmostTooLongRequest) {
  4471. // test for #2046 - URI length check shouldn't include other content on req
  4472. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4473. // leading /, space, HTTP/1.1)
  4474. std::string request =
  4475. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4476. auto res = cli_.Get(request.c_str());
  4477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4478. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4479. }
  4480. TEST_F(ServerTest, LongHeader) {
  4481. Request req;
  4482. req.method = "GET";
  4483. req.path = "/hi";
  4484. std::string host_and_port;
  4485. host_and_port += HOST;
  4486. host_and_port += ":";
  4487. host_and_port += std::to_string(PORT);
  4488. req.headers.emplace("Host", host_and_port.c_str());
  4489. req.headers.emplace("Accept", "*/*");
  4490. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4491. req.headers.emplace(
  4492. "Header-Name",
  4493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4494. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4495. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4521. "@@@@@@@@@@@@@@@@");
  4522. auto res = std::make_shared<Response>();
  4523. auto error = Error::Success;
  4524. auto ret = cli_.send(req, *res, error);
  4525. ASSERT_TRUE(ret);
  4526. EXPECT_EQ(StatusCode::OK_200, res->status);
  4527. }
  4528. TEST_F(ServerTest, LongQueryValue) {
  4529. auto start = std::chrono::high_resolution_clock::now();
  4530. cli_.set_keep_alive(true);
  4531. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4532. auto end = std::chrono::high_resolution_clock::now();
  4533. auto elapsed =
  4534. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4535. .count();
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4538. EXPECT_LE(elapsed, 1000);
  4539. EXPECT_EQ("close", res->get_header_value("Connection"));
  4540. EXPECT_FALSE(cli_.is_socket_open());
  4541. }
  4542. TEST_F(ServerTest, TooLongQueryValue) {
  4543. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4544. ASSERT_FALSE(res);
  4545. EXPECT_EQ(Error::Read, res.error());
  4546. }
  4547. TEST_F(ServerTest, TooLongHeader) {
  4548. Request req;
  4549. req.method = "GET";
  4550. req.path = "/hi";
  4551. std::string host_and_port;
  4552. host_and_port += HOST;
  4553. host_and_port += ":";
  4554. host_and_port += std::to_string(PORT);
  4555. req.headers.emplace("Host", host_and_port.c_str());
  4556. req.headers.emplace("Accept", "*/*");
  4557. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4558. req.headers.emplace(
  4559. "Header-Name",
  4560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4588. "@@@@@@@@@@@@@@@@@");
  4589. auto res = std::make_shared<Response>();
  4590. auto error = Error::Success;
  4591. auto ret = cli_.send(req, *res, error);
  4592. ASSERT_TRUE(ret);
  4593. EXPECT_EQ(StatusCode::OK_200, res->status);
  4594. }
  4595. TEST_F(ServerTest, HeaderCountAtLimit) {
  4596. // Test with headers just under the 100 limit
  4597. httplib::Headers headers;
  4598. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4599. // This should keep us just under the 100 header limit
  4600. for (int i = 0; i < 95; i++) {
  4601. std::string name = "X-Test-Header-" + std::to_string(i);
  4602. std::string value = "value" + std::to_string(i);
  4603. headers.emplace(name, value);
  4604. }
  4605. // This should work fine as we're under the limit
  4606. auto res = cli_.Get("/hi", headers);
  4607. EXPECT_TRUE(res);
  4608. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4609. }
  4610. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4611. // Test with many headers to exceed the 100 limit
  4612. httplib::Headers headers;
  4613. // Add 150 headers to definitely exceed the 100 limit
  4614. for (int i = 0; i < 150; i++) {
  4615. std::string name = "X-Test-Header-" + std::to_string(i);
  4616. std::string value = "value" + std::to_string(i);
  4617. headers.emplace(name, value);
  4618. }
  4619. // This should fail due to exceeding header count limit
  4620. cli_.set_keep_alive(true);
  4621. auto res = cli_.Get("/hi", headers);
  4622. // The server should respond with 400 Bad Request
  4623. ASSERT_TRUE(res);
  4624. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4625. EXPECT_EQ("close", res->get_header_value("Connection"));
  4626. EXPECT_FALSE(cli_.is_socket_open());
  4627. }
  4628. TEST_F(ServerTest, PercentEncoding) {
  4629. auto res = cli_.Get("/e%6edwith%");
  4630. ASSERT_TRUE(res);
  4631. EXPECT_EQ(StatusCode::OK_200, res->status);
  4632. }
  4633. TEST_F(ServerTest, PercentEncodingUnicode) {
  4634. auto res = cli_.Get("/e%u006edwith%");
  4635. ASSERT_TRUE(res);
  4636. EXPECT_EQ(StatusCode::OK_200, res->status);
  4637. }
  4638. TEST_F(ServerTest, InvalidPercentEncoding) {
  4639. auto res = cli_.Get("/%endwith%");
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4642. }
  4643. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4644. auto res = cli_.Get("/%uendwith%");
  4645. ASSERT_TRUE(res);
  4646. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4647. }
  4648. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4649. auto res = cli_.Get("/hello?aaa=bbb%");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4652. }
  4653. TEST_F(ServerTest, PlusSignEncoding) {
  4654. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. EXPECT_EQ("a +b", res->body);
  4658. }
  4659. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4660. // This test simulates a potential DoS attack using many headers
  4661. // to verify our security fix prevents memory exhaustion
  4662. httplib::Headers attack_headers;
  4663. // Attempt to add many headers like an attacker would (200 headers to far
  4664. // exceed limit)
  4665. for (int i = 0; i < 200; i++) {
  4666. std::string name = "X-Attack-Header-" + std::to_string(i);
  4667. std::string value = "attack_payload_" + std::to_string(i);
  4668. attack_headers.emplace(name, value);
  4669. }
  4670. // Try to POST with excessive headers
  4671. cli_.set_keep_alive(true);
  4672. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4673. // Should either fail or return 400 Bad Request due to security limit
  4674. if (res) {
  4675. // If we get a response, it should be 400 Bad Request
  4676. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4677. EXPECT_EQ("close", res->get_header_value("Connection"));
  4678. }
  4679. EXPECT_FALSE(cli_.is_socket_open());
  4680. }
  4681. TEST_F(ServerTest, MultipartFormData) {
  4682. UploadFormDataItems items = {
  4683. {"text1", "text default", "", ""},
  4684. {"text2", "aωb", "", ""},
  4685. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4686. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4687. {"file3", "", "", "application/octet-stream"},
  4688. {"file4", "", "", " application/json tmp-string "}};
  4689. auto res = cli_.Post("/multipart", items);
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. }
  4693. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4694. UploadFormDataItems items = {
  4695. {"text", "default text", "", ""},
  4696. {"multi_text1", "aaaaa", "", ""},
  4697. {"multi_text1", "bbbbb", "", ""},
  4698. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4699. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4700. "application/json"},
  4701. };
  4702. auto res = cli_.Post("/multipart/multi_file_values", items);
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. }
  4706. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4707. auto res = cli_.Get("/hi");
  4708. ASSERT_TRUE(res);
  4709. EXPECT_EQ(StatusCode::OK_200, res->status);
  4710. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4711. EXPECT_EQ("Hello World!", res->body);
  4712. }
  4713. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4714. Request req;
  4715. req.method = "POST";
  4716. req.path = "/chunked";
  4717. std::string host_and_port;
  4718. host_and_port += HOST;
  4719. host_and_port += ":";
  4720. host_and_port += std::to_string(PORT);
  4721. req.headers.emplace("Host", host_and_port.c_str());
  4722. req.headers.emplace("Accept", "*/*");
  4723. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4724. req.headers.emplace("Content-Type", "text/plain");
  4725. req.headers.emplace("Content-Length", "0");
  4726. req.headers.emplace(
  4727. "Transfer-Encoding",
  4728. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4729. // Client does not chunk, so make a chunked body manually.
  4730. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4731. auto res = std::make_shared<Response>();
  4732. auto error = Error::Success;
  4733. auto ret = cli_.send(req, *res, error);
  4734. ASSERT_TRUE(ret);
  4735. EXPECT_EQ(StatusCode::OK_200, res->status);
  4736. }
  4737. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4738. // rather than treat them as valid lengths.
  4739. template <typename ClientT>
  4740. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4741. Request req;
  4742. req.method = "POST";
  4743. req.path = "/chunked";
  4744. std::string host_and_port;
  4745. host_and_port += HOST;
  4746. host_and_port += ":";
  4747. host_and_port += std::to_string(PORT);
  4748. req.headers.emplace("Host", host_and_port.c_str());
  4749. req.headers.emplace("Content-Length", "0");
  4750. req.headers.emplace("Transfer-Encoding", "chunked");
  4751. req.body = body;
  4752. auto res = std::make_shared<Response>();
  4753. auto error = Error::Success;
  4754. ASSERT_TRUE(cli.send(req, *res, error));
  4755. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4756. }
  4757. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4758. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4759. }
  4760. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4761. expect_chunked_body_rejected(
  4762. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4763. }
  4764. TEST_F(ServerTest, GetStreamed2) {
  4765. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4766. ASSERT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4768. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4769. EXPECT_EQ(true, res->has_header("Content-Range"));
  4770. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4771. EXPECT_EQ(std::string("ab"), res->body);
  4772. }
  4773. TEST_F(ServerTest, GetStreamed) {
  4774. auto res = cli_.Get("/streamed");
  4775. ASSERT_TRUE(res);
  4776. EXPECT_EQ(StatusCode::OK_200, res->status);
  4777. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4778. EXPECT_EQ(std::string("aaabbb"), res->body);
  4779. }
  4780. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4781. auto res = cli_.Get("/streamed-without-length",
  4782. Headers{make_range_header({{0, -1}})});
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ(false, res->has_header("Content-Length"));
  4786. EXPECT_EQ(false, res->has_header("Content-Range"));
  4787. EXPECT_EQ(std::string("abcdefg"), res->body);
  4788. }
  4789. TEST_F(ServerTest, GetStreamedWithRange1) {
  4790. auto res =
  4791. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4792. ASSERT_TRUE(res);
  4793. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4794. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4795. EXPECT_EQ(true, res->has_header("Content-Range"));
  4796. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4797. EXPECT_EQ(std::string("def"), res->body);
  4798. }
  4799. TEST_F(ServerTest, GetStreamedWithRange2) {
  4800. auto res =
  4801. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4802. ASSERT_TRUE(res);
  4803. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4804. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4805. EXPECT_EQ(true, res->has_header("Content-Range"));
  4806. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4807. EXPECT_EQ(std::string("bcdefg"), res->body);
  4808. }
  4809. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4810. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4811. ASSERT_TRUE(res);
  4812. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4813. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4814. EXPECT_EQ(true, res->has_header("Content-Range"));
  4815. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4816. EXPECT_EQ(std::string("efg"), res->body);
  4817. }
  4818. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4819. auto res =
  4820. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4823. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4824. EXPECT_EQ(false, res->has_header("Content-Range"));
  4825. EXPECT_EQ(0U, res->body.size());
  4826. }
  4827. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4828. auto res =
  4829. cli_.Get("/streamed-with-range",
  4830. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4831. "92233720368547758079223372036854775807"}});
  4832. ASSERT_TRUE(res);
  4833. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4834. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4835. EXPECT_EQ(false, res->has_header("Content-Range"));
  4836. EXPECT_EQ(0U, res->body.size());
  4837. }
  4838. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4839. auto res = cli_.Get(
  4840. "/with-range",
  4841. Headers{{"Range",
  4842. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4843. {"Accept-Encoding", ""}});
  4844. ASSERT_TRUE(res);
  4845. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4846. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4847. EXPECT_EQ(true, res->has_header("Content-Range"));
  4848. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4849. EXPECT_EQ(std::string("abcdefg"), res->body);
  4850. }
  4851. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4852. auto res = cli_.Get("/with-range", Headers{
  4853. {"Range", "bytes=0-"},
  4854. {"Accept-Encoding", ""},
  4855. });
  4856. ASSERT_TRUE(res);
  4857. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4858. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4859. EXPECT_EQ(true, res->has_header("Content-Range"));
  4860. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4861. EXPECT_EQ(std::string("abcdefg"), res->body);
  4862. }
  4863. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4864. auto res = cli_.Get("/streamed-with-range",
  4865. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4866. ASSERT_TRUE(res);
  4867. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4868. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4869. EXPECT_EQ(false, res->has_header("Content-Range"));
  4870. EXPECT_EQ(267U, res->body.size());
  4871. // Check that both range contents are present
  4872. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4873. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4874. // Check that Content-Range headers are present for both ranges
  4875. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4876. std::string::npos);
  4877. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4878. std::string::npos);
  4879. }
  4880. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4881. Ranges ranges;
  4882. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4883. ranges.emplace_back(0, -1);
  4884. }
  4885. auto res = cli_.Get("/streamed-with-range?error",
  4886. Headers{{make_range_header(ranges)}});
  4887. ASSERT_TRUE(res);
  4888. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4889. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4890. EXPECT_EQ(false, res->has_header("Content-Range"));
  4891. EXPECT_EQ(0U, res->body.size());
  4892. }
  4893. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4894. auto res = cli_.Get("/streamed-with-range",
  4895. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4896. ASSERT_TRUE(res);
  4897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4898. EXPECT_EQ(5U, res->body.size());
  4899. // Check that overlapping ranges are coalesced into a single range
  4900. EXPECT_EQ("bcdef", res->body);
  4901. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4902. // Should be single range, not multipart
  4903. EXPECT_TRUE(res->has_header("Content-Range"));
  4904. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4905. }
  4906. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4907. auto res = cli_.Get("/streamed-with-range",
  4908. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4909. ASSERT_TRUE(res);
  4910. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4911. EXPECT_EQ(268U, res->body.size());
  4912. // Check that both range contents are present
  4913. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4914. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4915. // Check that Content-Range headers are present for both ranges
  4916. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4917. std::string::npos);
  4918. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4919. std::string::npos);
  4920. }
  4921. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4922. auto res = cli_.Get("/streamed-with-range",
  4923. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4926. EXPECT_EQ(269U, res->body.size());
  4927. // Check that both duplicate range contents are present
  4928. size_t first_abc = res->body.find("abc\r\n");
  4929. EXPECT_TRUE(first_abc != std::string::npos);
  4930. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4931. EXPECT_TRUE(second_abc != std::string::npos);
  4932. // Check that Content-Range headers are present for both ranges
  4933. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4934. EXPECT_TRUE(first_range != std::string::npos);
  4935. size_t second_range =
  4936. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4937. EXPECT_TRUE(second_range != std::string::npos);
  4938. }
  4939. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4940. auto res =
  4941. cli_.Get("/streamed-with-range?error",
  4942. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4945. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4946. EXPECT_EQ(false, res->has_header("Content-Range"));
  4947. EXPECT_EQ(0U, res->body.size());
  4948. }
  4949. TEST_F(ServerTest, GetStreamedEndless) {
  4950. uint64_t offset = 0;
  4951. auto res = cli_.Get("/streamed-cancel",
  4952. [&](const char * /*data*/, uint64_t data_length) {
  4953. if (offset < 100) {
  4954. offset += data_length;
  4955. return true;
  4956. }
  4957. return false;
  4958. });
  4959. ASSERT_TRUE(!res);
  4960. EXPECT_EQ(Error::Canceled, res.error());
  4961. }
  4962. TEST_F(ServerTest, ClientStop) {
  4963. std::atomic_size_t count{4};
  4964. std::vector<std::thread> threads;
  4965. for (auto i = count.load(); i != 0; --i) {
  4966. threads.emplace_back([&]() {
  4967. auto res = cli_.Get("/streamed-cancel",
  4968. [&](const char *, uint64_t) { return true; });
  4969. --count;
  4970. ASSERT_TRUE(!res);
  4971. EXPECT_TRUE(res.error() == Error::Canceled ||
  4972. res.error() == Error::Read || res.error() == Error::Write);
  4973. });
  4974. }
  4975. std::this_thread::sleep_for(std::chrono::seconds(2));
  4976. while (count != 0) {
  4977. cli_.stop();
  4978. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4979. }
  4980. for (auto &t : threads) {
  4981. t.join();
  4982. }
  4983. }
  4984. TEST_F(ServerTest, GetWithRange1) {
  4985. auto res = cli_.Get("/with-range", Headers{
  4986. make_range_header({{3, 5}}),
  4987. {"Accept-Encoding", ""},
  4988. });
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4991. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4992. EXPECT_EQ(true, res->has_header("Content-Range"));
  4993. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4994. EXPECT_EQ(std::string("def"), res->body);
  4995. }
  4996. TEST_F(ServerTest, GetWithRange2) {
  4997. auto res = cli_.Get("/with-range", Headers{
  4998. make_range_header({{1, -1}}),
  4999. {"Accept-Encoding", ""},
  5000. });
  5001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5003. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5004. EXPECT_EQ(true, res->has_header("Content-Range"));
  5005. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5006. EXPECT_EQ(std::string("bcdefg"), res->body);
  5007. }
  5008. TEST_F(ServerTest, GetWithRange3) {
  5009. auto res = cli_.Get("/with-range", Headers{
  5010. make_range_header({{0, 0}}),
  5011. {"Accept-Encoding", ""},
  5012. });
  5013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5014. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5015. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5016. EXPECT_EQ(true, res->has_header("Content-Range"));
  5017. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5018. EXPECT_EQ(std::string("a"), res->body);
  5019. }
  5020. TEST_F(ServerTest, GetWithRange4) {
  5021. auto res = cli_.Get("/with-range", Headers{
  5022. make_range_header({{-1, 2}}),
  5023. {"Accept-Encoding", ""},
  5024. });
  5025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5027. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5028. EXPECT_EQ(true, res->has_header("Content-Range"));
  5029. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5030. EXPECT_EQ(std::string("fg"), res->body);
  5031. }
  5032. TEST_F(ServerTest, GetWithRange5) {
  5033. auto res = cli_.Get("/with-range", Headers{
  5034. make_range_header({{0, 5}}),
  5035. {"Accept-Encoding", ""},
  5036. });
  5037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5039. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5040. EXPECT_EQ(true, res->has_header("Content-Range"));
  5041. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5042. EXPECT_EQ(std::string("abcdef"), res->body);
  5043. }
  5044. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5045. auto res =
  5046. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5047. ASSERT_TRUE(res);
  5048. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5049. }
  5050. TEST_F(ServerTest, GetWithRangeMultipart) {
  5051. auto res =
  5052. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5053. ASSERT_TRUE(res);
  5054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5055. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5056. EXPECT_EQ(false, res->has_header("Content-Range"));
  5057. EXPECT_EQ(267U, res->body.size());
  5058. }
  5059. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5060. auto res = cli_.Get("/with-range",
  5061. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5062. ASSERT_TRUE(res);
  5063. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5064. }
  5065. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5066. auto res = cli_.Get("/with-range-customized-response",
  5067. Headers{{make_range_header({{1, 2}})}});
  5068. ASSERT_TRUE(res);
  5069. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5070. EXPECT_EQ(true, res->has_header("Content-Length"));
  5071. EXPECT_EQ(false, res->has_header("Content-Range"));
  5072. EXPECT_EQ(JSON_DATA, res->body);
  5073. }
  5074. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5075. auto res = cli_.Get("/with-range-customized-response",
  5076. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5077. ASSERT_TRUE(res);
  5078. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5079. EXPECT_EQ(true, res->has_header("Content-Length"));
  5080. EXPECT_EQ(false, res->has_header("Content-Range"));
  5081. EXPECT_EQ(JSON_DATA, res->body);
  5082. }
  5083. TEST_F(ServerTest, Issue1772) {
  5084. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5085. ASSERT_TRUE(res);
  5086. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5087. }
  5088. TEST_F(ServerTest, Issue609) {
  5089. auto res = cli_.Delete("/issue609");
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ(StatusCode::OK_200, res->status);
  5092. EXPECT_EQ(std::string("ok"), res->body);
  5093. }
  5094. TEST_F(ServerTest, GetStreamedChunked) {
  5095. auto res = cli_.Get("/streamed-chunked");
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ(std::string("123456789"), res->body);
  5099. }
  5100. TEST_F(ServerTest, GetStreamedChunked2) {
  5101. auto res = cli_.Get("/streamed-chunked2");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ(std::string("123456789"), res->body);
  5105. }
  5106. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5107. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ(std::string("123456789"), res->body);
  5111. EXPECT_TRUE(res->has_header("Trailer"));
  5112. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5113. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5114. // Trailers are now stored separately from headers (security fix)
  5115. EXPECT_EQ(2U, res->trailers.size());
  5116. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5117. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5118. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5119. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5120. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5121. // Verify trailers are NOT in headers (security verification)
  5122. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5123. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5124. }
  5125. TEST_F(ServerTest, LargeChunkedPost) {
  5126. Request req;
  5127. req.method = "POST";
  5128. req.path = "/large-chunked";
  5129. std::string host_and_port;
  5130. host_and_port += HOST;
  5131. host_and_port += ":";
  5132. host_and_port += std::to_string(PORT);
  5133. req.headers.emplace("Host", host_and_port.c_str());
  5134. req.headers.emplace("Accept", "*/*");
  5135. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5136. req.headers.emplace("Content-Type", "text/plain");
  5137. req.headers.emplace("Content-Length", "0");
  5138. req.headers.emplace("Transfer-Encoding", "chunked");
  5139. std::string long_string(30 * 1024u, 'a');
  5140. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5141. // Attempt to make a large enough post to exceed OS buffers, to test that
  5142. // the server handles short reads if the full chunk data isn't available.
  5143. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5144. auto res = std::make_shared<Response>();
  5145. auto error = Error::Success;
  5146. auto ret = cli_.send(req, *res, error);
  5147. ASSERT_TRUE(ret);
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. }
  5150. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5151. auto res = cli_.Get("/remote_addr");
  5152. ASSERT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::OK_200, res->status);
  5154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5155. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5156. }
  5157. TEST_F(ServerTest, GetMethodLocalAddr) {
  5158. auto res = cli_.Get("/local_addr");
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ(StatusCode::OK_200, res->status);
  5161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5162. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5163. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5164. }
  5165. TEST_F(ServerTest, HTTPResponseSplitting) {
  5166. auto res = cli_.Get("/http_response_splitting");
  5167. ASSERT_TRUE(res);
  5168. EXPECT_EQ(StatusCode::OK_200, res->status);
  5169. }
  5170. TEST_F(ServerTest, SlowRequest) {
  5171. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5172. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5173. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5174. }
  5175. #if 0
  5176. TEST_F(ServerTest, SlowPost) {
  5177. char buffer[64 * 1024];
  5178. memset(buffer, 0x42, sizeof(buffer));
  5179. auto res = cli_.Post(
  5180. "/slowpost", 64 * 1024 * 1024,
  5181. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5182. auto ret = sink.write(buffer, sizeof(buffer));
  5183. EXPECT_TRUE(ret);
  5184. return true;
  5185. },
  5186. "text/plain");
  5187. ASSERT_TRUE(res);
  5188. EXPECT_EQ(StatusCode::OK_200, res->status);
  5189. }
  5190. TEST_F(ServerTest, SlowPostFail) {
  5191. char buffer[64 * 1024];
  5192. memset(buffer, 0x42, sizeof(buffer));
  5193. cli_.set_write_timeout(std::chrono::seconds(0));
  5194. auto res = cli_.Post(
  5195. "/slowpost", 64 * 1024 * 1024,
  5196. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5197. sink.write(buffer, sizeof(buffer));
  5198. return true;
  5199. },
  5200. "text/plain");
  5201. ASSERT_TRUE(!res);
  5202. EXPECT_EQ(Error::Write, res.error());
  5203. }
  5204. #endif
  5205. TEST_F(ServerTest, Put) {
  5206. auto res = cli_.Put("/put", "PUT", "text/plain");
  5207. ASSERT_TRUE(res);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. EXPECT_EQ("PUT", res->body);
  5210. }
  5211. TEST_F(ServerTest, PutWithContentProvider) {
  5212. auto res = cli_.Put(
  5213. "/put", 3,
  5214. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5215. sink.os << "PUT";
  5216. return true;
  5217. },
  5218. "text/plain");
  5219. ASSERT_TRUE(res);
  5220. EXPECT_EQ(StatusCode::OK_200, res->status);
  5221. EXPECT_EQ("PUT", res->body);
  5222. }
  5223. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5224. auto res = cli_.Post(
  5225. "/post", 42,
  5226. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5227. return false;
  5228. },
  5229. "text/plain");
  5230. ASSERT_TRUE(!res);
  5231. EXPECT_EQ(Error::Canceled, res.error());
  5232. }
  5233. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5234. auto res = cli_.Put(
  5235. "/put",
  5236. [](size_t /*offset*/, DataSink &sink) {
  5237. sink.os << "PUT";
  5238. sink.done();
  5239. return true;
  5240. },
  5241. "text/plain");
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. EXPECT_EQ("PUT", res->body);
  5245. }
  5246. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5247. auto res = cli_.Post(
  5248. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5249. "text/plain");
  5250. ASSERT_TRUE(!res);
  5251. EXPECT_EQ(Error::Canceled, res.error());
  5252. }
  5253. TEST_F(ServerTest, PostLoopBack) {
  5254. std::string body;
  5255. auto res = cli_.Post(
  5256. "/post-loopback", 9,
  5257. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5258. EXPECT_EQ(9u, length);
  5259. sink.write("123", 3);
  5260. sink.write("456", 3);
  5261. sink.write("789", 3);
  5262. return true;
  5263. },
  5264. "text/plain",
  5265. [&body](const char *data, size_t data_length) {
  5266. body.append(data, data_length);
  5267. return true;
  5268. });
  5269. ASSERT_TRUE(res);
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("123456789", body);
  5272. }
  5273. TEST_F(ServerTest, PutLoopBack) {
  5274. std::string body;
  5275. auto res = cli_.Put(
  5276. "/put-loopback", 9,
  5277. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5278. EXPECT_EQ(9u, length);
  5279. sink.write("123", 3);
  5280. sink.write("456", 3);
  5281. sink.write("789", 3);
  5282. return true;
  5283. },
  5284. "text/plain",
  5285. [&body](const char *data, size_t data_length) {
  5286. body.append(data, data_length);
  5287. return true;
  5288. });
  5289. ASSERT_TRUE(res);
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. EXPECT_EQ("123456789", body);
  5292. }
  5293. TEST_F(ServerTest, PatchLoopBack) {
  5294. std::string body;
  5295. auto res = cli_.Patch(
  5296. "/patch-loopback", 9,
  5297. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5298. EXPECT_EQ(9u, length);
  5299. sink.write("123", 3);
  5300. sink.write("456", 3);
  5301. sink.write("789", 3);
  5302. return true;
  5303. },
  5304. "text/plain",
  5305. [&body](const char *data, size_t data_length) {
  5306. body.append(data, data_length);
  5307. return true;
  5308. });
  5309. ASSERT_TRUE(res);
  5310. EXPECT_EQ(StatusCode::OK_200, res->status);
  5311. EXPECT_EQ("123456789", body);
  5312. }
  5313. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5314. std::string body;
  5315. auto res = cli_.Post(
  5316. "/post-loopback",
  5317. [](size_t /*offset*/, DataSink &sink) {
  5318. sink.write("123", 3);
  5319. sink.write("456", 3);
  5320. sink.write("789", 3);
  5321. sink.done();
  5322. return true;
  5323. },
  5324. "text/plain",
  5325. [&body](const char *data, size_t data_length) {
  5326. body.append(data, data_length);
  5327. return true;
  5328. });
  5329. ASSERT_TRUE(res);
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. EXPECT_EQ("123456789", body);
  5332. }
  5333. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5334. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5335. cli_.set_compress(true);
  5336. auto res = cli_.Put(
  5337. "/put", 3,
  5338. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5339. sink.os << "PUT";
  5340. return true;
  5341. },
  5342. "text/plain");
  5343. ASSERT_TRUE(res);
  5344. EXPECT_EQ(StatusCode::OK_200, res->status);
  5345. EXPECT_EQ("PUT", res->body);
  5346. }
  5347. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5348. cli_.set_compress(true);
  5349. auto res = cli_.Post(
  5350. "/post", 42,
  5351. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5352. return false;
  5353. },
  5354. "text/plain");
  5355. ASSERT_TRUE(!res);
  5356. EXPECT_EQ(Error::Canceled, res.error());
  5357. }
  5358. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5359. cli_.set_compress(true);
  5360. auto res = cli_.Put(
  5361. "/put",
  5362. [](size_t /*offset*/, DataSink &sink) {
  5363. sink.os << "PUT";
  5364. sink.done();
  5365. return true;
  5366. },
  5367. "text/plain");
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. EXPECT_EQ("PUT", res->body);
  5371. }
  5372. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5373. cli_.set_compress(true);
  5374. auto res = cli_.Post(
  5375. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5376. "text/plain");
  5377. ASSERT_TRUE(!res);
  5378. EXPECT_EQ(Error::Canceled, res.error());
  5379. }
  5380. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5381. cli_.set_compress(true);
  5382. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5383. ASSERT_TRUE(res);
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. EXPECT_EQ(LARGE_DATA, res->body);
  5386. }
  5387. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5388. #ifdef CPPHTTPLIB_SSL_ENABLED
  5389. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5390. Client cli(s.c_str());
  5391. cli.enable_server_certificate_verification(false);
  5392. #else
  5393. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5394. Client cli(s.c_str());
  5395. #endif
  5396. cli.set_compress(true);
  5397. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5398. ASSERT_TRUE(res);
  5399. EXPECT_EQ(StatusCode::OK_200, res->status);
  5400. EXPECT_EQ(LARGE_DATA, res->body);
  5401. // The compressed size should be less than a 10th of the original. May vary
  5402. // depending on the zlib library.
  5403. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5404. static_cast<uint64_t>(10 * 1024 * 1024));
  5405. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5406. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5407. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5408. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5409. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5410. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5411. #endif
  5412. }
  5413. TEST_F(ServerTest, PutContentWithDeflate) {
  5414. cli_.set_compress(false);
  5415. Headers headers;
  5416. headers.emplace("Content-Encoding", "deflate");
  5417. // PUT in deflate format:
  5418. auto res = cli_.Put("/put", headers,
  5419. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5420. ASSERT_TRUE(res);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. EXPECT_EQ("PUT", res->body);
  5423. }
  5424. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5425. Headers headers;
  5426. headers.emplace("Accept-Encoding", "gzip, deflate");
  5427. auto res = cli_.Get("/streamed-chunked", headers);
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ(std::string("123456789"), res->body);
  5431. }
  5432. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5433. Headers headers;
  5434. headers.emplace("Accept-Encoding", "gzip, deflate");
  5435. auto res = cli_.Get("/streamed-chunked2", headers);
  5436. ASSERT_TRUE(res);
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. EXPECT_EQ(std::string("123456789"), res->body);
  5439. }
  5440. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5441. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5442. ASSERT_TRUE(res);
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. }
  5445. TEST(GzipDecompressor, ChunkedDecompression) {
  5446. std::string data;
  5447. for (size_t i = 0; i < 32 * 1024; ++i) {
  5448. data.push_back(static_cast<char>('a' + i % 26));
  5449. }
  5450. std::string compressed_data;
  5451. {
  5452. httplib::detail::gzip_compressor compressor;
  5453. bool result = compressor.compress(
  5454. data.data(), data.size(),
  5455. /*last=*/true,
  5456. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5457. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5458. compressed_data_size);
  5459. return true;
  5460. });
  5461. ASSERT_TRUE(result);
  5462. }
  5463. std::string decompressed_data;
  5464. {
  5465. httplib::detail::gzip_decompressor decompressor;
  5466. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5467. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5468. size_t chunk_size = 130;
  5469. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5470. chunk_begin += chunk_size) {
  5471. size_t current_chunk_size =
  5472. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5473. bool result = decompressor.decompress(
  5474. compressed_data.data() + chunk_begin, current_chunk_size,
  5475. [&](const char *decompressed_data_chunk,
  5476. size_t decompressed_data_chunk_size) {
  5477. decompressed_data.insert(decompressed_data.size(),
  5478. decompressed_data_chunk,
  5479. decompressed_data_chunk_size);
  5480. return true;
  5481. });
  5482. ASSERT_TRUE(result);
  5483. }
  5484. }
  5485. ASSERT_EQ(data, decompressed_data);
  5486. }
  5487. TEST(GzipDecompressor, DeflateDecompression) {
  5488. std::string original_text = "Raw deflate without gzip";
  5489. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5490. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5491. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5492. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5493. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5494. std::string decompressed_data;
  5495. {
  5496. httplib::detail::gzip_decompressor decompressor;
  5497. bool result = decompressor.decompress(
  5498. compressed_data.data(), compressed_data.size(),
  5499. [&](const char *decompressed_data_chunk,
  5500. size_t decompressed_data_chunk_size) {
  5501. decompressed_data.insert(decompressed_data.size(),
  5502. decompressed_data_chunk,
  5503. decompressed_data_chunk_size);
  5504. return true;
  5505. });
  5506. ASSERT_TRUE(result);
  5507. }
  5508. ASSERT_EQ(original_text, decompressed_data);
  5509. }
  5510. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5511. std::string original_text = "Raw deflate without gzip";
  5512. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5513. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5514. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5515. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5516. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5517. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5518. std::string decompressed_data;
  5519. {
  5520. httplib::detail::gzip_decompressor decompressor;
  5521. bool result = decompressor.decompress(
  5522. compressed_data.data(), compressed_data.size(),
  5523. [&](const char *decompressed_data_chunk,
  5524. size_t decompressed_data_chunk_size) {
  5525. decompressed_data.insert(decompressed_data.size(),
  5526. decompressed_data_chunk,
  5527. decompressed_data_chunk_size);
  5528. return true;
  5529. });
  5530. ASSERT_TRUE(result);
  5531. }
  5532. ASSERT_EQ(original_text, decompressed_data);
  5533. }
  5534. #endif
  5535. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5536. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5537. Headers headers;
  5538. headers.emplace("Accept-Encoding", "br");
  5539. auto res = cli_.Get("/streamed-chunked", headers);
  5540. ASSERT_TRUE(res);
  5541. EXPECT_EQ(StatusCode::OK_200, res->status);
  5542. EXPECT_EQ(std::string("123456789"), res->body);
  5543. }
  5544. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5545. Headers headers;
  5546. headers.emplace("Accept-Encoding", "br");
  5547. auto res = cli_.Get("/streamed-chunked2", headers);
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ(std::string("123456789"), res->body);
  5551. }
  5552. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5553. cli_.set_compress(true);
  5554. auto res = cli_.Put(
  5555. "/put", 3,
  5556. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5557. sink.os << "PUT";
  5558. return true;
  5559. },
  5560. "text/plain");
  5561. ASSERT_TRUE(res);
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. EXPECT_EQ("PUT", res->body);
  5564. }
  5565. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5566. cli_.set_compress(true);
  5567. auto res = cli_.Put(
  5568. "/put",
  5569. [](size_t /*offset*/, DataSink &sink) {
  5570. sink.os << "PUT";
  5571. sink.done();
  5572. return true;
  5573. },
  5574. "text/plain");
  5575. ASSERT_TRUE(res);
  5576. EXPECT_EQ(StatusCode::OK_200, res->status);
  5577. EXPECT_EQ("PUT", res->body);
  5578. }
  5579. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5580. cli_.set_compress(true);
  5581. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5582. ASSERT_TRUE(res);
  5583. EXPECT_EQ(StatusCode::OK_200, res->status);
  5584. EXPECT_EQ(LARGE_DATA, res->body);
  5585. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5586. }
  5587. #endif
  5588. TEST_F(ServerTest, Patch) {
  5589. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5590. ASSERT_TRUE(res);
  5591. EXPECT_EQ(StatusCode::OK_200, res->status);
  5592. EXPECT_EQ("PATCH", res->body);
  5593. }
  5594. TEST_F(ServerTest, Delete) {
  5595. auto res = cli_.Delete("/delete");
  5596. ASSERT_TRUE(res);
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. EXPECT_EQ("DELETE", res->body);
  5599. }
  5600. TEST_F(ServerTest, DeleteContentReceiver) {
  5601. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ("content", res->body);
  5605. }
  5606. TEST_F(ServerTest, Options) {
  5607. auto res = cli_.Options("*");
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5611. EXPECT_TRUE(res->body.empty());
  5612. }
  5613. TEST_F(ServerTest, URL) {
  5614. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5615. ASSERT_TRUE(res);
  5616. EXPECT_EQ(StatusCode::OK_200, res->status);
  5617. }
  5618. TEST_F(ServerTest, ArrayParam) {
  5619. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5620. ASSERT_TRUE(res);
  5621. EXPECT_EQ(StatusCode::OK_200, res->status);
  5622. }
  5623. TEST_F(ServerTest, ArrayParamValues) {
  5624. auto res =
  5625. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST_F(ServerTest, NoMultipleHeaders) {
  5630. Headers headers = {{"Content-Length", "5"}};
  5631. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5632. "text/plain");
  5633. ASSERT_TRUE(res);
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. }
  5636. TEST_F(ServerTest, PostContentReceiver) {
  5637. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5638. ASSERT_TRUE(res);
  5639. ASSERT_EQ(StatusCode::OK_200, res->status);
  5640. ASSERT_EQ("content", res->body);
  5641. }
  5642. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5643. UploadFormDataItems items = {
  5644. {"text1", "text default", "", ""},
  5645. {"text2", "aωb", "", ""},
  5646. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5647. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5648. {"file3", "", "", "application/octet-stream"},
  5649. };
  5650. auto res = cli_.Post("/content_receiver", items);
  5651. ASSERT_TRUE(res);
  5652. EXPECT_EQ(StatusCode::OK_200, res->status);
  5653. }
  5654. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5655. UploadFormDataItems items = {
  5656. {"text1", "text default", "", ""},
  5657. {"text2", "aωb", "", ""},
  5658. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5659. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5660. {"file3", "", "", "application/octet-stream"},
  5661. };
  5662. auto boundary = std::string("+++++");
  5663. std::string body;
  5664. for (const auto &item : items) {
  5665. body += "--" + boundary + "\r\n";
  5666. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5667. if (!item.filename.empty()) {
  5668. body += "; filename=\"" + item.filename + "\"";
  5669. }
  5670. body += "\r\n";
  5671. if (!item.content_type.empty()) {
  5672. body += "Content-Type: " + item.content_type + "\r\n";
  5673. }
  5674. body += "\r\n";
  5675. body += item.content + "\r\n";
  5676. }
  5677. body += "--" + boundary + "--\r\n";
  5678. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5679. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5680. ASSERT_TRUE(res);
  5681. EXPECT_EQ(StatusCode::OK_200, res->status);
  5682. }
  5683. TEST(MultipartFormDataTest, FieldEscaping) {
  5684. Server svr;
  5685. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5686. const ContentReader &content_reader) {
  5687. ASSERT_TRUE(req.is_multipart_form_data());
  5688. std::vector<FormData> received;
  5689. content_reader(
  5690. [&](const FormData &file) {
  5691. received.push_back(file);
  5692. return true;
  5693. },
  5694. [&](const char *data, size_t data_length) {
  5695. received.back().content.append(data, data_length);
  5696. return true;
  5697. });
  5698. // '"', CR and LF in names and filenames are escaped following the
  5699. // WHATWG HTML standard, so each part still parses as a single part
  5700. // with no injected headers. Content types get CR/LF escaped too,
  5701. // while '"' (legal there, e.g. quoted charset) is preserved.
  5702. ASSERT_EQ(4U, received.size());
  5703. EXPECT_EQ("na%22me", received[0].name);
  5704. EXPECT_EQ("quoted name", received[0].content);
  5705. EXPECT_EQ("file", received[1].name);
  5706. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5707. received[1].filename);
  5708. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5709. EXPECT_EQ("injected", received[1].content);
  5710. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5711. EXPECT_EQ("my%22file.txt", received[2].filename);
  5712. EXPECT_EQ("cr lf name", received[2].content);
  5713. EXPECT_EQ("typed", received[3].name);
  5714. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5715. received[3].content_type);
  5716. EXPECT_EQ("typed content", received[3].content);
  5717. });
  5718. auto port = svr.bind_to_any_port("localhost");
  5719. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5720. auto se = detail::scope_exit([&] {
  5721. svr.stop();
  5722. t.join();
  5723. ASSERT_FALSE(svr.is_running());
  5724. });
  5725. svr.wait_until_ready();
  5726. Client cli("localhost", port);
  5727. UploadFormDataItems items = {
  5728. {"na\"me", "quoted name", "", ""},
  5729. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5730. "application/octet-stream"},
  5731. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5732. {"typed", "typed content", "",
  5733. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5734. };
  5735. auto res = cli.Post("/post", items);
  5736. ASSERT_TRUE(res);
  5737. EXPECT_EQ(StatusCode::OK_200, res->status);
  5738. }
  5739. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5740. const UploadFormDataItems items = {
  5741. {"name1", "Content 1", "", ""},
  5742. {"name2", "Content 2", "file2.txt", "text/plain"},
  5743. };
  5744. Server svr;
  5745. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5746. const ContentReader &content_reader) {
  5747. ASSERT_TRUE(req.is_multipart_form_data());
  5748. std::vector<FormData> received;
  5749. content_reader(
  5750. [&](const FormData &file) {
  5751. received.push_back(file);
  5752. return true;
  5753. },
  5754. [&](const char *data, size_t data_length) {
  5755. received.back().content.append(data, data_length);
  5756. return true;
  5757. });
  5758. ASSERT_EQ(2U, received.size());
  5759. EXPECT_EQ("name1", received[0].name);
  5760. EXPECT_EQ("Content 1", received[0].content);
  5761. EXPECT_EQ("name2", received[1].name);
  5762. EXPECT_EQ("Content 2", received[1].content);
  5763. EXPECT_EQ("file2.txt", received[1].filename);
  5764. EXPECT_EQ("text/plain", received[1].content_type);
  5765. });
  5766. auto port = svr.bind_to_any_port("localhost");
  5767. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5768. auto se = detail::scope_exit([&] {
  5769. svr.stop();
  5770. t.join();
  5771. ASSERT_FALSE(svr.is_running());
  5772. });
  5773. svr.wait_until_ready();
  5774. Client cli("localhost", port);
  5775. // Whole-body serialization with a generated boundary
  5776. {
  5777. MultipartFormDataWriter writer;
  5778. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5779. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5780. writer.content_type());
  5781. auto body = writer.serialize(items);
  5782. EXPECT_EQ(body.size(), writer.content_length(items));
  5783. auto res = cli.Post("/post", body, writer.content_type());
  5784. ASSERT_TRUE(res);
  5785. EXPECT_EQ(StatusCode::OK_200, res->status);
  5786. }
  5787. // Per-part framing with a custom boundary via a content provider
  5788. {
  5789. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5790. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5791. MultipartFormDataWriter writer("custom-boundary_123");
  5792. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5793. std::string body;
  5794. for (const auto &item : items) {
  5795. body += writer.item_begin(item);
  5796. body += item.content;
  5797. body += MultipartFormDataWriter::item_end();
  5798. }
  5799. body += writer.finish();
  5800. EXPECT_EQ(body.size(), writer.content_length(items));
  5801. auto res = cli.Post(
  5802. "/post", body.size(),
  5803. [&](size_t offset, size_t length, DataSink &sink) {
  5804. sink.write(body.data() + offset, length);
  5805. return true;
  5806. },
  5807. writer.content_type());
  5808. ASSERT_TRUE(res);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. }
  5811. }
  5812. TEST_F(ServerTest, PostContentReceiverGzip) {
  5813. cli_.set_compress(true);
  5814. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5815. ASSERT_TRUE(res);
  5816. ASSERT_EQ(StatusCode::OK_200, res->status);
  5817. ASSERT_EQ("content", res->body);
  5818. }
  5819. TEST_F(ServerTest, PutContentReceiver) {
  5820. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5821. ASSERT_TRUE(res);
  5822. ASSERT_EQ(StatusCode::OK_200, res->status);
  5823. ASSERT_EQ("content", res->body);
  5824. }
  5825. TEST_F(ServerTest, PatchContentReceiver) {
  5826. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5827. ASSERT_TRUE(res);
  5828. ASSERT_EQ(StatusCode::OK_200, res->status);
  5829. ASSERT_EQ("content", res->body);
  5830. }
  5831. template <typename ClientType>
  5832. void TestWithHeadersAndContentReceiver(
  5833. ClientType &cli,
  5834. std::function<Result(ClientType &, const std::string &, const Headers &,
  5835. const std::string &, const std::string &,
  5836. ContentReceiver, DownloadProgress)>
  5837. request_func) {
  5838. Headers headers;
  5839. headers.emplace("X-Custom-Header", "test-value");
  5840. std::string received_body;
  5841. auto res = request_func(
  5842. cli, "/content_receiver", headers, "content", "application/json",
  5843. [&](const char *data, size_t data_length) {
  5844. received_body.append(data, data_length);
  5845. return true;
  5846. },
  5847. nullptr);
  5848. ASSERT_TRUE(res);
  5849. EXPECT_EQ(StatusCode::OK_200, res->status);
  5850. EXPECT_EQ("content", received_body);
  5851. }
  5852. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5853. #ifdef CPPHTTPLIB_SSL_ENABLED
  5854. using ClientT = SSLClient;
  5855. #else
  5856. using ClientT = Client;
  5857. #endif
  5858. TestWithHeadersAndContentReceiver<ClientT>(
  5859. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5860. const std::string &body, const std::string &content_type,
  5861. ContentReceiver receiver, DownloadProgress progress) {
  5862. return cli.Post(path, headers, body, content_type, receiver, progress);
  5863. });
  5864. }
  5865. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5866. #ifdef CPPHTTPLIB_SSL_ENABLED
  5867. using ClientT = SSLClient;
  5868. #else
  5869. using ClientT = Client;
  5870. #endif
  5871. TestWithHeadersAndContentReceiver<ClientT>(
  5872. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5873. const std::string &body, const std::string &content_type,
  5874. ContentReceiver receiver, DownloadProgress progress) {
  5875. return cli.Put(path, headers, body, content_type, receiver, progress);
  5876. });
  5877. }
  5878. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5879. #ifdef CPPHTTPLIB_SSL_ENABLED
  5880. using ClientT = SSLClient;
  5881. #else
  5882. using ClientT = Client;
  5883. #endif
  5884. TestWithHeadersAndContentReceiver<ClientT>(
  5885. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5886. const std::string &body, const std::string &content_type,
  5887. ContentReceiver receiver, DownloadProgress progress) {
  5888. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5889. });
  5890. }
  5891. template <typename ClientType>
  5892. void TestWithHeadersAndContentReceiverWithProgress(
  5893. ClientType &cli,
  5894. std::function<Result(ClientType &, const std::string &, const Headers &,
  5895. const std::string &, const std::string &,
  5896. ContentReceiver, DownloadProgress)>
  5897. request_func) {
  5898. Headers headers;
  5899. headers.emplace("X-Test-Header", "progress-test");
  5900. std::string received_body;
  5901. auto progress_called = false;
  5902. auto res = request_func(
  5903. cli, "/content_receiver", headers, "content", "text/plain",
  5904. [&](const char *data, size_t data_length) {
  5905. received_body.append(data, data_length);
  5906. return true;
  5907. },
  5908. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5909. progress_called = true;
  5910. return true;
  5911. });
  5912. ASSERT_TRUE(res);
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. EXPECT_EQ("content", received_body);
  5915. EXPECT_TRUE(progress_called);
  5916. }
  5917. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5918. #ifdef CPPHTTPLIB_SSL_ENABLED
  5919. using ClientT = SSLClient;
  5920. #else
  5921. using ClientT = Client;
  5922. #endif
  5923. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5924. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5925. const std::string &body, const std::string &content_type,
  5926. ContentReceiver receiver, DownloadProgress progress) {
  5927. return cli.Post(path, headers, body, content_type, receiver, progress);
  5928. });
  5929. }
  5930. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5931. #ifdef CPPHTTPLIB_SSL_ENABLED
  5932. using ClientT = SSLClient;
  5933. #else
  5934. using ClientT = Client;
  5935. #endif
  5936. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5937. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5938. const std::string &body, const std::string &content_type,
  5939. ContentReceiver receiver, DownloadProgress progress) {
  5940. return cli.Put(path, headers, body, content_type, receiver, progress);
  5941. });
  5942. }
  5943. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5944. #ifdef CPPHTTPLIB_SSL_ENABLED
  5945. using ClientT = SSLClient;
  5946. #else
  5947. using ClientT = Client;
  5948. #endif
  5949. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5950. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5951. const std::string &body, const std::string &content_type,
  5952. ContentReceiver receiver, DownloadProgress progress) {
  5953. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5954. });
  5955. }
  5956. template <typename ClientType>
  5957. void TestWithHeadersAndContentReceiverError(
  5958. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5959. const Headers &, const std::string &,
  5960. const std::string &, ContentReceiver)>
  5961. request_func) {
  5962. Headers headers;
  5963. headers.emplace("X-Error-Test", "true");
  5964. std::string received_body;
  5965. auto receiver_failed = false;
  5966. auto res =
  5967. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5968. [&](const char *data, size_t data_length) {
  5969. received_body.append(data, data_length);
  5970. receiver_failed = true;
  5971. return false;
  5972. });
  5973. ASSERT_FALSE(res);
  5974. EXPECT_TRUE(receiver_failed);
  5975. }
  5976. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5977. #ifdef CPPHTTPLIB_SSL_ENABLED
  5978. using ClientT = SSLClient;
  5979. #else
  5980. using ClientT = Client;
  5981. #endif
  5982. TestWithHeadersAndContentReceiverError<ClientT>(
  5983. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5984. const std::string &body, const std::string &content_type,
  5985. ContentReceiver receiver) {
  5986. return cli.Post(path, headers, body, content_type, receiver);
  5987. });
  5988. }
  5989. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5990. #ifdef CPPHTTPLIB_SSL_ENABLED
  5991. using ClientT = SSLClient;
  5992. #else
  5993. using ClientT = Client;
  5994. #endif
  5995. TestWithHeadersAndContentReceiverError<ClientT>(
  5996. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5997. const std::string &body, const std::string &content_type,
  5998. ContentReceiver receiver) {
  5999. return cli.Put(path, headers, body, content_type, receiver);
  6000. });
  6001. }
  6002. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6003. #ifdef CPPHTTPLIB_SSL_ENABLED
  6004. using ClientT = SSLClient;
  6005. #else
  6006. using ClientT = Client;
  6007. #endif
  6008. TestWithHeadersAndContentReceiverError<ClientT>(
  6009. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6010. const std::string &body, const std::string &content_type,
  6011. ContentReceiver receiver) {
  6012. return cli.Patch(path, headers, body, content_type, receiver);
  6013. });
  6014. }
  6015. TEST_F(ServerTest, PostQueryStringAndBody) {
  6016. auto res =
  6017. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6018. ASSERT_TRUE(res);
  6019. ASSERT_EQ(StatusCode::OK_200, res->status);
  6020. }
  6021. TEST_F(ServerTest, HTTP2Magic) {
  6022. Request req;
  6023. req.method = "PRI";
  6024. req.path = "*";
  6025. req.body = "SM";
  6026. auto res = std::make_shared<Response>();
  6027. auto error = Error::Success;
  6028. auto ret = cli_.send(req, *res, error);
  6029. ASSERT_TRUE(ret);
  6030. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6031. }
  6032. TEST_F(ServerTest, KeepAlive) {
  6033. auto res = cli_.Get("/hi");
  6034. ASSERT_TRUE(res);
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6037. EXPECT_EQ("Hello World!", res->body);
  6038. res = cli_.Get("/hi");
  6039. ASSERT_TRUE(res);
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6042. EXPECT_EQ("Hello World!", res->body);
  6043. res = cli_.Get("/hi");
  6044. ASSERT_TRUE(res);
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6047. EXPECT_EQ("Hello World!", res->body);
  6048. res = cli_.Get("/not-exist");
  6049. ASSERT_TRUE(res);
  6050. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6051. res = cli_.Post("/empty", "", "text/plain");
  6052. ASSERT_TRUE(res);
  6053. EXPECT_EQ(StatusCode::OK_200, res->status);
  6054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6055. EXPECT_EQ("empty", res->body);
  6056. EXPECT_EQ("close", res->get_header_value("Connection"));
  6057. res = cli_.Post(
  6058. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6059. "text/plain");
  6060. ASSERT_TRUE(res);
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6063. EXPECT_EQ("empty", res->body);
  6064. cli_.set_keep_alive(false);
  6065. res = cli_.Get("/last-request");
  6066. ASSERT_TRUE(res);
  6067. EXPECT_EQ(StatusCode::OK_200, res->status);
  6068. EXPECT_EQ("close", res->get_header_value("Connection"));
  6069. }
  6070. TEST_F(ServerTest, TooManyRedirect) {
  6071. cli_.set_follow_location(true);
  6072. auto res = cli_.Get("/redirect/0");
  6073. ASSERT_TRUE(!res);
  6074. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6075. }
  6076. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6077. Request req;
  6078. req.method = "FOOBAR";
  6079. req.path = "/hi";
  6080. cli_.set_keep_alive(true);
  6081. auto res = cli_.send(req);
  6082. ASSERT_TRUE(res);
  6083. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6084. EXPECT_EQ("close", res->get_header_value("Connection"));
  6085. EXPECT_FALSE(cli_.is_socket_open());
  6086. }
  6087. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6088. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6089. TEST_F(ServerTest, Gzip) {
  6090. Headers headers;
  6091. headers.emplace("Accept-Encoding", "gzip, deflate");
  6092. auto res = cli_.Get("/compress", headers);
  6093. ASSERT_TRUE(res);
  6094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6096. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6097. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6098. "7890123456789012345678901234567890",
  6099. res->body);
  6100. EXPECT_EQ(StatusCode::OK_200, res->status);
  6101. }
  6102. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6103. Headers headers;
  6104. headers.emplace("Accept-Encoding", "gzip, deflate");
  6105. auto res = cli_.Get("/compress-with-charset", headers);
  6106. ASSERT_TRUE(res);
  6107. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6108. EXPECT_EQ("application/json; charset=utf-8",
  6109. res->get_header_value("Content-Type"));
  6110. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6111. "7890123456789012345678901234567890",
  6112. res->body);
  6113. EXPECT_EQ(StatusCode::OK_200, res->status);
  6114. }
  6115. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6116. Headers headers;
  6117. headers.emplace("Accept-Encoding", "");
  6118. auto res = cli_.Get("/compress", headers);
  6119. ASSERT_TRUE(res);
  6120. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6122. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6123. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6124. "7890123456789012345678901234567890",
  6125. res->body);
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. }
  6128. TEST_F(ServerTest, GzipWithContentReceiver) {
  6129. Headers headers;
  6130. headers.emplace("Accept-Encoding", "gzip, deflate");
  6131. std::string body;
  6132. auto res = cli_.Get("/compress", headers,
  6133. [&](const char *data, uint64_t data_length) {
  6134. EXPECT_EQ(100U, data_length);
  6135. body.append(data, data_length);
  6136. return true;
  6137. });
  6138. ASSERT_TRUE(res);
  6139. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6140. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6141. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6142. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6143. "7890123456789012345678901234567890",
  6144. body);
  6145. EXPECT_EQ(StatusCode::OK_200, res->status);
  6146. }
  6147. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6148. Headers headers;
  6149. headers.emplace("Accept-Encoding", "gzip, deflate");
  6150. cli_.set_decompress(false);
  6151. auto res = cli_.Get("/compress", headers);
  6152. ASSERT_TRUE(res);
  6153. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6155. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6156. EXPECT_EQ(33U, res->body.size());
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. }
  6159. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6160. Headers headers;
  6161. headers.emplace("Accept-Encoding", "");
  6162. std::string body;
  6163. auto res = cli_.Get("/compress", headers,
  6164. [&](const char *data, uint64_t data_length) {
  6165. EXPECT_EQ(100U, data_length);
  6166. body.append(data, data_length);
  6167. return true;
  6168. });
  6169. ASSERT_TRUE(res);
  6170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6172. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6173. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6174. "7890123456789012345678901234567890",
  6175. body);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. }
  6178. TEST_F(ServerTest, NoGzip) {
  6179. Headers headers;
  6180. headers.emplace("Accept-Encoding", "gzip, deflate");
  6181. auto res = cli_.Get("/nocompress", headers);
  6182. ASSERT_TRUE(res);
  6183. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6184. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6185. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6186. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6187. "7890123456789012345678901234567890",
  6188. res->body);
  6189. EXPECT_EQ(StatusCode::OK_200, res->status);
  6190. }
  6191. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6192. Headers headers;
  6193. headers.emplace("Accept-Encoding", "gzip, deflate");
  6194. std::string body;
  6195. auto res = cli_.Get("/nocompress", headers,
  6196. [&](const char *data, uint64_t data_length) {
  6197. EXPECT_EQ(100U, data_length);
  6198. body.append(data, data_length);
  6199. return true;
  6200. });
  6201. ASSERT_TRUE(res);
  6202. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6203. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6204. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6206. "7890123456789012345678901234567890",
  6207. body);
  6208. EXPECT_EQ(StatusCode::OK_200, res->status);
  6209. }
  6210. TEST_F(ServerTest, MultipartFormDataGzip) {
  6211. UploadFormDataItems items = {
  6212. {"key1", "test", "", ""},
  6213. {"key2", "--abcdefg123", "", ""},
  6214. };
  6215. cli_.set_compress(true);
  6216. auto res = cli_.Post("/compress-multipart", items);
  6217. ASSERT_TRUE(res);
  6218. EXPECT_EQ(StatusCode::OK_200, res->status);
  6219. }
  6220. #endif
  6221. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6222. TEST_F(ServerTest, Brotli) {
  6223. Headers headers;
  6224. headers.emplace("Accept-Encoding", "br");
  6225. auto res = cli_.Get("/compress", headers);
  6226. ASSERT_TRUE(res);
  6227. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6229. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6230. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6231. "7890123456789012345678901234567890",
  6232. res->body);
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. }
  6235. #endif
  6236. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6237. TEST_F(ServerTest, Zstd) {
  6238. Headers headers;
  6239. headers.emplace("Accept-Encoding", "zstd");
  6240. auto res = cli_.Get("/compress", headers);
  6241. ASSERT_TRUE(res);
  6242. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6244. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6245. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6246. "7890123456789012345678901234567890",
  6247. res->body);
  6248. EXPECT_EQ(StatusCode::OK_200, res->status);
  6249. }
  6250. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6251. Headers headers;
  6252. headers.emplace("Accept-Encoding", "");
  6253. auto res = cli_.Get("/compress", headers);
  6254. ASSERT_TRUE(res);
  6255. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6256. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6257. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6258. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6259. "7890123456789012345678901234567890",
  6260. res->body);
  6261. EXPECT_EQ(StatusCode::OK_200, res->status);
  6262. }
  6263. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6264. Headers headers;
  6265. headers.emplace("Accept-Encoding", "zstd");
  6266. std::string body;
  6267. auto res = cli_.Get("/compress", headers,
  6268. [&](const char *data, uint64_t data_length) {
  6269. EXPECT_EQ(100U, data_length);
  6270. body.append(data, data_length);
  6271. return true;
  6272. });
  6273. ASSERT_TRUE(res);
  6274. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6276. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6277. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6278. "7890123456789012345678901234567890",
  6279. body);
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. }
  6282. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6283. Headers headers;
  6284. headers.emplace("Accept-Encoding", "zstd");
  6285. cli_.set_decompress(false);
  6286. auto res = cli_.Get("/compress", headers);
  6287. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6288. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6289. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6290. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6291. ASSERT_TRUE(res);
  6292. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6294. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6295. EXPECT_EQ(StatusCode::OK_200, res->status);
  6296. ASSERT_EQ(26U, res->body.size());
  6297. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6298. 0);
  6299. }
  6300. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6301. Headers headers;
  6302. headers.emplace("Accept-Encoding", "");
  6303. std::string body;
  6304. auto res = cli_.Get("/compress", headers,
  6305. [&](const char *data, uint64_t data_length) {
  6306. EXPECT_EQ(100U, data_length);
  6307. body.append(data, data_length);
  6308. return true;
  6309. });
  6310. ASSERT_TRUE(res);
  6311. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6313. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6314. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6315. "7890123456789012345678901234567890",
  6316. body);
  6317. EXPECT_EQ(StatusCode::OK_200, res->status);
  6318. }
  6319. TEST_F(ServerTest, NoZstd) {
  6320. Headers headers;
  6321. headers.emplace("Accept-Encoding", "zstd");
  6322. auto res = cli_.Get("/nocompress", headers);
  6323. ASSERT_TRUE(res);
  6324. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6325. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6326. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6327. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6328. "7890123456789012345678901234567890",
  6329. res->body);
  6330. EXPECT_EQ(StatusCode::OK_200, res->status);
  6331. }
  6332. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6333. Headers headers;
  6334. headers.emplace("Accept-Encoding", "zstd");
  6335. std::string body;
  6336. auto res = cli_.Get("/nocompress", headers,
  6337. [&](const char *data, uint64_t data_length) {
  6338. EXPECT_EQ(100U, data_length);
  6339. body.append(data, data_length);
  6340. return true;
  6341. });
  6342. ASSERT_TRUE(res);
  6343. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6344. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6345. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6346. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6347. "7890123456789012345678901234567890",
  6348. body);
  6349. EXPECT_EQ(StatusCode::OK_200, res->status);
  6350. }
  6351. // TODO: How to enable zstd ??
  6352. TEST_F(ServerTest, MultipartFormDataZstd) {
  6353. UploadFormDataItems items = {
  6354. {"key1", "test", "", ""},
  6355. {"key2", "--abcdefg123", "", ""},
  6356. };
  6357. Headers headers;
  6358. headers.emplace("Accept-Encoding", "zstd");
  6359. cli_.set_compress(true);
  6360. auto res = cli_.Post("/compress-multipart", headers, items);
  6361. ASSERT_TRUE(res);
  6362. EXPECT_EQ(StatusCode::OK_200, res->status);
  6363. }
  6364. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6365. Headers headers;
  6366. headers.emplace("Accept-Encoding", "zstd");
  6367. cli_.set_compress(true);
  6368. auto res = cli_.Put(
  6369. "/put", headers, 3,
  6370. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6371. sink.os << "PUT";
  6372. return true;
  6373. },
  6374. "text/plain");
  6375. ASSERT_TRUE(res);
  6376. EXPECT_EQ(StatusCode::OK_200, res->status);
  6377. EXPECT_EQ("PUT", res->body);
  6378. }
  6379. // Pre-compression logging tests
  6380. TEST_F(ServerTest, PreCompressionLogging) {
  6381. // Test data for compression (matches the actual /compress endpoint content)
  6382. const std::string test_content =
  6383. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6384. "3456789012345678901234567890";
  6385. // Variables to capture logging data
  6386. std::string pre_compression_body;
  6387. std::string pre_compression_content_type;
  6388. std::string pre_compression_content_encoding;
  6389. std::string post_compression_body;
  6390. std::string post_compression_content_type;
  6391. std::string post_compression_content_encoding;
  6392. // Set up pre-compression logger
  6393. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6394. const Response &res) {
  6395. pre_compression_body = res.body;
  6396. pre_compression_content_type = res.get_header_value("Content-Type");
  6397. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6398. });
  6399. // Set up post-compression logger
  6400. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6401. post_compression_body = res.body;
  6402. post_compression_content_type = res.get_header_value("Content-Type");
  6403. post_compression_content_encoding =
  6404. res.get_header_value("Content-Encoding");
  6405. });
  6406. // Test with gzip compression
  6407. Headers headers;
  6408. headers.emplace("Accept-Encoding", "gzip");
  6409. auto res = cli_.Get("/compress", headers);
  6410. // Verify response was compressed
  6411. ASSERT_TRUE(res);
  6412. EXPECT_EQ(StatusCode::OK_200, res->status);
  6413. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6414. // Verify pre-compression logger captured uncompressed content
  6415. EXPECT_EQ(test_content, pre_compression_body);
  6416. EXPECT_EQ("text/plain", pre_compression_content_type);
  6417. EXPECT_TRUE(pre_compression_content_encoding
  6418. .empty()); // No encoding header before compression
  6419. // Verify post-compression logger captured compressed content
  6420. EXPECT_NE(test_content,
  6421. post_compression_body); // Should be different after compression
  6422. EXPECT_EQ("text/plain", post_compression_content_type);
  6423. EXPECT_EQ("gzip", post_compression_content_encoding);
  6424. // Verify compressed content is smaller
  6425. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6426. }
  6427. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6428. const std::string test_content =
  6429. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6430. "3456789012345678901234567890";
  6431. std::string pre_compression_body;
  6432. std::string post_compression_body;
  6433. svr_.set_pre_compression_logger(
  6434. [&](const Request & /*req*/, const Response &res) {
  6435. pre_compression_body = res.body;
  6436. });
  6437. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6438. post_compression_body = res.body;
  6439. });
  6440. Headers headers;
  6441. headers.emplace("Accept-Encoding", "br");
  6442. auto res = cli_.Get("/compress", headers);
  6443. ASSERT_TRUE(res);
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6446. // Verify pre-compression content is uncompressed
  6447. EXPECT_EQ(test_content, pre_compression_body);
  6448. // Verify post-compression content is compressed
  6449. EXPECT_NE(test_content, post_compression_body);
  6450. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6451. }
  6452. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6453. const std::string test_content =
  6454. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6455. "3456789012345678901234567890";
  6456. std::string pre_compression_body;
  6457. std::string post_compression_body;
  6458. svr_.set_pre_compression_logger(
  6459. [&](const Request & /*req*/, const Response &res) {
  6460. pre_compression_body = res.body;
  6461. });
  6462. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6463. post_compression_body = res.body;
  6464. });
  6465. // Request without compression (use /nocompress endpoint)
  6466. Headers headers;
  6467. auto res = cli_.Get("/nocompress", headers);
  6468. ASSERT_TRUE(res);
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6471. // Pre-compression logger should not be called when no compression is applied
  6472. EXPECT_TRUE(
  6473. pre_compression_body.empty()); // Pre-compression logger not called
  6474. EXPECT_EQ(
  6475. test_content,
  6476. post_compression_body); // Post-compression logger captures final content
  6477. }
  6478. TEST_F(ServerTest, LoggerSeesContentLength) {
  6479. size_t logged_content_length = 0;
  6480. std::string logged_content_length_header;
  6481. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6482. logged_content_length = res.content_length_;
  6483. logged_content_length_header = res.get_header_value("Content-Length");
  6484. });
  6485. auto res = cli_.Get("/nocompress");
  6486. ASSERT_TRUE(res);
  6487. EXPECT_EQ(StatusCode::OK_200, res->status);
  6488. EXPECT_EQ(res->body.size(), logged_content_length);
  6489. EXPECT_EQ(std::to_string(logged_content_length),
  6490. logged_content_length_header);
  6491. }
  6492. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6493. const std::string test_content =
  6494. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6495. "3456789012345678901234567890";
  6496. std::string pre_compression_body;
  6497. bool pre_logger_called = false;
  6498. // Set only pre-compression logger
  6499. svr_.set_pre_compression_logger(
  6500. [&](const Request & /*req*/, const Response &res) {
  6501. pre_compression_body = res.body;
  6502. pre_logger_called = true;
  6503. });
  6504. Headers headers;
  6505. headers.emplace("Accept-Encoding", "gzip");
  6506. auto res = cli_.Get("/compress", headers);
  6507. ASSERT_TRUE(res);
  6508. EXPECT_EQ(StatusCode::OK_200, res->status);
  6509. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6510. // Verify pre-compression logger was called
  6511. EXPECT_TRUE(pre_logger_called);
  6512. EXPECT_EQ(test_content, pre_compression_body);
  6513. }
  6514. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6515. {
  6516. // Test with Expect: 100-continue header - success case
  6517. // Server returns 100 Continue, client sends body, server returns 200 OK
  6518. Request req;
  6519. req.method = "POST";
  6520. req.path = "/post-large";
  6521. req.set_header("Expect", "100-continue");
  6522. req.body = LARGE_DATA;
  6523. Response res;
  6524. auto error = Error::Success;
  6525. cli_.set_keep_alive(true);
  6526. auto ret = cli_.send(req, res, error);
  6527. EXPECT_TRUE(ret);
  6528. EXPECT_EQ(StatusCode::OK_200, res.status);
  6529. EXPECT_EQ(LARGE_DATA, res.body);
  6530. }
  6531. {
  6532. // Test with Expect: 100-continue header - error case
  6533. // Client should not send the body when server returns an error
  6534. Request req;
  6535. req.method = "POST";
  6536. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6537. req.set_header("Expect", "100-continue");
  6538. req.body = LARGE_DATA;
  6539. Response res;
  6540. auto error = Error::Success;
  6541. auto start = std::chrono::high_resolution_clock::now();
  6542. cli_.set_keep_alive(true);
  6543. auto ret = cli_.send(req, res, error);
  6544. auto end = std::chrono::high_resolution_clock::now();
  6545. auto elapsed =
  6546. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6547. .count();
  6548. // With Expect: 100-continue, request completes successfully but with error
  6549. EXPECT_TRUE(ret);
  6550. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6551. EXPECT_EQ("close", res.get_header_value("Connection"));
  6552. EXPECT_FALSE(cli_.is_socket_open());
  6553. EXPECT_LE(elapsed, 2000);
  6554. }
  6555. {
  6556. // Send an extra GET request to ensure error recovery without hanging
  6557. Request req;
  6558. req.method = "GET";
  6559. req.path = "/hi";
  6560. auto start = std::chrono::high_resolution_clock::now();
  6561. auto res = cli_.send(req);
  6562. auto end = std::chrono::high_resolution_clock::now();
  6563. auto elapsed =
  6564. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6565. .count();
  6566. ASSERT_TRUE(res);
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. EXPECT_EQ("Hello World!", res->body);
  6569. EXPECT_LE(elapsed, 500);
  6570. }
  6571. }
  6572. TEST(ZstdDecompressor, ChunkedDecompression) {
  6573. std::string data;
  6574. for (size_t i = 0; i < 32 * 1024; ++i) {
  6575. data.push_back(static_cast<char>('a' + i % 26));
  6576. }
  6577. std::string compressed_data;
  6578. {
  6579. httplib::detail::zstd_compressor compressor;
  6580. bool result = compressor.compress(
  6581. data.data(), data.size(),
  6582. /*last=*/true,
  6583. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6584. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6585. compressed_data_size);
  6586. return true;
  6587. });
  6588. ASSERT_TRUE(result);
  6589. }
  6590. std::string decompressed_data;
  6591. {
  6592. httplib::detail::zstd_decompressor decompressor;
  6593. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6594. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6595. size_t chunk_size = 130;
  6596. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6597. chunk_begin += chunk_size) {
  6598. size_t current_chunk_size =
  6599. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6600. bool result = decompressor.decompress(
  6601. compressed_data.data() + chunk_begin, current_chunk_size,
  6602. [&](const char *decompressed_data_chunk,
  6603. size_t decompressed_data_chunk_size) {
  6604. decompressed_data.insert(decompressed_data.size(),
  6605. decompressed_data_chunk,
  6606. decompressed_data_chunk_size);
  6607. return true;
  6608. });
  6609. ASSERT_TRUE(result);
  6610. }
  6611. }
  6612. ASSERT_EQ(data, decompressed_data);
  6613. }
  6614. TEST(ZstdDecompressor, Decompress) {
  6615. std::string original_text = "Compressed with ZSTD";
  6616. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6617. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6618. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6619. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6620. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6621. std::string decompressed_data;
  6622. {
  6623. httplib::detail::zstd_decompressor decompressor;
  6624. bool result = decompressor.decompress(
  6625. compressed_data.data(), compressed_data.size(),
  6626. [&](const char *decompressed_data_chunk,
  6627. size_t decompressed_data_chunk_size) {
  6628. decompressed_data.insert(decompressed_data.size(),
  6629. decompressed_data_chunk,
  6630. decompressed_data_chunk_size);
  6631. return true;
  6632. });
  6633. ASSERT_TRUE(result);
  6634. }
  6635. ASSERT_EQ(original_text, decompressed_data);
  6636. }
  6637. #endif
  6638. // Sends a raw request to a server listening at HOST:PORT.
  6639. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6640. std::string *resp = nullptr) {
  6641. auto error = Error::Success;
  6642. auto client_sock = detail::create_client_socket(
  6643. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6644. /*connection_timeout_sec=*/5, 0,
  6645. /*read_timeout_sec=*/5, 0,
  6646. /*write_timeout_sec=*/5, 0, std::string(), error);
  6647. if (client_sock == INVALID_SOCKET) { return false; }
  6648. auto ret = detail::process_client_socket(
  6649. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6650. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6651. if (req.size() !=
  6652. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6653. return false;
  6654. }
  6655. char buf[512];
  6656. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6657. while (line_reader.getline()) {
  6658. if (resp) { *resp += line_reader.ptr(); }
  6659. }
  6660. return true;
  6661. });
  6662. detail::close_socket(client_sock);
  6663. return ret;
  6664. }
  6665. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6666. Server svr;
  6667. std::string header_value;
  6668. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6669. header_value = req.get_header_value("foo");
  6670. res.set_content("ok", "text/plain");
  6671. });
  6672. thread t = thread([&] { svr.listen(HOST, PORT); });
  6673. auto se = detail::scope_exit([&] {
  6674. svr.stop();
  6675. t.join();
  6676. ASSERT_FALSE(svr.is_running());
  6677. });
  6678. svr.wait_until_ready();
  6679. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6680. // like characters are not treated the same - use vertical tab and escape.
  6681. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6682. "foo: \t \v bar \x1B\t \r\n"
  6683. "Connection: close\r\n"
  6684. "\r\n";
  6685. std::string res;
  6686. ASSERT_TRUE(send_request(5, req, &res));
  6687. EXPECT_EQ(header_value, "");
  6688. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6689. }
  6690. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6691. Server svr;
  6692. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6693. auto i = new int(0);
  6694. res.set_header("Trailer", "X-Safe, X-Reflected");
  6695. res.set_chunked_content_provider(
  6696. "text/plain",
  6697. [i](size_t /*offset*/, DataSink &sink) {
  6698. if (*i == 0) {
  6699. sink.os << "body";
  6700. } else {
  6701. Headers trailer;
  6702. // A valid trailer that must survive.
  6703. trailer.emplace("X-Safe", "safe");
  6704. // Attacker-controlled value carrying CR/LF (response splitting).
  6705. trailer.emplace("X-Reflected",
  6706. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6707. // Attacker-controlled name carrying CR/LF.
  6708. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6709. sink.done_with_trailer(trailer);
  6710. }
  6711. (*i)++;
  6712. return true;
  6713. },
  6714. [i](bool /*success*/) { delete i; });
  6715. });
  6716. thread t = thread([&] { svr.listen(HOST, PORT); });
  6717. auto se = detail::scope_exit([&] {
  6718. svr.stop();
  6719. t.join();
  6720. ASSERT_FALSE(svr.is_running());
  6721. });
  6722. svr.wait_until_ready();
  6723. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6724. "Host: " + HOST +
  6725. "\r\n"
  6726. "Connection: close\r\n"
  6727. "\r\n";
  6728. std::string res;
  6729. ASSERT_TRUE(send_request(5, req, &res));
  6730. // The injected fields must not appear anywhere in the raw response.
  6731. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6732. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6733. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6734. // Invalid trailers are dropped entirely, matching set_header().
  6735. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6736. // The valid trailer still passes through.
  6737. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6738. }
  6739. // Forward declaration: in split builds split.py strips `inline` and moves the
  6740. // definition into httplib.cc, so detail::write_request_line is not visible from
  6741. // the public httplib.h. Re-declaring it here lets the tests link against the
  6742. // symbol in both header-only and split builds.
  6743. namespace httplib {
  6744. namespace detail {
  6745. ssize_t write_request_line(Stream &strm, const std::string &method,
  6746. const std::string &path);
  6747. } // namespace detail
  6748. } // namespace httplib
  6749. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  6750. // A well-formed target is written verbatim.
  6751. {
  6752. detail::BufferStream strm;
  6753. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  6754. EXPECT_GT(n, 0);
  6755. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  6756. }
  6757. // A target carrying CR/LF must be rejected before anything reaches the wire,
  6758. // otherwise it splits the request line and injects a header or a whole
  6759. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  6760. // when path encoding is disabled.
  6761. const std::string evil_targets[] = {
  6762. "/a\r\nInjected: pwned",
  6763. "/a\rInjected",
  6764. "/a\nInjected",
  6765. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  6766. };
  6767. for (const auto &evil : evil_targets) {
  6768. detail::BufferStream strm;
  6769. auto n = detail::write_request_line(strm, "GET", evil);
  6770. EXPECT_LT(n, 0);
  6771. EXPECT_TRUE(strm.get_buffer().empty());
  6772. }
  6773. }
  6774. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  6775. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  6776. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  6777. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  6778. // client must fail cleanly with Error::Write instead of putting a
  6779. // request-line-less, header-injecting request on the wire.
  6780. Server svr;
  6781. svr.Get("/a", [](const Request &, Response &res) {
  6782. res.set_content("ok", "text/plain");
  6783. });
  6784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6785. auto se = detail::scope_exit([&] {
  6786. svr.stop();
  6787. thread.join();
  6788. ASSERT_FALSE(svr.is_running());
  6789. });
  6790. svr.wait_until_ready();
  6791. {
  6792. Client cli(HOST, PORT);
  6793. cli.set_path_encode(false);
  6794. // The request is rejected before anything is written, so the connection
  6795. // stays silent and the subsequent response read would otherwise block for
  6796. // the full default read timeout. Shorten it -- the assertion is on the
  6797. // error, not the timeout.
  6798. cli.set_read_timeout(1, 0);
  6799. auto res = cli.Get("/a\r\nInjected: pwned");
  6800. EXPECT_FALSE(res);
  6801. EXPECT_EQ(Error::Write, res.error());
  6802. }
  6803. }
  6804. // Sends a raw request and verifies that there isn't a crash or exception.
  6805. static void test_raw_request(const std::string &req,
  6806. std::string *out = nullptr) {
  6807. Server svr;
  6808. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6809. res.set_content("ok", "text/plain");
  6810. });
  6811. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6812. res.set_content("ok", "text/plain");
  6813. });
  6814. svr.Get("/header_field_value_check",
  6815. [&](const Request & /*req*/, Response &res) {
  6816. res.set_content("ok", "text/plain");
  6817. });
  6818. // Server read timeout must be longer than the client read timeout for the
  6819. // bug to reproduce, probably to force the server to process a request
  6820. // without a trailing blank line.
  6821. const time_t client_read_timeout_sec = 1;
  6822. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6823. bool listen_thread_ok = false;
  6824. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. t.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. EXPECT_TRUE(listen_thread_ok);
  6830. });
  6831. svr.wait_until_ready();
  6832. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6833. }
  6834. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6835. // A certain header line causes an exception if the header property is parsed
  6836. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6837. test_raw_request(
  6838. "GET /hi HTTP/1.1\r\n"
  6839. " : "
  6840. " "
  6841. " ");
  6842. }
  6843. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6844. // A certain header line causes an exception if the header property *name* is
  6845. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6846. // greedy matcher and requires backtracking when there are a lot of ":"
  6847. // characters.
  6848. // This occurs with libc++ but not libstdc++.
  6849. test_raw_request(
  6850. "GET /hi HTTP/1.1\r\n"
  6851. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6852. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6853. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6854. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6855. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6856. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6857. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6858. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6859. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6860. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6861. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6862. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6863. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6864. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6865. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6866. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6867. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6868. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6869. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6870. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6871. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6872. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6873. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6874. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6875. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6876. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6877. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6878. "&&&%%%");
  6879. }
  6880. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6881. // Make sure this doesn't crash the server.
  6882. // In a previous version of the header line regex, the "\r" rendered the line
  6883. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6884. // a new position where the leading white space ended and the field value
  6885. // began.
  6886. // The crash occurs with libc++ but not libstdc++.
  6887. test_raw_request("GET /hi HTTP/1.1\r\n"
  6888. "a:" +
  6889. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6890. "\r\n"
  6891. "\r\n");
  6892. }
  6893. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6894. std::string out;
  6895. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6896. "Content-Type: text/plain\r\n"
  6897. "Transfer-Encoding: chunked\r\n"
  6898. "\r\n"
  6899. "nothex\r\n",
  6900. &out);
  6901. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6902. }
  6903. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6904. std::string out;
  6905. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6906. "Content-Type: text/plain\r\n"
  6907. "Transfer-Encoding: chunked\r\n"
  6908. "\r\n"
  6909. "3\r\n"
  6910. "xyz\r\n"
  6911. "NaN\r\n",
  6912. &out);
  6913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6914. }
  6915. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6916. std::string out;
  6917. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6918. "Content-Type: text/plain\r\n"
  6919. "Transfer-Encoding: chunked\r\n"
  6920. "\r\n"
  6921. // Length is too large for 64 bits.
  6922. "1ffffffffffffffff\r\n"
  6923. "xyz\r\n",
  6924. &out);
  6925. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6926. }
  6927. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6928. test_raw_request("GET /hi HTTP/1.1\r\n"
  6929. "Content-Type: text/plain\r\n\r");
  6930. }
  6931. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6932. std::string out;
  6933. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6934. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6935. }
  6936. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6937. Server svr;
  6938. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6939. EXPECT_TRUE(!req.remote_addr.empty());
  6940. });
  6941. thread t = thread([&] { svr.listen(HOST, PORT); });
  6942. auto se = detail::scope_exit([&] {
  6943. svr.stop();
  6944. t.join();
  6945. ASSERT_FALSE(svr.is_running());
  6946. });
  6947. svr.wait_until_ready();
  6948. // Send an invalid request line to trigger Bad Request
  6949. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6950. std::string out;
  6951. ASSERT_TRUE(send_request(5, bad_req, &out));
  6952. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6953. }
  6954. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6955. std::string out;
  6956. std::string request(
  6957. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6958. test_raw_request(request, &out);
  6959. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6960. }
  6961. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6962. std::string out;
  6963. std::string request(
  6964. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6965. test_raw_request(request, &out);
  6966. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6967. }
  6968. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6969. std::string out;
  6970. std::string request(
  6971. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6972. test_raw_request(request, &out);
  6973. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6974. }
  6975. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6976. std::string out;
  6977. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6978. "Test: \r\n\r\n",
  6979. &out);
  6980. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6981. }
  6982. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6983. Server svr;
  6984. std::string x_custom;
  6985. std::string cookie;
  6986. std::string xff;
  6987. std::string x_unicode;
  6988. std::string x_iis;
  6989. svr.Get("/check", [&](const Request &req, Response &res) {
  6990. x_custom = req.get_header_value("X-Custom");
  6991. cookie = req.get_header_value("Cookie");
  6992. xff = req.get_header_value("X-Forwarded-For");
  6993. x_unicode = req.get_header_value("X-Unicode");
  6994. x_iis = req.get_header_value("X-IIS");
  6995. res.set_content("ok", "text/plain");
  6996. });
  6997. thread t = thread([&] { svr.listen(HOST, PORT); });
  6998. auto se = detail::scope_exit([&] {
  6999. svr.stop();
  7000. t.join();
  7001. ASSERT_FALSE(svr.is_running());
  7002. });
  7003. svr.wait_until_ready();
  7004. const std::string req = "GET /check HTTP/1.1\r\n"
  7005. "Host: localhost\r\n"
  7006. "X-Custom: a%0D%0AInjected: b\r\n"
  7007. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7008. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7009. "X-Unicode: %E3%81%82\r\n"
  7010. "X-IIS: %u00E9\r\n"
  7011. "Connection: close\r\n"
  7012. "\r\n";
  7013. std::string res;
  7014. ASSERT_TRUE(send_request(5, req, &res));
  7015. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7016. // Every value must be returned verbatim (wire form), with no decoding.
  7017. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7018. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7019. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7020. EXPECT_EQ("%E3%81%82", x_unicode);
  7021. EXPECT_EQ("%u00E9", x_iis);
  7022. }
  7023. // Applications that previously relied on automatic percent-decoding can
  7024. // reproduce the old behavior by explicitly calling decode_path_component()
  7025. // or, for RFC 3986 conformance, decode_uri_component().
  7026. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7027. Server svr;
  7028. std::string decoded;
  7029. svr.Get("/check", [&](const Request &req, Response &res) {
  7030. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7031. res.set_content("ok", "text/plain");
  7032. });
  7033. thread t = thread([&] { svr.listen(HOST, PORT); });
  7034. auto se = detail::scope_exit([&] {
  7035. svr.stop();
  7036. t.join();
  7037. ASSERT_FALSE(svr.is_running());
  7038. });
  7039. svr.wait_until_ready();
  7040. const std::string req = "GET /check HTTP/1.1\r\n"
  7041. "Host: localhost\r\n"
  7042. "X-Custom: hello%20world\r\n"
  7043. "Connection: close\r\n"
  7044. "\r\n";
  7045. std::string res;
  7046. ASSERT_TRUE(send_request(5, req, &res));
  7047. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7048. EXPECT_EQ("hello world", decoded);
  7049. }
  7050. // Regression test for #2033. Browsers send Referer values that include
  7051. // percent-encoded characters such as %0A inside the URL. Decoding the
  7052. // header value would either trip the post-decode CR/LF/NUL guard (the
  7053. // original bug, returning 400) or, after that guard was relaxed, silently
  7054. // store a literal LF — both unacceptable. The wire form must round-trip.
  7055. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7056. Server svr;
  7057. std::string referer;
  7058. svr.Get("/check", [&](const Request &req, Response &res) {
  7059. referer = req.get_header_value("Referer");
  7060. res.set_content("ok", "text/plain");
  7061. });
  7062. thread t = thread([&] { svr.listen(HOST, PORT); });
  7063. auto se = detail::scope_exit([&] {
  7064. svr.stop();
  7065. t.join();
  7066. ASSERT_FALSE(svr.is_running());
  7067. });
  7068. svr.wait_until_ready();
  7069. const std::string req = "GET /check HTTP/1.1\r\n"
  7070. "Host: localhost\r\n"
  7071. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7072. "Connection: close\r\n"
  7073. "\r\n";
  7074. std::string res;
  7075. ASSERT_TRUE(send_request(5, req, &res));
  7076. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7077. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7078. }
  7079. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7080. Server svr;
  7081. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7082. res.set_header("Cache-Control", "no-cache");
  7083. res.set_chunked_content_provider(
  7084. "text/event-stream", [](size_t offset, DataSink &sink) {
  7085. std::string s = "data:";
  7086. s += std::to_string(offset);
  7087. s += "\n\n";
  7088. auto ret = sink.write(s.data(), s.size());
  7089. EXPECT_TRUE(ret);
  7090. std::this_thread::sleep_for(std::chrono::seconds(1));
  7091. return true;
  7092. });
  7093. });
  7094. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7095. svr.wait_until_ready();
  7096. Client client(HOST, PORT);
  7097. const Headers headers = {{"Accept", "text/event-stream"}};
  7098. auto get_thread = std::thread([&client, &headers]() {
  7099. auto res = client.Get(
  7100. "/events", headers,
  7101. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7102. });
  7103. auto se = detail::scope_exit([&] {
  7104. svr.stop();
  7105. get_thread.join();
  7106. listen_thread.join();
  7107. ASSERT_FALSE(svr.is_running());
  7108. });
  7109. // Give GET time to get a few messages.
  7110. std::this_thread::sleep_for(std::chrono::seconds(2));
  7111. }
  7112. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7113. httplib::Server svr;
  7114. svr.Post("/hi",
  7115. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7116. res.status = StatusCode::OK_200;
  7117. });
  7118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7119. svr.wait_until_ready();
  7120. Client cli(HOST, PORT);
  7121. auto res = cli.Post("/hi", "data", "text/plain");
  7122. ASSERT_TRUE(res);
  7123. EXPECT_EQ(StatusCode::OK_200, res->status);
  7124. svr.stop();
  7125. thread.join();
  7126. ASSERT_FALSE(svr.is_running());
  7127. res = cli.Post("/hi", "data", "text/plain");
  7128. ASSERT_FALSE(res);
  7129. }
  7130. TEST(ServerStopTest, ListenFailure) {
  7131. Server svr;
  7132. auto t = thread([&]() {
  7133. auto ret = svr.listen("????", PORT);
  7134. EXPECT_FALSE(ret);
  7135. });
  7136. svr.wait_until_ready();
  7137. svr.stop();
  7138. t.join();
  7139. }
  7140. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7141. TEST(ServerStopTest, Decommision) {
  7142. Server svr;
  7143. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7144. for (int i = 0; i < 4; i++) {
  7145. auto is_even = !(i % 2);
  7146. std::thread t{[&] {
  7147. try {
  7148. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7149. if (is_even) {
  7150. throw std::runtime_error("Some thing that happens to go wrong.");
  7151. }
  7152. svr.listen(HOST, PORT);
  7153. } catch (...) { svr.decommission(); }
  7154. }};
  7155. svr.wait_until_ready();
  7156. // Server is up
  7157. {
  7158. Client cli(HOST, PORT);
  7159. auto res = cli.Get("/hi");
  7160. if (is_even) {
  7161. EXPECT_FALSE(res);
  7162. } else {
  7163. EXPECT_TRUE(res);
  7164. EXPECT_EQ("hi...", res->body);
  7165. }
  7166. }
  7167. svr.stop();
  7168. t.join();
  7169. // Server is down...
  7170. {
  7171. Client cli(HOST, PORT);
  7172. auto res = cli.Get("/hi");
  7173. EXPECT_FALSE(res);
  7174. }
  7175. }
  7176. }
  7177. #endif
  7178. // Helper function for string body upload progress tests
  7179. template <typename SetupHandler, typename ClientCall>
  7180. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7181. ClientCall &&client_call,
  7182. const string &body) {
  7183. Server svr;
  7184. setup_handler(svr);
  7185. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7186. auto se = detail::scope_exit([&] {
  7187. svr.stop();
  7188. t.join();
  7189. });
  7190. svr.wait_until_ready();
  7191. Client cli(HOST, PORT);
  7192. vector<uint64_t> progress_values;
  7193. bool progress_called = false;
  7194. auto res =
  7195. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7196. progress_values.push_back(current);
  7197. progress_called = true;
  7198. return true;
  7199. });
  7200. ASSERT_TRUE(res);
  7201. EXPECT_EQ(200, res->status);
  7202. EXPECT_TRUE(progress_called);
  7203. }
  7204. TEST(UploadProgressTest, PostStringBodyBasic) {
  7205. TestStringBodyUploadProgress(
  7206. [](Server &svr) {
  7207. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7208. res.set_content("received", "text/plain");
  7209. });
  7210. },
  7211. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7212. return cli.Post("/test", body, "text/plain", progress_callback);
  7213. },
  7214. "test data for upload progress");
  7215. }
  7216. TEST(UploadProgressTest, PutStringBodyBasic) {
  7217. TestStringBodyUploadProgress(
  7218. [](Server &svr) {
  7219. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7220. res.set_content("put received", "text/plain");
  7221. });
  7222. },
  7223. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7224. return cli.Put("/test", body, "text/plain", progress_callback);
  7225. },
  7226. "put test data for upload progress");
  7227. }
  7228. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7229. TestStringBodyUploadProgress(
  7230. [](Server &svr) {
  7231. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7232. res.set_content("patch received", "text/plain");
  7233. });
  7234. },
  7235. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7236. return cli.Patch("/test", body, "text/plain", progress_callback);
  7237. },
  7238. "patch test data for upload progress");
  7239. }
  7240. // Helper function for content provider upload progress tests
  7241. template <typename SetupHandler, typename ClientCall>
  7242. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7243. ClientCall &&client_call) {
  7244. Server svr;
  7245. setup_handler(svr);
  7246. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7247. auto se = detail::scope_exit([&] {
  7248. svr.stop();
  7249. t.join();
  7250. });
  7251. svr.wait_until_ready();
  7252. Client cli(HOST, PORT);
  7253. vector<uint64_t> progress_values;
  7254. auto res =
  7255. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7256. progress_values.push_back(current);
  7257. return true;
  7258. });
  7259. ASSERT_TRUE(res);
  7260. EXPECT_EQ(200, res->status);
  7261. EXPECT_FALSE(progress_values.empty());
  7262. }
  7263. TEST(UploadProgressTest, PostContentProviderProgress) {
  7264. TestContentProviderUploadProgress(
  7265. [](Server &svr) {
  7266. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7267. res.set_content("provider received", "text/plain");
  7268. });
  7269. },
  7270. [](Client &cli, UploadProgress progress_callback) {
  7271. return cli.Post(
  7272. "/test", 10,
  7273. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7274. sink.os << "test data";
  7275. return true;
  7276. },
  7277. "text/plain", progress_callback);
  7278. });
  7279. }
  7280. // Helper function for multipart upload progress tests
  7281. template <typename SetupHandler, typename ClientCall>
  7282. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7283. ClientCall &&client_call,
  7284. const string &endpoint) {
  7285. Server svr;
  7286. setup_handler(svr);
  7287. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7288. auto se = detail::scope_exit([&] {
  7289. svr.stop();
  7290. t.join();
  7291. });
  7292. svr.wait_until_ready();
  7293. Client cli(HOST, PORT);
  7294. vector<uint64_t> progress_values;
  7295. UploadFormDataItems items = {
  7296. {"field1", "value1", "", ""},
  7297. {"field2", "longer value for progress tracking test", "", ""},
  7298. {"file1", "file content data for upload progress", "test.txt",
  7299. "text/plain"}};
  7300. auto res = client_call(cli, endpoint, items,
  7301. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7302. progress_values.push_back(current);
  7303. return true;
  7304. });
  7305. ASSERT_TRUE(res);
  7306. EXPECT_EQ(200, res->status);
  7307. EXPECT_FALSE(progress_values.empty());
  7308. }
  7309. TEST(UploadProgressTest, PostMultipartProgress) {
  7310. TestMultipartUploadProgress(
  7311. [](Server &svr) {
  7312. svr.Post("/multipart", [](const Request &req, Response &res) {
  7313. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7314. res.set_content("multipart received", "text/plain");
  7315. });
  7316. },
  7317. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7318. UploadProgress progress_callback) {
  7319. return cli.Post(endpoint, items, progress_callback);
  7320. },
  7321. "/multipart");
  7322. }
  7323. // Helper function for basic download progress tests
  7324. template <typename SetupHandler, typename ClientCall>
  7325. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7326. ClientCall &&client_call, const string &endpoint,
  7327. size_t expected_content_size) {
  7328. Server svr;
  7329. setup_handler(svr);
  7330. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7331. auto se = detail::scope_exit([&] {
  7332. svr.stop();
  7333. t.join();
  7334. });
  7335. svr.wait_until_ready();
  7336. Client cli(HOST, PORT);
  7337. vector<uint64_t> progress_values;
  7338. auto res = client_call(cli, endpoint,
  7339. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7340. progress_values.push_back(current);
  7341. return true;
  7342. });
  7343. ASSERT_TRUE(res);
  7344. EXPECT_EQ(200, res->status);
  7345. EXPECT_FALSE(progress_values.empty());
  7346. EXPECT_EQ(expected_content_size, res->body.size());
  7347. }
  7348. TEST(DownloadProgressTest, GetBasic) {
  7349. TestBasicDownloadProgress(
  7350. [](Server &svr) {
  7351. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7352. string content(1000, 'D');
  7353. res.set_content(content, "text/plain");
  7354. });
  7355. },
  7356. [](Client &cli, const string &endpoint,
  7357. DownloadProgress progress_callback) {
  7358. return cli.Get(endpoint, progress_callback);
  7359. },
  7360. "/download", 1000u);
  7361. }
  7362. // Helper function for content receiver download progress tests
  7363. template <typename SetupHandler, typename ClientCall>
  7364. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7365. ClientCall &&client_call,
  7366. const string &endpoint,
  7367. size_t expected_content_size) {
  7368. Server svr;
  7369. setup_handler(svr);
  7370. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7371. auto se = detail::scope_exit([&] {
  7372. svr.stop();
  7373. t.join();
  7374. });
  7375. svr.wait_until_ready();
  7376. Client cli(HOST, PORT);
  7377. vector<uint64_t> progress_values;
  7378. string received_body;
  7379. auto res = client_call(
  7380. cli, endpoint,
  7381. [&](const char *data, size_t data_length) -> bool {
  7382. received_body.append(data, data_length);
  7383. return true;
  7384. },
  7385. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7386. progress_values.push_back(current);
  7387. return true;
  7388. });
  7389. ASSERT_TRUE(res);
  7390. EXPECT_EQ(200, res->status);
  7391. EXPECT_FALSE(progress_values.empty());
  7392. EXPECT_EQ(expected_content_size, received_body.size());
  7393. EXPECT_TRUE(res->body.empty());
  7394. }
  7395. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7396. TestContentReceiverDownloadProgress(
  7397. [](Server &svr) {
  7398. svr.Get("/download-receiver",
  7399. [](const Request & /*req*/, Response &res) {
  7400. string content(2000, 'R');
  7401. res.set_content(content, "text/plain");
  7402. });
  7403. },
  7404. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7405. DownloadProgress progress_callback) {
  7406. return cli.Get(endpoint, content_receiver, progress_callback);
  7407. },
  7408. "/download-receiver", 2000u);
  7409. }
  7410. TEST(StreamingTest, NoContentLengthStreaming) {
  7411. Server svr;
  7412. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7413. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7414. if (offset < 6) {
  7415. sink.os << (offset < 3 ? "a" : "b");
  7416. } else {
  7417. sink.done();
  7418. }
  7419. return true;
  7420. });
  7421. });
  7422. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7423. auto listen_se = detail::scope_exit([&] {
  7424. svr.stop();
  7425. listen_thread.join();
  7426. ASSERT_FALSE(svr.is_running());
  7427. });
  7428. svr.wait_until_ready();
  7429. Client client(HOST, PORT);
  7430. auto get_thread = std::thread([&client]() {
  7431. std::string s;
  7432. auto res =
  7433. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7434. s += std::string(data, len);
  7435. return true;
  7436. });
  7437. ASSERT_TRUE(res);
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. EXPECT_EQ("aaabbb", s);
  7440. });
  7441. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7442. // Give GET time to get a few messages.
  7443. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7444. }
  7445. TEST(MountTest, Unmount) {
  7446. Server svr;
  7447. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7448. auto se = detail::scope_exit([&] {
  7449. svr.stop();
  7450. listen_thread.join();
  7451. ASSERT_FALSE(svr.is_running());
  7452. });
  7453. svr.wait_until_ready();
  7454. Client cli("localhost", PORT);
  7455. svr.set_mount_point("/mount2", "./www2");
  7456. auto res = cli.Get("/");
  7457. ASSERT_TRUE(res);
  7458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7459. res = cli.Get("/mount2/dir/test.html");
  7460. ASSERT_TRUE(res);
  7461. EXPECT_EQ(StatusCode::OK_200, res->status);
  7462. svr.set_mount_point("/", "./www");
  7463. res = cli.Get("/dir/");
  7464. ASSERT_TRUE(res);
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. svr.remove_mount_point("/");
  7467. res = cli.Get("/dir/");
  7468. ASSERT_TRUE(res);
  7469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7470. svr.remove_mount_point("/mount2");
  7471. res = cli.Get("/mount2/dir/test.html");
  7472. ASSERT_TRUE(res);
  7473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7474. }
  7475. TEST(MountTest, Redicect) {
  7476. Server svr;
  7477. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7478. auto se = detail::scope_exit([&] {
  7479. svr.stop();
  7480. listen_thread.join();
  7481. ASSERT_FALSE(svr.is_running());
  7482. });
  7483. svr.set_mount_point("/", "./www");
  7484. svr.wait_until_ready();
  7485. Client cli("localhost", PORT);
  7486. auto res = cli.Get("/dir/");
  7487. ASSERT_TRUE(res);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. res = cli.Get("/dir");
  7490. ASSERT_TRUE(res);
  7491. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7492. res = cli.Get("/file");
  7493. ASSERT_TRUE(res);
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. res = cli.Get("/file/");
  7496. ASSERT_TRUE(res);
  7497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7498. cli.set_follow_location(true);
  7499. res = cli.Get("/dir");
  7500. ASSERT_TRUE(res);
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. }
  7503. TEST(MountTest, MultibytesPathName) {
  7504. Server svr;
  7505. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7506. auto se = detail::scope_exit([&] {
  7507. svr.stop();
  7508. listen_thread.join();
  7509. ASSERT_FALSE(svr.is_running());
  7510. });
  7511. svr.set_mount_point("/", "./www");
  7512. svr.wait_until_ready();
  7513. Client cli("localhost", PORT);
  7514. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7515. ASSERT_TRUE(res);
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7518. }
  7519. #ifdef _WIN32
  7520. // Issue #2435: mmap::open() must succeed even when another handle holds
  7521. // the file open for writing (e.g. an active log file).
  7522. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7523. const char *path = "mmap_concurrent_writer_test.txt";
  7524. const char *content = "hello";
  7525. {
  7526. std::ofstream f(path, std::ios::binary);
  7527. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7528. }
  7529. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7530. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7531. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7532. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7533. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7534. detail::mmap m(path);
  7535. ASSERT_TRUE(m.is_open());
  7536. EXPECT_EQ(strlen(content), m.size());
  7537. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7538. }
  7539. #endif
  7540. TEST(KeepAliveTest, ReadTimeout) {
  7541. Server svr;
  7542. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7543. std::this_thread::sleep_for(std::chrono::seconds(2));
  7544. res.set_content("a", "text/plain");
  7545. });
  7546. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7547. res.set_content("b", "text/plain");
  7548. });
  7549. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7550. auto se = detail::scope_exit([&] {
  7551. svr.stop();
  7552. listen_thread.join();
  7553. ASSERT_FALSE(svr.is_running());
  7554. });
  7555. svr.wait_until_ready();
  7556. Client cli("localhost", PORT);
  7557. cli.set_keep_alive(true);
  7558. cli.set_read_timeout(std::chrono::seconds(1));
  7559. auto resa = cli.Get("/a");
  7560. ASSERT_FALSE(resa);
  7561. EXPECT_EQ(Error::Read, resa.error());
  7562. auto resb = cli.Get("/b");
  7563. ASSERT_TRUE(resb);
  7564. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7565. EXPECT_EQ("b", resb->body);
  7566. }
  7567. TEST(KeepAliveTest, MaxCount) {
  7568. size_t keep_alive_max_count = 3;
  7569. Server svr;
  7570. svr.set_keep_alive_max_count(keep_alive_max_count);
  7571. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7572. res.set_content("Hello World!", "text/plain");
  7573. });
  7574. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7575. auto se = detail::scope_exit([&] {
  7576. svr.stop();
  7577. listen_thread.join();
  7578. ASSERT_FALSE(svr.is_running());
  7579. });
  7580. svr.wait_until_ready();
  7581. Client cli(HOST, PORT);
  7582. cli.set_keep_alive(true);
  7583. for (size_t i = 0; i < 5; i++) {
  7584. auto result = cli.Get("/hi");
  7585. ASSERT_TRUE(result);
  7586. EXPECT_EQ(StatusCode::OK_200, result->status);
  7587. if (i == keep_alive_max_count - 1) {
  7588. EXPECT_EQ("close", result->get_header_value("Connection"));
  7589. } else {
  7590. EXPECT_FALSE(result->has_header("Connection"));
  7591. }
  7592. }
  7593. }
  7594. TEST(KeepAliveTest, Issue1041) {
  7595. Server svr;
  7596. svr.set_keep_alive_timeout(3);
  7597. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7598. res.set_content("Hello World!", "text/plain");
  7599. });
  7600. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7601. auto se = detail::scope_exit([&] {
  7602. svr.stop();
  7603. listen_thread.join();
  7604. ASSERT_FALSE(svr.is_running());
  7605. });
  7606. svr.wait_until_ready();
  7607. Client cli(HOST, PORT);
  7608. cli.set_keep_alive(true);
  7609. auto result = cli.Get("/hi");
  7610. ASSERT_TRUE(result);
  7611. EXPECT_EQ(StatusCode::OK_200, result->status);
  7612. std::this_thread::sleep_for(std::chrono::seconds(5));
  7613. result = cli.Get("/hi");
  7614. ASSERT_TRUE(result);
  7615. EXPECT_EQ(StatusCode::OK_200, result->status);
  7616. }
  7617. TEST(KeepAliveTest, Issue1959) {
  7618. Server svr;
  7619. svr.set_keep_alive_timeout(5);
  7620. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7621. res.set_content("a", "text/plain");
  7622. });
  7623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7624. auto se = detail::scope_exit([&] {
  7625. if (!svr.is_running()) return;
  7626. svr.stop();
  7627. listen_thread.join();
  7628. ASSERT_FALSE(svr.is_running());
  7629. });
  7630. svr.wait_until_ready();
  7631. Client cli("localhost", PORT);
  7632. cli.set_keep_alive(true);
  7633. using namespace std::chrono;
  7634. auto start = steady_clock::now();
  7635. cli.Get("/a");
  7636. svr.stop();
  7637. listen_thread.join();
  7638. auto end = steady_clock::now();
  7639. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7640. EXPECT_LT(elapsed, 5000);
  7641. }
  7642. #ifdef CPPHTTPLIB_SSL_ENABLED
  7643. TEST(KeepAliveTest, SSLClientReconnection) {
  7644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7645. ASSERT_TRUE(svr.is_valid());
  7646. svr.set_keep_alive_timeout(1);
  7647. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7648. res.set_content("Hello World!", "text/plain");
  7649. });
  7650. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7651. auto se = detail::scope_exit([&] {
  7652. svr.stop();
  7653. listen_thread.join();
  7654. ASSERT_FALSE(svr.is_running());
  7655. });
  7656. svr.wait_until_ready();
  7657. SSLClient cli(HOST, PORT);
  7658. cli.enable_server_certificate_verification(false);
  7659. cli.set_keep_alive(true);
  7660. auto result = cli.Get("/hi");
  7661. ASSERT_TRUE(result);
  7662. EXPECT_EQ(StatusCode::OK_200, result->status);
  7663. result = cli.Get("/hi");
  7664. ASSERT_TRUE(result);
  7665. EXPECT_EQ(StatusCode::OK_200, result->status);
  7666. std::this_thread::sleep_for(std::chrono::seconds(2));
  7667. // Recoonect
  7668. result = cli.Get("/hi");
  7669. ASSERT_TRUE(result);
  7670. EXPECT_EQ(StatusCode::OK_200, result->status);
  7671. result = cli.Get("/hi");
  7672. ASSERT_TRUE(result);
  7673. EXPECT_EQ(StatusCode::OK_200, result->status);
  7674. }
  7675. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7677. ASSERT_TRUE(svr.is_valid());
  7678. svr.set_keep_alive_timeout(1);
  7679. std::string content = "reconnect";
  7680. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7681. res.set_content("Hello World!", "text/plain");
  7682. });
  7683. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7684. auto se = detail::scope_exit([&] {
  7685. svr.stop();
  7686. listen_thread.join();
  7687. ASSERT_FALSE(svr.is_running());
  7688. });
  7689. svr.wait_until_ready();
  7690. SSLClient cli(HOST, PORT);
  7691. cli.enable_server_certificate_verification(false);
  7692. cli.set_keep_alive(true);
  7693. auto result = cli.Post(
  7694. "/hi", content.size(),
  7695. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7696. sink.write(content.c_str(), content.size());
  7697. return true;
  7698. },
  7699. "text/plain");
  7700. ASSERT_TRUE(result);
  7701. EXPECT_EQ(200, result->status);
  7702. std::this_thread::sleep_for(std::chrono::seconds(2));
  7703. // Recoonect
  7704. result = cli.Post(
  7705. "/hi", content.size(),
  7706. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7707. sink.write(content.c_str(), content.size());
  7708. return true;
  7709. },
  7710. "text/plain");
  7711. ASSERT_TRUE(result);
  7712. EXPECT_EQ(200, result->status);
  7713. result = cli.Post(
  7714. "/hi", content.size(),
  7715. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7716. sink.write(content.c_str(), content.size());
  7717. return true;
  7718. },
  7719. "text/plain");
  7720. ASSERT_TRUE(result);
  7721. EXPECT_EQ(200, result->status);
  7722. }
  7723. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7724. using namespace httplib::tls;
  7725. {
  7726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7727. ASSERT_TRUE(svr.is_valid());
  7728. svr.Get("/sni", [&](const Request &req, Response &res) {
  7729. std::string expected = req.sni();
  7730. EXPECT_EQ(expected, req.get_param_value("expected"));
  7731. res.set_content("ok", "text/plain");
  7732. });
  7733. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7734. auto se = detail::scope_exit([&] {
  7735. svr.stop();
  7736. listen_thread.join();
  7737. ASSERT_FALSE(svr.is_running());
  7738. });
  7739. svr.wait_until_ready();
  7740. {
  7741. SSLClient cli("localhost", PORT);
  7742. cli.enable_server_certificate_verification(false);
  7743. auto res = cli.Get("/sni?expected=localhost");
  7744. ASSERT_TRUE(res);
  7745. }
  7746. {
  7747. SSLClient cli("::1", PORT);
  7748. cli.enable_server_certificate_verification(false);
  7749. auto res = cli.Get("/sni?expected=");
  7750. // NOTE: This may fail if the server is listening on IPv4 only
  7751. // (e.g., when localhost resolves to 127.0.0.1 only)
  7752. if (res) {
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. } else {
  7755. EXPECT_EQ(Error::Connection, res.error());
  7756. }
  7757. }
  7758. }
  7759. }
  7760. #endif
  7761. TEST(ClientProblemDetectionTest, ContentProvider) {
  7762. Server svr;
  7763. size_t content_length = 1024 * 1024;
  7764. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7765. res.set_content_provider(
  7766. content_length, "text/plain",
  7767. [&](size_t offset, size_t length, DataSink &sink) {
  7768. auto out_len = std::min(length, static_cast<size_t>(1024));
  7769. std::string out(out_len, '@');
  7770. sink.write(out.data(), out_len);
  7771. return offset < 4096;
  7772. },
  7773. [](bool success) { ASSERT_FALSE(success); });
  7774. });
  7775. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7776. res.set_content_provider(
  7777. 0, "text/plain",
  7778. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7779. EXPECT_TRUE(false);
  7780. return true;
  7781. },
  7782. [](bool success) { ASSERT_FALSE(success); });
  7783. });
  7784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7785. auto se = detail::scope_exit([&] {
  7786. svr.stop();
  7787. listen_thread.join();
  7788. ASSERT_FALSE(svr.is_running());
  7789. });
  7790. svr.wait_until_ready();
  7791. Client cli("localhost", PORT);
  7792. {
  7793. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7794. size_t /*data_length*/) { return false; });
  7795. ASSERT_FALSE(res);
  7796. }
  7797. {
  7798. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7799. size_t /*data_length*/) { return false; });
  7800. ASSERT_TRUE(res);
  7801. }
  7802. }
  7803. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7804. Server svr;
  7805. svr.set_error_handler([](Request const &, Response &res) -> void {
  7806. res.set_chunked_content_provider(
  7807. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7808. sink.os << "hello";
  7809. sink.os << "world";
  7810. sink.done();
  7811. return true;
  7812. });
  7813. });
  7814. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7815. auto se = detail::scope_exit([&] {
  7816. svr.stop();
  7817. listen_thread.join();
  7818. ASSERT_FALSE(svr.is_running());
  7819. });
  7820. svr.wait_until_ready();
  7821. Client cli("localhost", PORT);
  7822. auto res = cli.Get("/");
  7823. ASSERT_TRUE(res);
  7824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7825. EXPECT_EQ("helloworld", res->body);
  7826. }
  7827. TEST(LongPollingTest, ClientCloseDetection) {
  7828. Server svr;
  7829. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7830. res.set_chunked_content_provider(
  7831. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7832. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7833. sink.os << "hello";
  7834. auto count = 10;
  7835. while (count > 0 && sink.is_writable()) {
  7836. this_thread::sleep_for(chrono::milliseconds(10));
  7837. count--;
  7838. }
  7839. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7840. return true;
  7841. });
  7842. });
  7843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7844. auto se = detail::scope_exit([&] {
  7845. svr.stop();
  7846. listen_thread.join();
  7847. ASSERT_FALSE(svr.is_running());
  7848. });
  7849. svr.wait_until_ready();
  7850. Client cli("localhost", PORT);
  7851. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7852. EXPECT_EQ("hello", string(data, data_length));
  7853. return false; // close the socket immediately.
  7854. });
  7855. ASSERT_FALSE(res);
  7856. }
  7857. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7858. Server svr;
  7859. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7860. res.set_chunked_content_provider(
  7861. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7862. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7863. sink.os << "hello";
  7864. EXPECT_TRUE(sink.os.good());
  7865. // Wait for the client to close the connection
  7866. auto count = 10;
  7867. while (count > 0 && sink.is_writable()) {
  7868. this_thread::sleep_for(chrono::milliseconds(10));
  7869. count--;
  7870. }
  7871. // After client disconnect, write repeatedly until the socket
  7872. // write actually fails (small writes may be absorbed by the
  7873. // kernel buffer)
  7874. std::string chunk(1024, 'x');
  7875. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7876. sink.os << chunk;
  7877. }
  7878. EXPECT_TRUE(sink.os.fail());
  7879. return true;
  7880. });
  7881. });
  7882. auto port = svr.bind_to_any_port("localhost");
  7883. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7884. auto se = detail::scope_exit([&] {
  7885. svr.stop();
  7886. listen_thread.join();
  7887. ASSERT_FALSE(svr.is_running());
  7888. });
  7889. svr.wait_until_ready();
  7890. Client cli("localhost", port);
  7891. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7892. EXPECT_EQ("hello", string(data, data_length));
  7893. return false; // close the socket immediately.
  7894. });
  7895. ASSERT_FALSE(res);
  7896. }
  7897. TEST(GetWithParametersTest, GetWithParameters) {
  7898. Server svr;
  7899. svr.Get("/", [&](const Request &req, Response &) {
  7900. EXPECT_EQ("world", req.get_param_value("hello"));
  7901. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7902. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7903. });
  7904. svr.Get("/params", [&](const Request &req, Response &) {
  7905. EXPECT_EQ("world", req.get_param_value("hello"));
  7906. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7907. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7908. });
  7909. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7910. EXPECT_EQ("resource-id", req.matches[1]);
  7911. EXPECT_EQ("foo", req.get_param_value("param1"));
  7912. EXPECT_EQ("bar", req.get_param_value("param2"));
  7913. });
  7914. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7915. EXPECT_EQ("user-id", req.path_params.at("id"));
  7916. EXPECT_EQ("foo", req.get_param_value("param1"));
  7917. EXPECT_EQ("bar", req.get_param_value("param2"));
  7918. });
  7919. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7920. auto se = detail::scope_exit([&] {
  7921. svr.stop();
  7922. listen_thread.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. {
  7927. Client cli(HOST, PORT);
  7928. Params params;
  7929. params.emplace("hello", "world");
  7930. params.emplace("hello2", "world2");
  7931. params.emplace("hello3", "world3");
  7932. auto res = cli.Get("/", params, Headers{});
  7933. ASSERT_TRUE(res);
  7934. EXPECT_EQ(StatusCode::OK_200, res->status);
  7935. }
  7936. {
  7937. Client cli(HOST, PORT);
  7938. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7939. ASSERT_TRUE(res);
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. }
  7942. {
  7943. Client cli(HOST, PORT);
  7944. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7945. ASSERT_TRUE(res);
  7946. EXPECT_EQ(StatusCode::OK_200, res->status);
  7947. }
  7948. {
  7949. Client cli(HOST, PORT);
  7950. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7951. ASSERT_TRUE(res);
  7952. EXPECT_EQ(StatusCode::OK_200, res->status);
  7953. }
  7954. }
  7955. TEST(GetWithParametersTest, GetWithParameters2) {
  7956. Server svr;
  7957. svr.Get("/", [&](const Request &req, Response &res) {
  7958. auto text = req.get_param_value("hello");
  7959. res.set_content(text, "text/plain");
  7960. });
  7961. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7962. auto se = detail::scope_exit([&] {
  7963. svr.stop();
  7964. listen_thread.join();
  7965. ASSERT_FALSE(svr.is_running());
  7966. });
  7967. svr.wait_until_ready();
  7968. Client cli("localhost", PORT);
  7969. Params params;
  7970. params.emplace("hello", "world");
  7971. std::string body;
  7972. auto res = cli.Get("/", params, Headers{},
  7973. [&](const char *data, size_t data_length) {
  7974. body.append(data, data_length);
  7975. return true;
  7976. });
  7977. ASSERT_TRUE(res);
  7978. EXPECT_EQ(StatusCode::OK_200, res->status);
  7979. EXPECT_EQ("world", body);
  7980. }
  7981. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7982. Server svr;
  7983. svr.Get("/search", [&](const Request &req, Response &res) {
  7984. auto q = req.get_param_value("q");
  7985. res.set_content(q, "text/plain");
  7986. });
  7987. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7988. auto se = detail::scope_exit([&] {
  7989. svr.stop();
  7990. listen_thread.join();
  7991. ASSERT_FALSE(svr.is_running());
  7992. });
  7993. svr.wait_until_ready();
  7994. Client cli("localhost", PORT);
  7995. // Verify that Get(path, params) works without requiring Headers argument
  7996. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7997. ASSERT_TRUE(res);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. EXPECT_EQ("cpp-httplib", res->body);
  8000. }
  8001. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8002. auto host = "httpbingo.org";
  8003. auto path = std::string{"/range/32"};
  8004. #ifdef CPPHTTPLIB_SSL_ENABLED
  8005. SSLClient cli(host);
  8006. #else
  8007. Client cli(host);
  8008. #endif
  8009. cli.set_default_headers({make_range_header({{1, 10}})});
  8010. cli.set_connection_timeout(5);
  8011. {
  8012. auto res = cli.Get(path);
  8013. ASSERT_TRUE(res);
  8014. EXPECT_EQ("bcdefghijk", res->body);
  8015. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8016. }
  8017. {
  8018. auto res = cli.Get(path);
  8019. ASSERT_TRUE(res);
  8020. EXPECT_EQ("bcdefghijk", res->body);
  8021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8022. }
  8023. }
  8024. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8025. Server svr;
  8026. svr.set_default_headers({{"Hello", "World"}});
  8027. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8028. res.set_content("ok", "text/plain");
  8029. });
  8030. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8031. auto se = detail::scope_exit([&] {
  8032. svr.stop();
  8033. listen_thread.join();
  8034. ASSERT_FALSE(svr.is_running());
  8035. });
  8036. svr.wait_until_ready();
  8037. Client cli("localhost", PORT);
  8038. auto res = cli.Get("/");
  8039. ASSERT_TRUE(res);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. EXPECT_EQ("ok", res->body);
  8042. EXPECT_EQ("World", res->get_header_value("Hello"));
  8043. }
  8044. #ifdef CPPHTTPLIB_SSL_ENABLED
  8045. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8047. ASSERT_TRUE(svr.is_valid());
  8048. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8049. std::this_thread::sleep_for(std::chrono::seconds(2));
  8050. res.set_content("a", "text/plain");
  8051. });
  8052. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8053. res.set_content("b", "text/plain");
  8054. });
  8055. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8056. auto se = detail::scope_exit([&] {
  8057. svr.stop();
  8058. listen_thread.join();
  8059. ASSERT_FALSE(svr.is_running());
  8060. });
  8061. svr.wait_until_ready();
  8062. SSLClient cli("localhost", PORT);
  8063. cli.enable_server_certificate_verification(false);
  8064. cli.set_keep_alive(true);
  8065. cli.set_read_timeout(std::chrono::seconds(1));
  8066. auto resa = cli.Get("/a");
  8067. ASSERT_TRUE(!resa);
  8068. EXPECT_EQ(Error::Read, resa.error());
  8069. auto resb = cli.Get("/b");
  8070. ASSERT_TRUE(resb);
  8071. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8072. EXPECT_EQ("b", resb->body);
  8073. }
  8074. #endif
  8075. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8076. protected:
  8077. ServerTestWithAI_PASSIVE()
  8078. : cli_(HOST, PORT)
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. ,
  8081. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8082. #endif
  8083. {
  8084. #ifdef CPPHTTPLIB_SSL_ENABLED
  8085. cli_.enable_server_certificate_verification(false);
  8086. #endif
  8087. }
  8088. virtual void SetUp() {
  8089. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8090. res.set_content("Hello World!", "text/plain");
  8091. });
  8092. t_ = thread(
  8093. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8094. svr_.wait_until_ready();
  8095. }
  8096. virtual void TearDown() {
  8097. svr_.stop();
  8098. t_.join();
  8099. }
  8100. #ifdef CPPHTTPLIB_SSL_ENABLED
  8101. SSLClient cli_;
  8102. SSLServer svr_;
  8103. #else
  8104. Client cli_;
  8105. Server svr_;
  8106. #endif
  8107. thread t_;
  8108. };
  8109. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8110. auto res = cli_.Get("/hi");
  8111. ASSERT_TRUE(res);
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8114. EXPECT_EQ("Hello World!", res->body);
  8115. }
  8116. class ServerUpDownTest : public ::testing::Test {
  8117. protected:
  8118. ServerUpDownTest() : cli_(HOST, PORT) {}
  8119. virtual void SetUp() {
  8120. t_ = thread([&]() {
  8121. svr_.bind_to_any_port(HOST);
  8122. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8123. ASSERT_TRUE(svr_.listen_after_bind());
  8124. });
  8125. svr_.wait_until_ready();
  8126. }
  8127. virtual void TearDown() {
  8128. svr_.stop();
  8129. t_.join();
  8130. }
  8131. Client cli_;
  8132. Server svr_;
  8133. thread t_;
  8134. };
  8135. TEST_F(ServerUpDownTest, QuickStartStop) {
  8136. // Should not crash, especially when run with
  8137. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8138. }
  8139. class PayloadMaxLengthTest : public ::testing::Test {
  8140. protected:
  8141. PayloadMaxLengthTest()
  8142. : cli_(HOST, PORT)
  8143. #ifdef CPPHTTPLIB_SSL_ENABLED
  8144. ,
  8145. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8146. #endif
  8147. {
  8148. #ifdef CPPHTTPLIB_SSL_ENABLED
  8149. cli_.enable_server_certificate_verification(false);
  8150. #endif
  8151. }
  8152. virtual void SetUp() {
  8153. svr_.set_payload_max_length(8);
  8154. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8155. res.set_content("test", "text/plain");
  8156. });
  8157. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8158. svr_.wait_until_ready();
  8159. }
  8160. virtual void TearDown() {
  8161. svr_.stop();
  8162. t_.join();
  8163. }
  8164. #ifdef CPPHTTPLIB_SSL_ENABLED
  8165. SSLClient cli_;
  8166. SSLServer svr_;
  8167. #else
  8168. Client cli_;
  8169. Server svr_;
  8170. #endif
  8171. thread t_;
  8172. };
  8173. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8174. auto res = cli_.Post("/test", "123456789", "text/plain");
  8175. ASSERT_TRUE(res);
  8176. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8177. res = cli_.Post("/test", "12345678", "text/plain");
  8178. ASSERT_TRUE(res);
  8179. EXPECT_EQ(StatusCode::OK_200, res->status);
  8180. }
  8181. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8182. // Test chunked encoding with payload exceeding the 8-byte limit
  8183. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8184. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8185. ASSERT_TRUE(res);
  8186. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8187. }
  8188. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8189. // Test chunked encoding with payload within the 8-byte limit
  8190. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8191. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8192. ASSERT_TRUE(res);
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. }
  8195. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8196. // Test using send_request to send chunked data exceeding payload limit
  8197. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8198. "Host: " +
  8199. std::string(HOST) + ":" + std::to_string(PORT) +
  8200. "\r\n"
  8201. "Transfer-Encoding: chunked\r\n"
  8202. "Connection: close\r\n"
  8203. "\r\n"
  8204. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8205. "0123456789\r\n"
  8206. "0\r\n" // End chunk
  8207. "\r\n";
  8208. std::string response;
  8209. bool result = send_request(1, chunked_request, &response);
  8210. if (!result) {
  8211. // If send_request fails, it might be because the server closed the
  8212. // connection due to payload limit enforcement, which is acceptable
  8213. SUCCEED()
  8214. << "Server rejected oversized chunked request (connection closed)";
  8215. } else {
  8216. // If we got a response, check if it's an error response or connection was
  8217. // closed early Short response length indicates connection was closed due to
  8218. // payload limit
  8219. if (response.length() <= 10) {
  8220. SUCCEED() << "Server closed connection for oversized chunked request";
  8221. } else {
  8222. // Check for error status codes
  8223. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8224. response.find("Payload Too Large") != std::string::npos ||
  8225. response.find("400") != std::string::npos);
  8226. }
  8227. }
  8228. }
  8229. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8230. // Test request without Content-Length header exceeding payload limit
  8231. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8232. "Host: " +
  8233. std::string(HOST) + ":" +
  8234. std::to_string(PORT) +
  8235. "\r\n"
  8236. "Connection: close\r\n"
  8237. "\r\n";
  8238. // Add payload exceeding the 8-byte limit
  8239. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8240. request_without_content_length += large_payload;
  8241. std::string response;
  8242. bool result = send_request(1, request_without_content_length, &response);
  8243. if (!result) {
  8244. // If send_request fails, server likely closed connection due to payload
  8245. // limit
  8246. SUCCEED() << "Server rejected oversized request without Content-Length "
  8247. "(connection closed)";
  8248. } else {
  8249. // Check if server responded with error or closed connection early
  8250. if (response.length() <= 10) {
  8251. SUCCEED() << "Server closed connection for oversized request without "
  8252. "Content-Length";
  8253. } else {
  8254. // Check for error status codes
  8255. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8256. response.find("Payload Too Large") != std::string::npos ||
  8257. response.find("400") != std::string::npos);
  8258. }
  8259. }
  8260. }
  8261. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8262. // Test request without Content-Length header within payload limit
  8263. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8264. "Host: " +
  8265. std::string(HOST) + ":" +
  8266. std::to_string(PORT) +
  8267. "\r\n"
  8268. "Connection: close\r\n"
  8269. "\r\n";
  8270. // Add payload within the 8-byte limit
  8271. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8272. request_without_content_length += small_payload;
  8273. std::string response;
  8274. bool result = send_request(1, request_without_content_length, &response);
  8275. // For requests without Content-Length, the server may have different behavior
  8276. // The key is that it should not reject due to payload limit for small
  8277. // payloads
  8278. if (result) {
  8279. // Check for any HTTP response (success or error, but not connection closed)
  8280. if (response.length() > 10) {
  8281. SUCCEED()
  8282. << "Server processed request without Content-Length within limit";
  8283. } else {
  8284. // Short response might indicate connection closed, which is acceptable
  8285. SUCCEED() << "Server closed connection for request without "
  8286. "Content-Length (acceptable behavior)";
  8287. }
  8288. } else {
  8289. // Connection failure might be due to protocol requirements
  8290. SUCCEED() << "Connection issue with request without Content-Length "
  8291. "(environment-specific)";
  8292. }
  8293. }
  8294. class LargePayloadMaxLengthTest : public ::testing::Test {
  8295. protected:
  8296. LargePayloadMaxLengthTest()
  8297. : cli_(HOST, PORT)
  8298. #ifdef CPPHTTPLIB_SSL_ENABLED
  8299. ,
  8300. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8301. #endif
  8302. {
  8303. #ifdef CPPHTTPLIB_SSL_ENABLED
  8304. cli_.enable_server_certificate_verification(false);
  8305. #endif
  8306. }
  8307. virtual void SetUp() {
  8308. // Set 10MB payload limit
  8309. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8310. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8311. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8312. res.set_content("Large payload test", "text/plain");
  8313. });
  8314. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8315. svr_.wait_until_ready();
  8316. }
  8317. virtual void TearDown() {
  8318. svr_.stop();
  8319. t_.join();
  8320. }
  8321. #ifdef CPPHTTPLIB_SSL_ENABLED
  8322. SSLClient cli_;
  8323. SSLServer svr_;
  8324. #else
  8325. Client cli_;
  8326. Server svr_;
  8327. #endif
  8328. thread t_;
  8329. };
  8330. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8331. // Test chunked encoding with payload within 10MB limit
  8332. std::string medium_payload(5 * 1024 * 1024,
  8333. 'A'); // 5MB payload, within 10MB limit
  8334. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8335. ASSERT_TRUE(res);
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. }
  8338. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8339. // Test chunked encoding with payload exceeding 10MB limit
  8340. std::string large_payload(12 * 1024 * 1024,
  8341. 'B'); // 12MB payload, exceeds 10MB limit
  8342. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8343. // Server may either return 413 or close the connection
  8344. if (res) {
  8345. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8346. } else {
  8347. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8348. }
  8349. }
  8350. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8351. // Test request without Content-Length header within 10MB limit
  8352. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8353. "Host: " +
  8354. std::string(HOST) + ":" +
  8355. std::to_string(PORT) +
  8356. "\r\n"
  8357. "Connection: close\r\n"
  8358. "\r\n";
  8359. // Add 1MB payload (within 10MB limit)
  8360. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8361. request_without_content_length += medium_payload;
  8362. std::string response;
  8363. bool result = send_request(5, request_without_content_length, &response);
  8364. if (result) {
  8365. // Should get a proper HTTP response for payloads within limit
  8366. if (response.length() > 10) {
  8367. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8368. "10MB limit";
  8369. } else {
  8370. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8371. "Content-Length)";
  8372. }
  8373. } else {
  8374. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8375. }
  8376. }
  8377. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8378. // Test request without Content-Length header exceeding 10MB limit
  8379. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8380. "Host: " +
  8381. std::string(HOST) + ":" +
  8382. std::to_string(PORT) +
  8383. "\r\n"
  8384. "Connection: close\r\n"
  8385. "\r\n";
  8386. // Add 12MB payload (exceeds 10MB limit)
  8387. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8388. request_without_content_length += large_payload;
  8389. std::string response;
  8390. bool result = send_request(10, request_without_content_length, &response);
  8391. if (!result) {
  8392. // Server should close connection due to payload limit
  8393. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8394. "(connection closed)";
  8395. } else {
  8396. // Check for error response
  8397. if (response.length() <= 10) {
  8398. SUCCEED()
  8399. << "Server closed connection for 12MB request exceeding 10MB limit";
  8400. } else {
  8401. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8402. response.find("Payload Too Large") != std::string::npos ||
  8403. response.find("400") != std::string::npos);
  8404. }
  8405. }
  8406. }
  8407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8408. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8409. // path.
  8410. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8411. Server svr;
  8412. const size_t LIMIT = 64 * 1024; // 64KB
  8413. svr.set_payload_max_length(LIMIT);
  8414. size_t total = 0;
  8415. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8416. const ContentReader &content_reader) {
  8417. content_reader([&](const char * /*data*/, size_t len) {
  8418. total += len;
  8419. return true;
  8420. });
  8421. res.status = 200;
  8422. res.set_content("stream_ok", "text/plain");
  8423. });
  8424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8425. auto se = detail::scope_exit([&] {
  8426. svr.stop();
  8427. thread.join();
  8428. ASSERT_FALSE(svr.is_running());
  8429. });
  8430. svr.wait_until_ready();
  8431. // Prepare 256KB raw data and gzip-compress it
  8432. std::string raw(256 * 1024, 'A');
  8433. std::string gz;
  8434. {
  8435. z_stream zs{};
  8436. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8437. Z_DEFAULT_STRATEGY);
  8438. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8439. zs.avail_in = static_cast<uInt>(raw.size());
  8440. char outbuf[4096];
  8441. int ret;
  8442. do {
  8443. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8444. zs.avail_out = sizeof(outbuf);
  8445. ret = deflate(&zs, Z_FINISH);
  8446. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8447. } while (ret != Z_STREAM_END);
  8448. deflateEnd(&zs);
  8449. }
  8450. Client cli(HOST, PORT);
  8451. cli.set_connection_timeout(std::chrono::seconds(5));
  8452. Headers headers = {{"Content-Encoding", "gzip"}};
  8453. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8454. "application/octet-stream");
  8455. ASSERT_TRUE(res);
  8456. // Server must reject oversized decompressed payloads with 413.
  8457. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8458. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8459. EXPECT_LE(total, LIMIT);
  8460. }
  8461. #endif
  8462. // Regression test for DoS vulnerability: a malicious server sending a response
  8463. // without Content-Length header must not cause unbounded memory consumption on
  8464. // the client side. The client should stop reading after a reasonable limit,
  8465. // similar to the server-side set_payload_max_length protection.
  8466. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8467. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8468. #ifndef _WIN32
  8469. signal(SIGPIPE, SIG_IGN);
  8470. #endif
  8471. auto server_thread = std::thread([] {
  8472. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8473. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8474. default_socket_options(srv);
  8475. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8476. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8477. sockaddr_in addr{};
  8478. addr.sin_family = AF_INET;
  8479. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8480. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8481. int opt = 1;
  8482. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8483. #ifdef _WIN32
  8484. reinterpret_cast<const char *>(&opt),
  8485. #else
  8486. &opt,
  8487. #endif
  8488. sizeof(opt));
  8489. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8490. ::listen(srv, 1);
  8491. sockaddr_in cli_addr{};
  8492. socklen_t cli_len = sizeof(cli_addr);
  8493. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8494. if (cli != INVALID_SOCKET) {
  8495. char buf[4096];
  8496. ::recv(cli, buf, sizeof(buf), 0);
  8497. // Malicious response: no Content-Length, no chunked encoding
  8498. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8499. "Connection: close\r\n"
  8500. "\r\n";
  8501. ::send(cli,
  8502. #ifdef _WIN32
  8503. static_cast<const char *>(response_header.c_str()),
  8504. static_cast<int>(response_header.size()),
  8505. #else
  8506. response_header.c_str(), response_header.size(),
  8507. #endif
  8508. 0);
  8509. // Send 10MB of data
  8510. std::string chunk(64 * 1024, 'A');
  8511. size_t total_sent = 0;
  8512. while (total_sent < MALICIOUS_DATA_SIZE) {
  8513. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8514. auto sent = ::send(cli,
  8515. #ifdef _WIN32
  8516. static_cast<const char *>(chunk.c_str()),
  8517. static_cast<int>(to_send),
  8518. #else
  8519. chunk.c_str(), to_send,
  8520. #endif
  8521. 0);
  8522. if (sent <= 0) break;
  8523. total_sent += static_cast<size_t>(sent);
  8524. }
  8525. detail::close_socket(cli);
  8526. }
  8527. detail::close_socket(srv);
  8528. });
  8529. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8530. size_t total_read = 0;
  8531. {
  8532. Client cli("127.0.0.1", PORT + 2);
  8533. cli.set_read_timeout(5, 0);
  8534. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8535. auto stream = cli.open_stream("GET", "/malicious");
  8536. ASSERT_TRUE(stream.is_valid());
  8537. char buffer[64 * 1024];
  8538. ssize_t n;
  8539. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8540. total_read += static_cast<size_t>(n);
  8541. }
  8542. } // StreamHandle and Client destroyed here, closing the socket
  8543. server_thread.join();
  8544. // With set_payload_max_length, the client must stop reading before consuming
  8545. // all 10MB. The read loop should be cut off at or near the configured limit.
  8546. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8547. << "Client read " << total_read << " bytes, exceeding the configured "
  8548. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8549. }
  8550. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8551. // the entire response body without truncation.
  8552. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8553. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8554. #ifndef _WIN32
  8555. signal(SIGPIPE, SIG_IGN);
  8556. #endif
  8557. auto server_thread = std::thread([] {
  8558. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8559. default_socket_options(srv);
  8560. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8561. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8562. sockaddr_in addr{};
  8563. addr.sin_family = AF_INET;
  8564. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8565. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8566. int opt = 1;
  8567. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8568. #ifdef _WIN32
  8569. reinterpret_cast<const char *>(&opt),
  8570. #else
  8571. &opt,
  8572. #endif
  8573. sizeof(opt));
  8574. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8575. ::listen(srv, 1);
  8576. sockaddr_in cli_addr{};
  8577. socklen_t cli_len = sizeof(cli_addr);
  8578. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8579. if (cli != INVALID_SOCKET) {
  8580. char buf[4096];
  8581. ::recv(cli, buf, sizeof(buf), 0);
  8582. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8583. "Connection: close\r\n"
  8584. "\r\n";
  8585. ::send(cli,
  8586. #ifdef _WIN32
  8587. static_cast<const char *>(response_header.c_str()),
  8588. static_cast<int>(response_header.size()),
  8589. #else
  8590. response_header.c_str(), response_header.size(),
  8591. #endif
  8592. 0);
  8593. std::string chunk(64 * 1024, 'A');
  8594. size_t total_sent = 0;
  8595. while (total_sent < DATA_SIZE) {
  8596. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8597. auto sent = ::send(cli,
  8598. #ifdef _WIN32
  8599. static_cast<const char *>(chunk.c_str()),
  8600. static_cast<int>(to_send),
  8601. #else
  8602. chunk.c_str(), to_send,
  8603. #endif
  8604. 0);
  8605. if (sent <= 0) break;
  8606. total_sent += static_cast<size_t>(sent);
  8607. }
  8608. #ifdef _WIN32
  8609. ::shutdown(cli, SD_SEND);
  8610. #else
  8611. ::shutdown(cli, SHUT_WR);
  8612. #endif
  8613. // Drain until the client closes its end, ensuring all data is delivered
  8614. char drain[1024];
  8615. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8616. detail::close_socket(cli);
  8617. }
  8618. detail::close_socket(srv);
  8619. });
  8620. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8621. size_t total_read = 0;
  8622. {
  8623. Client cli("127.0.0.1", PORT + 2);
  8624. cli.set_read_timeout(5, 0);
  8625. cli.set_payload_max_length(0); // 0 means no limit
  8626. auto stream = cli.open_stream("GET", "/data");
  8627. ASSERT_TRUE(stream.is_valid());
  8628. char buffer[64 * 1024];
  8629. ssize_t n;
  8630. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8631. total_read += static_cast<size_t>(n);
  8632. }
  8633. }
  8634. server_thread.join();
  8635. EXPECT_EQ(total_read, DATA_SIZE)
  8636. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8637. << " bytes without truncation, but only read " << total_read << " bytes.";
  8638. }
  8639. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8640. // enormous Content-Length must not cause the client to pre-allocate a huge
  8641. // response body buffer. The reservation is capped at payload_max_length_, and
  8642. // the read itself fails when the body exceeds the limit.
  8643. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8644. #ifndef _WIN32
  8645. signal(SIGPIPE, SIG_IGN);
  8646. #endif
  8647. auto server_thread = std::thread([] {
  8648. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8649. default_socket_options(srv);
  8650. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8651. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8652. sockaddr_in addr{};
  8653. addr.sin_family = AF_INET;
  8654. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8655. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8656. int opt = 1;
  8657. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8658. #ifdef _WIN32
  8659. reinterpret_cast<const char *>(&opt),
  8660. #else
  8661. &opt,
  8662. #endif
  8663. sizeof(opt));
  8664. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8665. ::listen(srv, 1);
  8666. sockaddr_in cli_addr{};
  8667. socklen_t cli_len = sizeof(cli_addr);
  8668. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8669. if (cli != INVALID_SOCKET) {
  8670. char buf[4096];
  8671. ::recv(cli, buf, sizeof(buf), 0);
  8672. // Malicious response: claim a 20GB body but send only a tiny payload.
  8673. std::string response = "HTTP/1.1 200 OK\r\n"
  8674. "Content-Length: 20000000000\r\n"
  8675. "\r\n"
  8676. "abc";
  8677. ::send(cli,
  8678. #ifdef _WIN32
  8679. static_cast<const char *>(response.c_str()),
  8680. static_cast<int>(response.size()),
  8681. #else
  8682. response.c_str(), response.size(),
  8683. #endif
  8684. 0);
  8685. detail::close_socket(cli);
  8686. }
  8687. detail::close_socket(srv);
  8688. });
  8689. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8690. {
  8691. Client cli("127.0.0.1", PORT + 2);
  8692. cli.set_read_timeout(5, 0);
  8693. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8694. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8695. // (server claims more bytes than payload_max_length permits), but it must
  8696. // not exhaust memory before getting there.
  8697. auto res = cli.Get("/malicious");
  8698. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8699. }
  8700. server_thread.join();
  8701. }
  8702. // Verify that content_receiver bypasses the default payload_max_length,
  8703. // allowing streaming downloads larger than 100MB without requiring an explicit
  8704. // set_payload_max_length call.
  8705. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8706. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8707. #ifndef _WIN32
  8708. signal(SIGPIPE, SIG_IGN);
  8709. #endif
  8710. auto server_thread = std::thread([] {
  8711. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8712. default_socket_options(srv);
  8713. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8715. sockaddr_in addr{};
  8716. addr.sin_family = AF_INET;
  8717. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8718. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8719. int opt = 1;
  8720. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8721. #ifdef _WIN32
  8722. reinterpret_cast<const char *>(&opt),
  8723. #else
  8724. &opt,
  8725. #endif
  8726. sizeof(opt));
  8727. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8728. ::listen(srv, 1);
  8729. sockaddr_in cli_addr{};
  8730. socklen_t cli_len = sizeof(cli_addr);
  8731. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8732. if (cli != INVALID_SOCKET) {
  8733. char buf[4096];
  8734. ::recv(cli, buf, sizeof(buf), 0);
  8735. // Response with Content-Length larger than default 100MB limit
  8736. auto content_length = std::to_string(DATA_SIZE);
  8737. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8738. "Content-Length: " +
  8739. content_length +
  8740. "\r\n"
  8741. "Connection: close\r\n"
  8742. "\r\n";
  8743. ::send(cli,
  8744. #ifdef _WIN32
  8745. static_cast<const char *>(response_header.c_str()),
  8746. static_cast<int>(response_header.size()),
  8747. #else
  8748. response_header.c_str(), response_header.size(),
  8749. #endif
  8750. 0);
  8751. std::string chunk(64 * 1024, 'A');
  8752. size_t total_sent = 0;
  8753. while (total_sent < DATA_SIZE) {
  8754. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8755. auto sent = ::send(cli,
  8756. #ifdef _WIN32
  8757. static_cast<const char *>(chunk.c_str()),
  8758. static_cast<int>(to_send),
  8759. #else
  8760. chunk.c_str(), to_send,
  8761. #endif
  8762. 0);
  8763. if (sent <= 0) break;
  8764. total_sent += static_cast<size_t>(sent);
  8765. }
  8766. detail::close_socket(cli);
  8767. }
  8768. detail::close_socket(srv);
  8769. });
  8770. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8771. size_t total_received = 0;
  8772. {
  8773. Client cli("127.0.0.1", PORT + 2);
  8774. cli.set_read_timeout(10, 0);
  8775. // Do NOT call set_payload_max_length — use the default 100MB limit
  8776. auto res =
  8777. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8778. total_received += data_length;
  8779. return true;
  8780. });
  8781. ASSERT_TRUE(res);
  8782. EXPECT_EQ(StatusCode::OK_200, res->status);
  8783. }
  8784. server_thread.join();
  8785. EXPECT_EQ(total_received, DATA_SIZE)
  8786. << "With content_receiver, the client should read all " << DATA_SIZE
  8787. << " bytes despite the default 100MB payload_max_length, but only read "
  8788. << total_received << " bytes.";
  8789. }
  8790. // Verify that an explicit set_payload_max_length smaller than the response is
  8791. // enforced even when a content_receiver is used.
  8792. TEST(ClientVulnerabilityTest,
  8793. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8794. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8795. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8796. #ifndef _WIN32
  8797. signal(SIGPIPE, SIG_IGN);
  8798. #endif
  8799. auto server_thread = std::thread([] {
  8800. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8801. default_socket_options(srv);
  8802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8804. sockaddr_in addr{};
  8805. addr.sin_family = AF_INET;
  8806. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8807. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8808. int opt = 1;
  8809. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8810. #ifdef _WIN32
  8811. reinterpret_cast<const char *>(&opt),
  8812. #else
  8813. &opt,
  8814. #endif
  8815. sizeof(opt));
  8816. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8817. ::listen(srv, 1);
  8818. sockaddr_in cli_addr{};
  8819. socklen_t cli_len = sizeof(cli_addr);
  8820. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8821. if (cli != INVALID_SOCKET) {
  8822. char buf[4096];
  8823. ::recv(cli, buf, sizeof(buf), 0);
  8824. auto content_length = std::to_string(DATA_SIZE);
  8825. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8826. "Content-Length: " +
  8827. content_length +
  8828. "\r\n"
  8829. "Connection: close\r\n"
  8830. "\r\n";
  8831. ::send(cli,
  8832. #ifdef _WIN32
  8833. static_cast<const char *>(response_header.c_str()),
  8834. static_cast<int>(response_header.size()),
  8835. #else
  8836. response_header.c_str(), response_header.size(),
  8837. #endif
  8838. 0);
  8839. std::string chunk(64 * 1024, 'A');
  8840. size_t total_sent = 0;
  8841. while (total_sent < DATA_SIZE) {
  8842. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8843. auto sent = ::send(cli,
  8844. #ifdef _WIN32
  8845. static_cast<const char *>(chunk.c_str()),
  8846. static_cast<int>(to_send),
  8847. #else
  8848. chunk.c_str(), to_send,
  8849. #endif
  8850. 0);
  8851. if (sent <= 0) break;
  8852. total_sent += static_cast<size_t>(sent);
  8853. }
  8854. detail::close_socket(cli);
  8855. }
  8856. detail::close_socket(srv);
  8857. });
  8858. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8859. size_t total_received = 0;
  8860. {
  8861. Client cli("127.0.0.1", PORT + 2);
  8862. cli.set_read_timeout(10, 0);
  8863. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8864. auto res =
  8865. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8866. total_received += data_length;
  8867. return true;
  8868. });
  8869. // Should fail because 200MB exceeds the explicit 150MB limit
  8870. EXPECT_FALSE(res);
  8871. }
  8872. server_thread.join();
  8873. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8874. << "Client with content_receiver should respect the explicit "
  8875. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8876. << total_received << " bytes.";
  8877. }
  8878. // Verify that an explicit set_payload_max_length larger than the response
  8879. // allows the content_receiver to read all data successfully.
  8880. TEST(ClientVulnerabilityTest,
  8881. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8882. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8883. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8884. #ifndef _WIN32
  8885. signal(SIGPIPE, SIG_IGN);
  8886. #endif
  8887. auto server_thread = std::thread([] {
  8888. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8889. default_socket_options(srv);
  8890. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8892. sockaddr_in addr{};
  8893. addr.sin_family = AF_INET;
  8894. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8895. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8896. int opt = 1;
  8897. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8898. #ifdef _WIN32
  8899. reinterpret_cast<const char *>(&opt),
  8900. #else
  8901. &opt,
  8902. #endif
  8903. sizeof(opt));
  8904. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8905. ::listen(srv, 1);
  8906. sockaddr_in cli_addr{};
  8907. socklen_t cli_len = sizeof(cli_addr);
  8908. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8909. if (cli != INVALID_SOCKET) {
  8910. char buf[4096];
  8911. ::recv(cli, buf, sizeof(buf), 0);
  8912. auto content_length = std::to_string(DATA_SIZE);
  8913. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8914. "Content-Length: " +
  8915. content_length +
  8916. "\r\n"
  8917. "Connection: close\r\n"
  8918. "\r\n";
  8919. ::send(cli,
  8920. #ifdef _WIN32
  8921. static_cast<const char *>(response_header.c_str()),
  8922. static_cast<int>(response_header.size()),
  8923. #else
  8924. response_header.c_str(), response_header.size(),
  8925. #endif
  8926. 0);
  8927. std::string chunk(64 * 1024, 'A');
  8928. size_t total_sent = 0;
  8929. while (total_sent < DATA_SIZE) {
  8930. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8931. auto sent = ::send(cli,
  8932. #ifdef _WIN32
  8933. static_cast<const char *>(chunk.c_str()),
  8934. static_cast<int>(to_send),
  8935. #else
  8936. chunk.c_str(), to_send,
  8937. #endif
  8938. 0);
  8939. if (sent <= 0) break;
  8940. total_sent += static_cast<size_t>(sent);
  8941. }
  8942. #ifdef _WIN32
  8943. ::shutdown(cli, SD_SEND);
  8944. #else
  8945. ::shutdown(cli, SHUT_WR);
  8946. #endif
  8947. char drain[1024];
  8948. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8949. detail::close_socket(cli);
  8950. }
  8951. detail::close_socket(srv);
  8952. });
  8953. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8954. size_t total_received = 0;
  8955. {
  8956. Client cli("127.0.0.1", PORT + 2);
  8957. cli.set_read_timeout(10, 0);
  8958. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8959. auto res =
  8960. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8961. total_received += data_length;
  8962. return true;
  8963. });
  8964. ASSERT_TRUE(res);
  8965. EXPECT_EQ(StatusCode::OK_200, res->status);
  8966. }
  8967. server_thread.join();
  8968. EXPECT_EQ(total_received, DATA_SIZE)
  8969. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8970. << " bytes (larger than " << DATA_SIZE
  8971. << " bytes response), content_receiver should read all data, but only "
  8972. "read "
  8973. << total_received << " bytes.";
  8974. }
  8975. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8976. // Regression test for "zip bomb" attack on the client side: a malicious server
  8977. // sends a small gzip-compressed response that decompresses to a huge payload.
  8978. // The client must enforce payload_max_length on the decompressed size.
  8979. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8980. constexpr size_t DECOMPRESSED_SIZE =
  8981. 10 * 1024 * 1024; // 10MB after decompression
  8982. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8983. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8984. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8985. std::string compressed;
  8986. {
  8987. httplib::detail::gzip_compressor compressor;
  8988. bool ok =
  8989. compressor.compress(uncompressed.data(), uncompressed.size(),
  8990. /*last=*/true, [&](const char *buf, size_t len) {
  8991. compressed.append(buf, len);
  8992. return true;
  8993. });
  8994. ASSERT_TRUE(ok);
  8995. }
  8996. // Sanity: compressed data should be much smaller than the decompressed size
  8997. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8998. #ifndef _WIN32
  8999. signal(SIGPIPE, SIG_IGN);
  9000. #endif
  9001. // Set up the listening socket in the main thread so the server is guaranteed
  9002. // to be ready before the client connects (eliminates race condition).
  9003. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9004. default_socket_options(srv);
  9005. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9007. sockaddr_in addr{};
  9008. addr.sin_family = AF_INET;
  9009. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9010. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9011. int opt = 1;
  9012. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9013. #ifdef _WIN32
  9014. reinterpret_cast<const char *>(&opt),
  9015. #else
  9016. &opt,
  9017. #endif
  9018. sizeof(opt));
  9019. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9020. ASSERT_EQ(0, ::listen(srv, 1));
  9021. auto server_thread = std::thread([&compressed, srv] {
  9022. sockaddr_in cli_addr{};
  9023. socklen_t cli_len = sizeof(cli_addr);
  9024. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9025. if (cli != INVALID_SOCKET) {
  9026. // Read the full HTTP request (until \r\n\r\n)
  9027. char buf[4096];
  9028. size_t total = 0;
  9029. while (total < sizeof(buf)) {
  9030. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9031. if (n <= 0) break;
  9032. total += static_cast<size_t>(n);
  9033. // Check for end of headers
  9034. if (total >= 4) {
  9035. std::string req(buf, total);
  9036. if (req.find("\r\n\r\n") != std::string::npos) break;
  9037. }
  9038. }
  9039. // Malicious response: gzip-compressed body, no Content-Length
  9040. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9041. "Content-Encoding: gzip\r\n"
  9042. "Connection: close\r\n"
  9043. "\r\n";
  9044. ::send(cli,
  9045. #ifdef _WIN32
  9046. static_cast<const char *>(response_header.c_str()),
  9047. static_cast<int>(response_header.size()),
  9048. #else
  9049. response_header.c_str(), response_header.size(),
  9050. #endif
  9051. 0);
  9052. // Send the compressed payload (small on the wire, huge when decompressed)
  9053. size_t total_sent = 0;
  9054. while (total_sent < compressed.size()) {
  9055. auto to_send = std::min(compressed.size() - total_sent,
  9056. static_cast<size_t>(64 * 1024));
  9057. auto sent =
  9058. ::send(cli,
  9059. #ifdef _WIN32
  9060. static_cast<const char *>(compressed.c_str() + total_sent),
  9061. static_cast<int>(to_send),
  9062. #else
  9063. compressed.c_str() + total_sent, to_send,
  9064. #endif
  9065. 0);
  9066. if (sent <= 0) break;
  9067. total_sent += static_cast<size_t>(sent);
  9068. }
  9069. detail::close_socket(cli);
  9070. }
  9071. });
  9072. auto se = detail::scope_exit([&] {
  9073. detail::close_socket(srv);
  9074. server_thread.join();
  9075. });
  9076. size_t total_decompressed = 0;
  9077. {
  9078. Client cli("127.0.0.1", PORT + 3);
  9079. cli.set_read_timeout(5, 0);
  9080. cli.set_decompress(true);
  9081. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9082. auto stream = cli.open_stream("GET", "/zipbomb");
  9083. ASSERT_TRUE(stream.is_valid());
  9084. char buffer[64 * 1024];
  9085. ssize_t n;
  9086. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9087. total_decompressed += static_cast<size_t>(n);
  9088. }
  9089. }
  9090. // The decompressed size must be capped by payload_max_length. Without
  9091. // protection, the client would decompress the full 10MB from a tiny
  9092. // compressed payload, enabling a zip bomb DoS attack.
  9093. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9094. << "Client decompressed " << total_decompressed
  9095. << " bytes from a gzip response. The decompressed size should be "
  9096. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9097. }
  9098. #endif
  9099. TEST(HostAndPortPropertiesTest, NoSSL) {
  9100. httplib::Client cli("www.google.com", 1234);
  9101. ASSERT_EQ("www.google.com", cli.host());
  9102. ASSERT_EQ(1234, cli.port());
  9103. }
  9104. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9105. httplib::Client cli("www.google.com:1234");
  9106. ASSERT_EQ("www.google.com", cli.host());
  9107. ASSERT_EQ(1234, cli.port());
  9108. }
  9109. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9110. // Port number that overflows int — should not crash, client becomes invalid
  9111. httplib::Client cli("http://www.google.com:99999999999999999999");
  9112. ASSERT_FALSE(cli.is_valid());
  9113. }
  9114. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9115. // Port 99999 exceeds valid range (1-65535) — should not crash
  9116. httplib::Client cli("http://www.google.com:99999");
  9117. ASSERT_FALSE(cli.is_valid());
  9118. }
  9119. #ifdef CPPHTTPLIB_SSL_ENABLED
  9120. TEST(HostAndPortPropertiesTest, SSL) {
  9121. httplib::SSLClient cli("www.google.com");
  9122. ASSERT_EQ("www.google.com", cli.host());
  9123. ASSERT_EQ(443, cli.port());
  9124. }
  9125. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9126. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9127. std::string cert;
  9128. read_file(CA_CERT_FILE, cert);
  9129. httplib::SSLClient httplib_client("www.google.com");
  9130. // Load CA store first time
  9131. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9132. // Load CA store second time (update)
  9133. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9134. // Verify client is still valid and can make connections
  9135. httplib_client.enable_server_certificate_verification(true);
  9136. auto res = httplib_client.Get("/");
  9137. ASSERT_TRUE(res);
  9138. // Google may return 200 or 301 depending on various factors
  9139. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9140. res->status == StatusCode::MovedPermanently_301);
  9141. }
  9142. TEST(SSLClientTest, ServerNameIndication_Online) {
  9143. auto host = "httpbingo.org";
  9144. auto path = std::string{"/get"};
  9145. SSLClient cli(host, 443);
  9146. auto res = cli.Get(path);
  9147. ASSERT_TRUE(res);
  9148. ASSERT_EQ(StatusCode::OK_200, res->status);
  9149. }
  9150. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9151. // Use a site that will cause SSL verification failure due to self-signed cert
  9152. SSLClient cli("self-signed.badssl.com", 443);
  9153. cli.enable_server_certificate_verification(true);
  9154. auto res = cli.Get("/");
  9155. ASSERT_TRUE(!res);
  9156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9157. // Verify backend error is captured for SSLServerVerification
  9158. // This occurs when certificate verification fails
  9159. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9160. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9161. EXPECT_NE(0UL, res.ssl_backend_error());
  9162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9163. // For OpenSSL, ssl_error is 0 for verification errors
  9164. EXPECT_EQ(0, res.ssl_error());
  9165. #if !defined(_WIN32) || \
  9166. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9167. // On non-Windows or when Windows Schannel is disabled, the error comes
  9168. // from OpenSSL's verification
  9169. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9170. res.ssl_backend_error());
  9171. #endif
  9172. #endif
  9173. }
  9174. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9175. // Use a site where hostname doesn't match the certificate
  9176. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9177. SSLClient cli("wrong.host.badssl.com", 443);
  9178. cli.enable_server_certificate_verification(true);
  9179. cli.enable_server_hostname_verification(true);
  9180. auto res = cli.Get("/");
  9181. ASSERT_TRUE(!res);
  9182. // The error type depends on when hostname verification occurs:
  9183. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9184. // - Mbed TLS: SSLServerVerification (during handshake)
  9185. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9186. res.error() == Error::SSLServerVerification);
  9187. // Verify backend error is captured for hostname verification failure
  9188. EXPECT_NE(0UL, res.ssl_backend_error());
  9189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9190. // For OpenSSL, ssl_error is 0 for verification errors
  9191. EXPECT_EQ(0, res.ssl_error());
  9192. #if !defined(_WIN32) || \
  9193. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9194. // On non-Windows or when Windows Schannel is disabled, the error comes
  9195. // from OpenSSL's hostname verification
  9196. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9197. res.ssl_backend_error());
  9198. #endif
  9199. #endif
  9200. }
  9201. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9202. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9203. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9204. SSLClient cli("www.google.com", 443);
  9205. cli.enable_server_certificate_verification(true);
  9206. auto res = cli.Get("/");
  9207. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9208. }
  9209. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9210. SSLClient cli("www.google.com", 443);
  9211. cli.enable_server_certificate_verification(true);
  9212. cli.enable_windows_certificate_verification(false);
  9213. auto res = cli.Get("/");
  9214. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9215. }
  9216. #endif
  9217. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9218. Client cli("https://google.com");
  9219. auto res = cli.Get("/");
  9220. ASSERT_TRUE(res);
  9221. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9222. }
  9223. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9224. SSLClient cli("google.com");
  9225. cli.set_ca_cert_path(CA_CERT_FILE);
  9226. auto res = cli.Get("/");
  9227. ASSERT_TRUE(res);
  9228. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9229. }
  9230. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9231. SSLClient cli("google.com");
  9232. cli.enable_server_certificate_verification(true);
  9233. cli.set_ca_cert_path("hello");
  9234. auto res = cli.Get("/");
  9235. ASSERT_TRUE(!res);
  9236. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9237. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9238. // should be set
  9239. EXPECT_EQ(0, res.ssl_error());
  9240. // Verify backend error is captured for SSLLoadingCerts
  9241. // This error occurs when loading CA certificates fails
  9242. EXPECT_NE(0UL, res.ssl_backend_error());
  9243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9244. // OpenSSL specific error codes:
  9245. // > openssl errstr 0x80000002
  9246. // error:80000002:system library::No such file or directory
  9247. // > openssl errstr 0xA000126
  9248. // error:0A000126:SSL routines::unexpected eof while reading
  9249. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9250. res.ssl_backend_error() == 0xA000126);
  9251. #endif
  9252. }
  9253. TEST(SSLClientTest, ServerCertificateVerification4) {
  9254. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9255. ASSERT_TRUE(svr.is_valid());
  9256. svr.Get("/test", [&](const Request &, Response &res) {
  9257. res.set_content("test", "text/plain");
  9258. svr.stop();
  9259. ASSERT_TRUE(true);
  9260. });
  9261. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9262. auto se = detail::scope_exit([&] {
  9263. t.join();
  9264. ASSERT_FALSE(svr.is_running());
  9265. });
  9266. svr.wait_until_ready();
  9267. SSLClient cli("127.0.0.1", PORT);
  9268. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9269. cli.enable_server_certificate_verification(true);
  9270. cli.set_connection_timeout(30);
  9271. auto res = cli.Get("/test");
  9272. ASSERT_TRUE(res);
  9273. ASSERT_EQ(StatusCode::OK_200, res->status);
  9274. }
  9275. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9276. std::string cert;
  9277. read_file(CA_CERT_FILE, cert);
  9278. SSLClient cli("google.com");
  9279. cli.load_ca_cert_store(cert.data(), cert.size());
  9280. const auto res = cli.Get("/");
  9281. ASSERT_TRUE(res);
  9282. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9283. }
  9284. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9285. // clang-format off
  9286. static constexpr char cert[] =
  9287. "GlobalSign Root CA\n"
  9288. "==================\n"
  9289. "-----BEGIN CERTIFICATE-----\n"
  9290. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9291. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9292. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9293. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9294. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9295. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9296. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9297. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9298. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9299. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9300. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9301. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9302. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9303. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9304. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9305. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9306. "-----END CERTIFICATE-----\n";
  9307. // clang-format on
  9308. SSLClient cli("google.com");
  9309. cli.load_ca_cert_store(cert, sizeof(cert));
  9310. const auto res = cli.Get("/");
  9311. ASSERT_TRUE(res);
  9312. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9313. }
  9314. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9315. SSLClient cli("www.youtube.com");
  9316. cli.set_ca_cert_path(CA_CERT_FILE);
  9317. cli.enable_server_certificate_verification(true);
  9318. cli.set_follow_location(true);
  9319. auto res = cli.Get("/");
  9320. ASSERT_TRUE(res);
  9321. ASSERT_EQ(StatusCode::OK_200, res->status);
  9322. }
  9323. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9324. SSLClient cli("wWw.YouTube.Com");
  9325. cli.set_ca_cert_path(CA_CERT_FILE);
  9326. cli.enable_server_certificate_verification(true);
  9327. cli.enable_server_hostname_verification(true);
  9328. cli.set_follow_location(true);
  9329. auto res = cli.Get("/");
  9330. ASSERT_TRUE(res);
  9331. ASSERT_EQ(StatusCode::OK_200, res->status);
  9332. }
  9333. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9334. SSLClient cli("gOoGlE.COm");
  9335. cli.enable_server_certificate_verification(true);
  9336. cli.enable_server_hostname_verification(true);
  9337. cli.set_follow_location(true);
  9338. auto res = cli.Get("/");
  9339. ASSERT_TRUE(res);
  9340. ASSERT_EQ(StatusCode::OK_200, res->status);
  9341. }
  9342. TEST(SSLClientTest, Issue2004_Online) {
  9343. Client client("https://google.com");
  9344. client.set_follow_location(true);
  9345. auto res = client.Get("/");
  9346. ASSERT_TRUE(res);
  9347. ASSERT_EQ(StatusCode::OK_200, res->status);
  9348. auto body = res->body;
  9349. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9350. }
  9351. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9352. // Create SSLClient with invalid cert/key to make is_valid() return false
  9353. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9354. "nonexistent_key.pem");
  9355. // is_valid() should be false due to cert loading failure
  9356. ASSERT_FALSE(cli.is_valid());
  9357. auto res = cli.Get("/");
  9358. ASSERT_FALSE(res);
  9359. EXPECT_EQ(Error::SSLConnection, res.error());
  9360. }
  9361. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9362. // Test for Issue #2251: SSL error not properly reported when client cert
  9363. // and key paths are swapped or mismatched
  9364. // This simulates the scenario where user accidentally swaps the cert and key
  9365. // files
  9366. // Using client cert file as private key and vice versa (completely wrong)
  9367. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9368. // Should fail validation due to cert/key mismatch
  9369. ASSERT_FALSE(cli.is_valid());
  9370. // Attempt to make a request should fail with proper error
  9371. auto res = cli.Get("/");
  9372. ASSERT_FALSE(res);
  9373. EXPECT_EQ(Error::SSLConnection, res.error());
  9374. // SSL error should be recorded in the Result object (this is the key fix for
  9375. // Issue #2251)
  9376. auto backend_error = res.ssl_backend_error();
  9377. EXPECT_NE(0u, backend_error);
  9378. }
  9379. // Tests cert/key mismatch detection at the TLS context level
  9380. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9381. // Test that using mismatched cert/key causes connection failure.
  9382. // We verify this at the SSLClient level rather than through internal
  9383. // TLS API functions.
  9384. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9385. cli.enable_server_certificate_verification(false);
  9386. cli.set_connection_timeout(2);
  9387. // The mismatch should cause a connection or handshake error
  9388. auto res = cli.Get("/test");
  9389. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9390. // Either way, the request should fail
  9391. EXPECT_FALSE(res);
  9392. }
  9393. #endif
  9394. #if 0
  9395. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9396. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9397. ASSERT_TRUE(cli != nullptr);
  9398. cli->set_address_family(AF_INET6);
  9399. cli->set_interface("en0");
  9400. auto res = cli->Get("/get");
  9401. ASSERT_TRUE(res);
  9402. ASSERT_EQ(StatusCode::OK_200, res->status);
  9403. }
  9404. #endif
  9405. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9406. #ifdef CPPHTTPLIB_SSL_ENABLED
  9407. void ClientCertPresent(
  9408. const std::string &client_cert_file,
  9409. const std::string &client_private_key_file,
  9410. const std::string &client_encrypted_private_key_pass = std::string()) {
  9411. using namespace httplib::tls;
  9412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9413. CLIENT_CA_CERT_DIR);
  9414. ASSERT_TRUE(svr.is_valid());
  9415. svr.Get("/test", [&](const Request &req, Response &res) {
  9416. res.set_content("test", "text/plain");
  9417. auto cert = req.peer_cert();
  9418. ASSERT_TRUE(static_cast<bool>(cert));
  9419. std::string common_name = cert.subject_cn();
  9420. EXPECT_EQ("Common Name", common_name);
  9421. });
  9422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9423. auto se = detail::scope_exit([&] {
  9424. svr.stop();
  9425. t.join();
  9426. ASSERT_FALSE(svr.is_running());
  9427. });
  9428. svr.wait_until_ready();
  9429. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9430. client_encrypted_private_key_pass);
  9431. cli.enable_server_certificate_verification(false);
  9432. cli.set_connection_timeout(30);
  9433. auto res = cli.Get("/test");
  9434. ASSERT_TRUE(res);
  9435. ASSERT_EQ(StatusCode::OK_200, res->status);
  9436. }
  9437. TEST(SSLClientServerTest, ClientCertPresent) {
  9438. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9439. }
  9440. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9441. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9442. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9443. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9444. }
  9445. // PEM memory-based constructor tests (works with all TLS backends)
  9446. void PemMemoryClientCertPresent(
  9447. const std::string &client_cert_file,
  9448. const std::string &client_private_key_file,
  9449. const std::string &client_encrypted_private_key_pass = std::string()) {
  9450. // Read PEM files into memory
  9451. std::string server_cert_pem, server_key_pem;
  9452. std::string client_ca_pem;
  9453. std::string client_cert_pem, client_key_pem;
  9454. read_file(SERVER_CERT_FILE, server_cert_pem);
  9455. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9456. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9457. read_file(client_cert_file, client_cert_pem);
  9458. read_file(client_private_key_file, client_key_pem);
  9459. // Create server with PEM memory
  9460. SSLServer::PemMemory server_pem = {
  9461. server_cert_pem.c_str(),
  9462. server_cert_pem.size(),
  9463. server_key_pem.c_str(),
  9464. server_key_pem.size(),
  9465. client_ca_pem.c_str(),
  9466. client_ca_pem.size(),
  9467. nullptr // no password for server key
  9468. };
  9469. SSLServer svr(server_pem);
  9470. ASSERT_TRUE(svr.is_valid());
  9471. svr.Get("/test", [&](const Request &, Response &res) {
  9472. res.set_content("test", "text/plain");
  9473. });
  9474. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9475. auto se = detail::scope_exit([&] {
  9476. svr.stop();
  9477. t.join();
  9478. ASSERT_FALSE(svr.is_running());
  9479. });
  9480. svr.wait_until_ready();
  9481. // Create client with PEM memory
  9482. const char *password = client_encrypted_private_key_pass.empty()
  9483. ? nullptr
  9484. : client_encrypted_private_key_pass.c_str();
  9485. SSLClient::PemMemory client_pem = {
  9486. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9487. client_key_pem.size(), password};
  9488. SSLClient cli(HOST, PORT, client_pem);
  9489. cli.enable_server_certificate_verification(false);
  9490. cli.set_connection_timeout(30);
  9491. auto res = cli.Get("/test");
  9492. ASSERT_TRUE(res);
  9493. ASSERT_EQ(StatusCode::OK_200, res->status);
  9494. }
  9495. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9496. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9497. }
  9498. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9499. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9500. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9501. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9502. }
  9503. TEST(SSLClientServerTest, ClientCertMissing) {
  9504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9505. CLIENT_CA_CERT_DIR);
  9506. ASSERT_TRUE(svr.is_valid());
  9507. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9508. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. ASSERT_FALSE(svr.is_running());
  9513. });
  9514. svr.wait_until_ready();
  9515. SSLClient cli(HOST, PORT);
  9516. cli.set_connection_timeout(30);
  9517. auto res = cli.Get("/test");
  9518. ASSERT_TRUE(!res);
  9519. // When client cert is missing and server requires it, connection fails
  9520. // Error type depends on backend implementation
  9521. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9522. res.error() == Error::SSLConnection);
  9523. // Verify backend error is captured
  9524. // Note: This test may have different error codes depending on the exact
  9525. // verification failure
  9526. EXPECT_NE(0UL, res.ssl_backend_error());
  9527. }
  9528. TEST(SSLClientServerTest, TrustDirOptional) {
  9529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9530. ASSERT_TRUE(svr.is_valid());
  9531. svr.Get("/test", [&](const Request &, Response &res) {
  9532. res.set_content("test", "text/plain");
  9533. });
  9534. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9542. cli.enable_server_certificate_verification(false);
  9543. cli.set_connection_timeout(30);
  9544. auto res = cli.Get("/test");
  9545. ASSERT_TRUE(res);
  9546. ASSERT_EQ(StatusCode::OK_200, res->status);
  9547. }
  9548. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9549. class NoListenSSLServer : public SSLServer {
  9550. public:
  9551. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9552. const char *client_ca_cert_file_path,
  9553. const char *client_ca_cert_dir_path = nullptr)
  9554. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9555. client_ca_cert_dir_path),
  9556. stop_(false) {}
  9557. std::atomic_bool stop_;
  9558. private:
  9559. bool process_and_close_socket(socket_t /*sock*/) override {
  9560. // Don't create SSL context
  9561. while (!stop_.load()) {
  9562. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9563. }
  9564. return true;
  9565. }
  9566. };
  9567. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9568. CLIENT_CA_CERT_FILE);
  9569. ASSERT_TRUE(svr.is_valid());
  9570. svr.Get("/test", [&](const Request &, Response &res) {
  9571. res.set_content("test", "text/plain");
  9572. });
  9573. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9574. auto se = detail::scope_exit([&] {
  9575. svr.stop_ = true;
  9576. svr.stop();
  9577. t.join();
  9578. ASSERT_FALSE(svr.is_running());
  9579. });
  9580. svr.wait_until_ready();
  9581. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9582. cli.enable_server_certificate_verification(false);
  9583. cli.set_connection_timeout(1);
  9584. auto res = cli.Get("/test");
  9585. ASSERT_TRUE(!res);
  9586. EXPECT_EQ(Error::SSLConnection, res.error());
  9587. // Timeout results in WantRead error code (maps to backend-specific value)
  9588. EXPECT_NE(0, res.ssl_error());
  9589. }
  9590. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9591. // Test SSLServer with client certificate verification using the standard
  9592. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9594. CLIENT_CA_CERT_DIR);
  9595. ASSERT_TRUE(svr.is_valid());
  9596. svr.Get("/test", [&](const Request &req, Response &res) {
  9597. res.set_content("test", "text/plain");
  9598. auto cert = req.peer_cert();
  9599. ASSERT_TRUE(static_cast<bool>(cert));
  9600. auto common_name = cert.subject_cn();
  9601. EXPECT_EQ("Common Name", common_name);
  9602. });
  9603. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9604. auto se = detail::scope_exit([&] {
  9605. svr.stop();
  9606. t.join();
  9607. ASSERT_FALSE(svr.is_running());
  9608. });
  9609. svr.wait_until_ready();
  9610. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9611. cli.enable_server_certificate_verification(false);
  9612. cli.set_connection_timeout(30);
  9613. auto res = cli.Get("/test");
  9614. ASSERT_TRUE(res);
  9615. ASSERT_EQ(StatusCode::OK_200, res->status);
  9616. }
  9617. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9618. // Verifies that wildcard matching and exact matching work consistently
  9619. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9620. using namespace httplib::tls;
  9621. // We need a running server to test against
  9622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9623. ASSERT_TRUE(svr.is_valid());
  9624. svr.Get("/test", [](const Request &, Response &res) {
  9625. res.set_content("ok", "text/plain");
  9626. });
  9627. thread t([&]() { svr.listen(HOST, PORT); });
  9628. auto se = detail::scope_exit([&] {
  9629. svr.stop();
  9630. t.join();
  9631. });
  9632. svr.wait_until_ready();
  9633. bool verify_callback_called = false;
  9634. bool verify_result_wrong = false;
  9635. SSLClient cli(HOST, PORT);
  9636. cli.enable_server_certificate_verification(true);
  9637. cli.set_ca_cert_path(CA_CERT_FILE);
  9638. cli.set_connection_timeout(5);
  9639. // Note: Test certificate has CN="Common Name", not "localhost"
  9640. bool verify_result_cn = false;
  9641. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9642. verify_callback_called = true;
  9643. if (!ctx.cert) return false;
  9644. // Test 1: "Common Name" should match (our test server cert CN)
  9645. verify_result_cn = ctx.check_hostname("Common Name");
  9646. // Test 2: wrong hostname should not match
  9647. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9648. return true; // Accept for the purpose of this test
  9649. });
  9650. auto res = cli.Get("/test");
  9651. // The request may succeed or fail depending on cert configuration
  9652. // but the callback should have been called
  9653. ASSERT_TRUE(verify_callback_called)
  9654. << "Verify callback should have been called";
  9655. // CN="Common Name" should match our test certificate
  9656. //
  9657. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9658. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9659. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9660. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9661. // <openssl/base.h>, which is included transitively when
  9662. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9663. #if defined(OPENSSL_IS_BORINGSSL)
  9664. EXPECT_FALSE(verify_result_cn)
  9665. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9666. #else
  9667. EXPECT_TRUE(verify_result_cn)
  9668. << "verify_hostname should match 'Common Name' (certificate CN)";
  9669. #endif
  9670. // Wrong hostname should not match
  9671. EXPECT_FALSE(verify_result_wrong)
  9672. << "verify_hostname should not match 'wronghost.example.com'";
  9673. }
  9674. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9675. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9676. // X509_check_ip behavior and must hold for every backend.
  9677. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9678. using namespace httplib::tls;
  9679. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9680. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9681. ASSERT_TRUE(svr.is_valid());
  9682. svr.Get("/test", [](const Request &, Response &res) {
  9683. res.set_content("ok", "text/plain");
  9684. });
  9685. thread t([&]() { svr.listen(HOST, PORT); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. });
  9690. svr.wait_until_ready();
  9691. bool verify_callback_called = false;
  9692. bool ip_matched_via_cn = true;
  9693. SSLClient cli(HOST, PORT);
  9694. cli.enable_server_certificate_verification(true);
  9695. cli.set_ca_cert_path(CA_CERT_FILE);
  9696. cli.set_connection_timeout(5);
  9697. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9698. verify_callback_called = true;
  9699. if (!ctx.cert) return false;
  9700. // The IP appears only in the CN, so it must NOT be accepted.
  9701. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9702. return true; // Accept for the purpose of this test
  9703. });
  9704. cli.Get("/test");
  9705. ASSERT_TRUE(verify_callback_called)
  9706. << "Verify callback should have been called";
  9707. EXPECT_FALSE(ip_matched_via_cn)
  9708. << "An IP host must not be authenticated via the certificate CN";
  9709. }
  9710. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9711. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9712. using namespace httplib::tls;
  9713. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9714. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9715. ASSERT_TRUE(svr.is_valid());
  9716. svr.Get("/test", [](const Request &, Response &res) {
  9717. res.set_content("ok", "text/plain");
  9718. });
  9719. thread t([&]() { svr.listen(HOST, PORT); });
  9720. auto se = detail::scope_exit([&] {
  9721. svr.stop();
  9722. t.join();
  9723. });
  9724. svr.wait_until_ready();
  9725. bool verify_callback_called = false;
  9726. bool san_matched = false;
  9727. bool wrong_ipv6_matched = true;
  9728. bool cn_ipv6_matched = true;
  9729. SSLClient cli(HOST, PORT);
  9730. cli.enable_server_certificate_verification(true);
  9731. cli.set_ca_cert_path(CA_CERT_FILE);
  9732. cli.set_connection_timeout(5);
  9733. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9734. verify_callback_called = true;
  9735. if (!ctx.cert) return false;
  9736. // Matches the IPv6 iPAddress SAN.
  9737. san_matched = ctx.check_hostname("2001:db8::1");
  9738. // A different IPv6 address must not match.
  9739. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9740. // "::1" lives only in the CN, so it must not be accepted.
  9741. cn_ipv6_matched = ctx.check_hostname("::1");
  9742. return true; // Accept for the purpose of this test
  9743. });
  9744. cli.Get("/test");
  9745. ASSERT_TRUE(verify_callback_called)
  9746. << "Verify callback should have been called";
  9747. EXPECT_TRUE(san_matched)
  9748. << "verify_hostname should match an IPv6 iPAddress SAN";
  9749. EXPECT_FALSE(wrong_ipv6_matched)
  9750. << "verify_hostname should not match a non-matching IPv6 address";
  9751. EXPECT_FALSE(cn_ipv6_matched)
  9752. << "An IPv6 host must not be authenticated via the certificate CN";
  9753. }
  9754. #endif
  9755. // mbedTLS-specific callback constructor test
  9756. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9757. #ifdef CPPHTTPLIB_SSL_ENABLED
  9758. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9759. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9760. ASSERT_TRUE(svr.is_valid());
  9761. // Set up a handler to verify client certificate is present
  9762. bool client_cert_verified = false;
  9763. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9764. // Verify that client certificate was provided
  9765. client_cert_verified = true;
  9766. res.set_content("success", "text/plain");
  9767. });
  9768. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. });
  9774. svr.wait_until_ready();
  9775. // Client with certificate
  9776. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9777. cli.enable_server_certificate_verification(false);
  9778. cli.set_connection_timeout(30);
  9779. auto res = cli.Get("/test");
  9780. ASSERT_TRUE(res);
  9781. ASSERT_EQ(StatusCode::OK_200, res->status);
  9782. ASSERT_TRUE(client_cert_verified);
  9783. EXPECT_EQ("success", res->body);
  9784. }
  9785. #endif
  9786. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9787. // backends
  9788. #ifdef CPPHTTPLIB_SSL_ENABLED
  9789. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9790. using namespace httplib::tls;
  9791. // Test that when client CA cert file is provided,
  9792. // the server properly requests and validates client certificates
  9793. // Create a server with client authentication
  9794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9795. ASSERT_TRUE(svr.is_valid());
  9796. bool handler_called = false;
  9797. svr.Get("/test", [&](const Request &req, Response &res) {
  9798. handler_called = true;
  9799. // Verify that a client certificate was provided
  9800. auto cert = req.peer_cert();
  9801. ASSERT_TRUE(static_cast<bool>(cert));
  9802. // Get the issuer name
  9803. std::string issuer_str = cert.issuer_name();
  9804. ASSERT_FALSE(issuer_str.empty());
  9805. // The client certificate should be issued by our test CA
  9806. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9807. res.set_content("authenticated", "text/plain");
  9808. });
  9809. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9810. auto se = detail::scope_exit([&] {
  9811. svr.stop();
  9812. t.join();
  9813. ASSERT_FALSE(svr.is_running());
  9814. });
  9815. svr.wait_until_ready();
  9816. // Connect with a client certificate issued by the CA
  9817. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9818. cli.enable_server_certificate_verification(false);
  9819. cli.set_connection_timeout(30);
  9820. auto res = cli.Get("/test");
  9821. ASSERT_TRUE(res);
  9822. ASSERT_EQ(StatusCode::OK_200, res->status);
  9823. ASSERT_TRUE(handler_called);
  9824. EXPECT_EQ("authenticated", res->body);
  9825. }
  9826. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9827. using namespace httplib::tls;
  9828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9829. ASSERT_TRUE(svr.is_valid());
  9830. svr.Get("/test", [](const Request &, Response &res) {
  9831. res.set_content("ok", "text/plain");
  9832. });
  9833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9834. auto se = detail::scope_exit([&] {
  9835. svr.stop();
  9836. t.join();
  9837. });
  9838. svr.wait_until_ready();
  9839. SSLClient cli(HOST, PORT);
  9840. cli.enable_server_certificate_verification(false);
  9841. cli.set_connection_timeout(30);
  9842. bool cert_checked = false;
  9843. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9844. if (ctx.cert) {
  9845. auto sans = ctx.sans();
  9846. // Test certificate may or may not have SANs - just verify the API
  9847. // works If SANs exist, verify the types are valid
  9848. for (const auto &san : sans) {
  9849. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9850. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9851. san.type == SanType::OTHER);
  9852. EXPECT_FALSE(san.value.empty());
  9853. }
  9854. cert_checked = true;
  9855. }
  9856. return true;
  9857. });
  9858. auto res = cli.Get("/test");
  9859. ASSERT_TRUE(res);
  9860. EXPECT_TRUE(cert_checked);
  9861. }
  9862. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9863. using namespace httplib::tls;
  9864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9865. ASSERT_TRUE(svr.is_valid());
  9866. svr.Get("/test", [](const Request &, Response &res) {
  9867. res.set_content("ok", "text/plain");
  9868. });
  9869. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9870. auto se = detail::scope_exit([&] {
  9871. svr.stop();
  9872. t.join();
  9873. });
  9874. svr.wait_until_ready();
  9875. SSLClient cli(HOST, PORT);
  9876. cli.enable_server_certificate_verification(false);
  9877. cli.set_connection_timeout(30);
  9878. bool validity_checked = false;
  9879. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9880. if (ctx.cert) {
  9881. time_t not_before = 0, not_after = 0;
  9882. bool result = ctx.validity(not_before, not_after);
  9883. EXPECT_TRUE(result);
  9884. // Verify that not_before < now < not_after for a valid cert
  9885. time_t now = time(nullptr);
  9886. EXPECT_LT(not_before, now);
  9887. EXPECT_GT(not_after, now);
  9888. validity_checked = true;
  9889. }
  9890. return true;
  9891. });
  9892. auto res = cli.Get("/test");
  9893. ASSERT_TRUE(res);
  9894. EXPECT_TRUE(validity_checked);
  9895. }
  9896. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9897. using namespace httplib::tls;
  9898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9899. ASSERT_TRUE(svr.is_valid());
  9900. svr.Get("/test", [](const Request &, Response &res) {
  9901. res.set_content("ok", "text/plain");
  9902. });
  9903. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9904. auto se = detail::scope_exit([&] {
  9905. svr.stop();
  9906. t.join();
  9907. });
  9908. svr.wait_until_ready();
  9909. SSLClient cli(HOST, PORT);
  9910. cli.enable_server_certificate_verification(false);
  9911. cli.set_connection_timeout(30);
  9912. bool serial_checked = false;
  9913. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9914. if (ctx.cert) {
  9915. std::string serial = ctx.serial();
  9916. EXPECT_FALSE(serial.empty());
  9917. // Serial should be a hex string
  9918. for (char c : serial) {
  9919. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9920. (c >= 'a' && c <= 'f'));
  9921. }
  9922. serial_checked = true;
  9923. }
  9924. return true;
  9925. });
  9926. auto res = cli.Get("/test");
  9927. ASSERT_TRUE(res);
  9928. EXPECT_TRUE(serial_checked);
  9929. }
  9930. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9931. // Test 1: Valid CA file - no error should be recorded
  9932. {
  9933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9934. CLIENT_CA_CERT_FILE);
  9935. ASSERT_TRUE(svr.is_valid());
  9936. // With valid setup, last_ssl_error should be 0
  9937. EXPECT_EQ(0, svr.ssl_last_error());
  9938. }
  9939. // Test 2: Invalid CA file content
  9940. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9941. {
  9942. // Create a temporary file with completely invalid content
  9943. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9944. {
  9945. std::ofstream ofs(temp_invalid_ca);
  9946. ofs << "This is not a certificate file at all\n";
  9947. ofs << "Just plain text content\n";
  9948. }
  9949. // Create server with invalid CA file
  9950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9951. // Clean up temporary file
  9952. std::remove(temp_invalid_ca);
  9953. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9954. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9955. // Note: SSL_CTX_load_verify_locations typically fails first,
  9956. // but our error handling code path is still exercised
  9957. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9958. }
  9959. }
  9960. TEST(VerifyCallbackTest, VerifyContextFields) {
  9961. using namespace httplib::tls;
  9962. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9963. ASSERT_TRUE(svr.is_valid());
  9964. svr.Get("/test", [](const Request &, Response &res) {
  9965. res.set_content("ok", "text/plain");
  9966. });
  9967. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. t.join();
  9971. });
  9972. svr.wait_until_ready();
  9973. SSLClient cli(HOST, PORT);
  9974. cli.enable_server_certificate_verification(false);
  9975. cli.set_connection_timeout(30);
  9976. int callback_count = 0;
  9977. bool saw_leaf_cert = false;
  9978. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9979. if (ctx.cert) {
  9980. callback_count++;
  9981. // We should see at least one certificate (the leaf)
  9982. std::string cn = ctx.subject_cn();
  9983. if (!cn.empty()) { saw_leaf_cert = true; }
  9984. // Verify context fields are populated
  9985. EXPECT_NE(ctx.session, nullptr);
  9986. EXPECT_GE(ctx.depth, 0);
  9987. }
  9988. return true;
  9989. });
  9990. auto res = cli.Get("/test");
  9991. ASSERT_TRUE(res);
  9992. EXPECT_GT(callback_count, 0);
  9993. EXPECT_TRUE(saw_leaf_cert);
  9994. }
  9995. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9996. using httplib::tls::TlsError;
  9997. // Test that verify_error_to_string returns empty for success
  9998. std::string success_str = TlsError::verify_error_to_string(0);
  9999. EXPECT_TRUE(success_str.empty());
  10000. // Test that verify_error_to_string returns non-empty for error codes
  10001. // Using a common error code (certificate expired)
  10002. std::string error_str =
  10003. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10004. EXPECT_FALSE(error_str.empty());
  10005. }
  10006. TEST(SessionVerifierTest, CertificateAccepted) {
  10007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10008. ASSERT_TRUE(svr.is_valid());
  10009. svr.Get("/test", [](const Request &, Response &res) {
  10010. res.set_content("ok", "text/plain");
  10011. });
  10012. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10013. auto se = detail::scope_exit([&] {
  10014. svr.stop();
  10015. t.join();
  10016. });
  10017. svr.wait_until_ready();
  10018. SSLClient cli(HOST, PORT);
  10019. cli.enable_server_certificate_verification(false);
  10020. cli.set_connection_timeout(30);
  10021. bool callback_called = false;
  10022. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10023. EXPECT_NE(session, nullptr);
  10024. callback_called = true;
  10025. return SSLVerifierResponse::CertificateAccepted;
  10026. });
  10027. auto res = cli.Get("/test");
  10028. ASSERT_TRUE(res);
  10029. EXPECT_EQ(200, res->status);
  10030. EXPECT_TRUE(callback_called);
  10031. }
  10032. TEST(SessionVerifierTest, CertificateRejected) {
  10033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10034. ASSERT_TRUE(svr.is_valid());
  10035. svr.Get("/test", [](const Request &, Response &res) {
  10036. res.set_content("ok", "text/plain");
  10037. });
  10038. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10039. auto se = detail::scope_exit([&] {
  10040. svr.stop();
  10041. t.join();
  10042. });
  10043. svr.wait_until_ready();
  10044. SSLClient cli(HOST, PORT);
  10045. cli.enable_server_certificate_verification(false);
  10046. cli.set_connection_timeout(30);
  10047. bool callback_called = false;
  10048. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10049. EXPECT_NE(session, nullptr);
  10050. callback_called = true;
  10051. return SSLVerifierResponse::CertificateRejected;
  10052. });
  10053. auto res = cli.Get("/test");
  10054. EXPECT_FALSE(res);
  10055. EXPECT_TRUE(callback_called);
  10056. }
  10057. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10059. ASSERT_TRUE(svr.is_valid());
  10060. svr.Get("/test", [](const Request &, Response &res) {
  10061. res.set_content("ok", "text/plain");
  10062. });
  10063. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10064. auto se = detail::scope_exit([&] {
  10065. svr.stop();
  10066. t.join();
  10067. });
  10068. svr.wait_until_ready();
  10069. // NoDecisionMade with verification disabled should succeed (no default check)
  10070. SSLClient cli(HOST, PORT);
  10071. cli.enable_server_certificate_verification(false);
  10072. cli.set_connection_timeout(30);
  10073. bool callback_called = false;
  10074. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10075. EXPECT_NE(session, nullptr);
  10076. callback_called = true;
  10077. return SSLVerifierResponse::NoDecisionMade;
  10078. });
  10079. auto res = cli.Get("/test");
  10080. ASSERT_TRUE(res);
  10081. EXPECT_EQ(200, res->status);
  10082. EXPECT_TRUE(callback_called);
  10083. }
  10084. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10086. ASSERT_TRUE(svr.is_valid());
  10087. svr.Get("/test", [](const Request &, Response &res) {
  10088. res.set_content("ok", "text/plain");
  10089. });
  10090. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10091. auto se = detail::scope_exit([&] {
  10092. svr.stop();
  10093. t.join();
  10094. });
  10095. svr.wait_until_ready();
  10096. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10097. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10098. // so we only check that the request fails, not whether the callback was
  10099. // called.
  10100. SSLClient cli(HOST, PORT);
  10101. cli.enable_server_certificate_verification(true);
  10102. cli.set_connection_timeout(30);
  10103. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10104. EXPECT_NE(session, nullptr);
  10105. return SSLVerifierResponse::NoDecisionMade;
  10106. });
  10107. auto res = cli.Get("/test");
  10108. EXPECT_FALSE(res);
  10109. }
  10110. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10111. // Test SSL server using PemMemory constructor with client CA certificates
  10112. // Read PEM files
  10113. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10114. read_file(SERVER_CERT_FILE, server_cert_pem);
  10115. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10116. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10117. // Create SSLServer with PemMemory constructor including client CA
  10118. SSLServer::PemMemory server_pem = {
  10119. server_cert_pem.c_str(),
  10120. server_cert_pem.size(),
  10121. server_key_pem.c_str(),
  10122. server_key_pem.size(),
  10123. client_ca_pem.c_str(),
  10124. client_ca_pem.size(),
  10125. nullptr // no password for server key
  10126. };
  10127. SSLServer svr(server_pem);
  10128. ASSERT_TRUE(svr.is_valid());
  10129. // No SSL error should be recorded for valid setup
  10130. EXPECT_EQ(0, svr.ssl_last_error());
  10131. // Set up server endpoints
  10132. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10133. res.set_content("ok", "text/plain");
  10134. });
  10135. // Start server in a thread
  10136. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10137. svr.wait_until_ready();
  10138. // Connect with client certificate (using constructor with paths)
  10139. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10140. cli.enable_server_certificate_verification(false);
  10141. auto res = cli.Get("/test-pem-ca");
  10142. ASSERT_TRUE(res);
  10143. EXPECT_EQ(200, res->status);
  10144. EXPECT_EQ("ok", res->body);
  10145. svr.stop();
  10146. server_thread.join();
  10147. }
  10148. #endif
  10149. #ifdef _WIN32
  10150. TEST(CleanupTest, WSACleanup) {
  10151. int ret = WSACleanup();
  10152. ASSERT_EQ(0, ret);
  10153. }
  10154. #endif
  10155. #ifndef CPPHTTPLIB_SSL_ENABLED
  10156. TEST(NoSSLSupport, SimpleInterface) {
  10157. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10158. }
  10159. #endif
  10160. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10161. TEST(InvalidScheme, SimpleInterface) {
  10162. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10163. }
  10164. #endif
  10165. TEST(NoScheme, SimpleInterface) {
  10166. Client cli("yahoo.com:80");
  10167. ASSERT_TRUE(cli.is_valid());
  10168. }
  10169. TEST(SendAPI, SimpleInterface_Online) {
  10170. Client cli("http://yahoo.com");
  10171. Request req;
  10172. req.method = "GET";
  10173. req.path = "/";
  10174. auto res = cli.send(req);
  10175. ASSERT_TRUE(res);
  10176. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10177. }
  10178. TEST(SendAPI, WithParamsInRequest) {
  10179. Server svr;
  10180. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10181. EXPECT_TRUE(req.has_param("test"));
  10182. EXPECT_EQ("test_value", req.get_param_value("test"));
  10183. });
  10184. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10185. auto se = detail::scope_exit([&] {
  10186. svr.stop();
  10187. t.join();
  10188. ASSERT_FALSE(svr.is_running());
  10189. });
  10190. svr.wait_until_ready();
  10191. Client cli(HOST, PORT);
  10192. {
  10193. Request req;
  10194. req.method = "GET";
  10195. req.path = "/";
  10196. req.params.emplace("test", "test_value");
  10197. auto res = cli.send(req);
  10198. ASSERT_TRUE(res);
  10199. }
  10200. {
  10201. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10202. ASSERT_TRUE(res);
  10203. }
  10204. }
  10205. TEST(ClientImplMethods, GetSocketTest) {
  10206. httplib::Server svr;
  10207. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10208. res.status = StatusCode::OK_200;
  10209. });
  10210. auto port = svr.bind_to_any_port("127.0.0.1");
  10211. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10212. auto se = detail::scope_exit([&] {
  10213. svr.stop();
  10214. thread.join();
  10215. ASSERT_FALSE(svr.is_running());
  10216. });
  10217. svr.wait_until_ready();
  10218. {
  10219. httplib::Client cli("127.0.0.1", port);
  10220. cli.set_keep_alive(true);
  10221. // Use the behavior of cpp-httplib of opening the connection
  10222. // only when the first request happens. If that changes,
  10223. // this test would be obsolete.
  10224. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10225. // This also implicitly tests the server. But other tests would fail much
  10226. // earlier than this one to be considered.
  10227. auto res = cli.Get("/");
  10228. ASSERT_TRUE(res);
  10229. EXPECT_EQ(StatusCode::OK_200, res->status);
  10230. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10231. }
  10232. }
  10233. #ifdef CPPHTTPLIB_SSL_ENABLED
  10234. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10235. Client cli("http://yahoo.com");
  10236. auto res = cli.Get("/");
  10237. ASSERT_TRUE(res);
  10238. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10239. cli.set_follow_location(true);
  10240. res = cli.Get("/");
  10241. ASSERT_TRUE(res);
  10242. EXPECT_EQ(StatusCode::OK_200, res->status);
  10243. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10244. }
  10245. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10246. Client cli("https://yahoo.com");
  10247. auto res = cli.Get("/");
  10248. ASSERT_TRUE(res);
  10249. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10250. cli.set_follow_location(true);
  10251. res = cli.Get("/");
  10252. ASSERT_TRUE(res);
  10253. EXPECT_EQ(StatusCode::OK_200, res->status);
  10254. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10255. }
  10256. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10257. Client cli("https://yahoo.com");
  10258. auto res = cli.Get("/");
  10259. ASSERT_TRUE(res);
  10260. ASSERT_FALSE(!res);
  10261. ASSERT_TRUE(res);
  10262. ASSERT_FALSE(res == nullptr);
  10263. ASSERT_TRUE(res != nullptr);
  10264. EXPECT_EQ(Error::Success, res.error());
  10265. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10266. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10267. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10268. cli.set_follow_location(true);
  10269. res = cli.Get("/");
  10270. ASSERT_TRUE(res);
  10271. EXPECT_EQ(Error::Success, res.error());
  10272. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10273. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10274. EXPECT_EQ(StatusCode::OK_200, res->status);
  10275. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10276. }
  10277. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10278. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10279. Client cli("https://cdnjs.cloudflare.com");
  10280. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10281. Headers{{"Accept-Encoding", "br"}});
  10282. ASSERT_TRUE(res);
  10283. EXPECT_EQ(StatusCode::OK_200, res->status);
  10284. EXPECT_EQ(287630U, res->body.size());
  10285. EXPECT_EQ("application/javascript; charset=utf-8",
  10286. res->get_header_value("Content-Type"));
  10287. }
  10288. #endif
  10289. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10290. #undef REDIR_HOST // Silence compiler warning
  10291. #define REDIR_HOST "https://httpbingo.org"
  10292. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10293. Client cli(REDIR_HOST);
  10294. cli.set_follow_location(true);
  10295. auto res =
  10296. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10297. ASSERT_TRUE(res);
  10298. EXPECT_EQ(StatusCode::OK_200, res->status);
  10299. }
  10300. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10301. Client cli(REDIR_HOST);
  10302. cli.set_follow_location(true);
  10303. Params params;
  10304. params.emplace("url", "http://example.com");
  10305. params.emplace("status_code", "302");
  10306. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10307. ASSERT_TRUE(res);
  10308. EXPECT_EQ(StatusCode::OK_200, res->status);
  10309. }
  10310. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10311. Client cli(REDIR_HOST);
  10312. cli.set_follow_location(true);
  10313. Params params;
  10314. params.emplace("url", "http://example.com");
  10315. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10316. ASSERT_TRUE(res);
  10317. EXPECT_EQ(StatusCode::OK_200, res->status);
  10318. }
  10319. TEST(HttpToHttpsRedirectTest, CertFile) {
  10320. auto ssl_port = PORT + 1;
  10321. Server svr;
  10322. ASSERT_TRUE(svr.is_valid());
  10323. svr.Get("/index", [&](const Request &, Response &res) {
  10324. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10325. "/index");
  10326. svr.stop();
  10327. });
  10328. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10329. ASSERT_TRUE(ssl_svr.is_valid());
  10330. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10331. res.set_content("test", "text/plain");
  10332. ssl_svr.stop();
  10333. });
  10334. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10335. thread t2 =
  10336. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10337. auto se = detail::scope_exit([&] {
  10338. t2.join();
  10339. t.join();
  10340. ASSERT_FALSE(svr.is_running());
  10341. });
  10342. svr.wait_until_ready();
  10343. ssl_svr.wait_until_ready();
  10344. Client cli("127.0.0.1", PORT);
  10345. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10346. cli.enable_server_certificate_verification(true);
  10347. cli.set_follow_location(true);
  10348. cli.set_connection_timeout(30);
  10349. auto res = cli.Get("/index");
  10350. ASSERT_TRUE(res);
  10351. ASSERT_EQ(StatusCode::OK_200, res->status);
  10352. }
  10353. TEST(SSLClientRedirectTest, CertFile) {
  10354. auto ssl_port = PORT + 1;
  10355. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10356. ASSERT_TRUE(ssl_svr1.is_valid());
  10357. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10358. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10359. "/index");
  10360. ssl_svr1.stop();
  10361. });
  10362. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10363. ASSERT_TRUE(ssl_svr2.is_valid());
  10364. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10365. res.set_content("test", "text/plain");
  10366. ssl_svr2.stop();
  10367. });
  10368. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10369. thread t2 =
  10370. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10371. auto se = detail::scope_exit([&] {
  10372. t2.join();
  10373. t.join();
  10374. ASSERT_FALSE(ssl_svr1.is_running());
  10375. });
  10376. ssl_svr1.wait_until_ready();
  10377. ssl_svr2.wait_until_ready();
  10378. SSLClient cli("127.0.0.1", PORT);
  10379. std::string cert;
  10380. read_file(SERVER_CERT2_FILE, cert);
  10381. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10382. cli.enable_server_certificate_verification(true);
  10383. cli.set_follow_location(true);
  10384. cli.set_connection_timeout(30);
  10385. auto res = cli.Get("/index");
  10386. ASSERT_TRUE(res);
  10387. ASSERT_EQ(StatusCode::OK_200, res->status);
  10388. }
  10389. #endif
  10390. #ifdef CPPHTTPLIB_SSL_ENABLED
  10391. // Test that set_ca_cert_store() skips system certs (consistent with
  10392. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10393. // should be trusted - system certs should NOT be loaded.
  10394. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10395. // Load a specific cert that is NOT a system CA cert
  10396. std::string cert;
  10397. read_file(SERVER_CERT2_FILE, cert);
  10398. SSLClient cli("google.com");
  10399. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10400. cli.enable_server_certificate_verification(true);
  10401. // This should FAIL because:
  10402. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10403. // 2. System certs should NOT be loaded when custom store is set
  10404. // If system certs WERE loaded, this would succeed
  10405. auto res = cli.Get("/");
  10406. ASSERT_FALSE(res);
  10407. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10408. }
  10409. // Same as above, but through the native store handle path. Regression test:
  10410. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10411. // merged system certs into the user-provided store.
  10412. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10413. std::string cert;
  10414. read_file(SERVER_CERT2_FILE, cert);
  10415. SSLClient cli("google.com");
  10416. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10417. cli.enable_server_certificate_verification(true);
  10418. auto res = cli.Get("/");
  10419. ASSERT_FALSE(res);
  10420. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10421. }
  10422. // A custom store set via the native handle must still verify a server whose
  10423. // cert it does contain.
  10424. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10425. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10426. ASSERT_TRUE(svr.is_valid());
  10427. svr.Get("/test", [&](const Request &, Response &res) {
  10428. res.set_content("test", "text/plain");
  10429. });
  10430. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10431. auto se = detail::scope_exit([&] {
  10432. svr.stop();
  10433. t.join();
  10434. ASSERT_FALSE(svr.is_running());
  10435. });
  10436. svr.wait_until_ready();
  10437. SSLClient cli("127.0.0.1", PORT);
  10438. std::string cert;
  10439. read_file(SERVER_CERT2_FILE, cert);
  10440. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10441. cli.enable_server_certificate_verification(true);
  10442. cli.set_connection_timeout(30);
  10443. auto res = cli.Get("/test");
  10444. ASSERT_TRUE(res);
  10445. ASSERT_EQ(StatusCode::OK_200, res->status);
  10446. }
  10447. // CA certs loaded through the universal Client must be transferred to the
  10448. // client created internally for following an HTTPS redirect. Regression test:
  10449. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10450. // the CA data for redirect transfer.
  10451. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10452. auto ssl_port = PORT + 1;
  10453. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10454. ASSERT_TRUE(ssl_svr1.is_valid());
  10455. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10456. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10457. "/index");
  10458. });
  10459. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10460. ASSERT_TRUE(ssl_svr2.is_valid());
  10461. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10462. res.set_content("test", "text/plain");
  10463. });
  10464. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10465. thread t2 =
  10466. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10467. auto se = detail::scope_exit([&] {
  10468. ssl_svr2.stop();
  10469. ssl_svr1.stop();
  10470. t2.join();
  10471. t.join();
  10472. ASSERT_FALSE(ssl_svr1.is_running());
  10473. });
  10474. ssl_svr1.wait_until_ready();
  10475. ssl_svr2.wait_until_ready();
  10476. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10477. std::string cert;
  10478. read_file(SERVER_CERT2_FILE, cert);
  10479. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10480. cli.enable_server_certificate_verification(true);
  10481. cli.set_follow_location(true);
  10482. cli.set_connection_timeout(30);
  10483. auto res = cli.Get("/index");
  10484. ASSERT_TRUE(res);
  10485. ASSERT_EQ(StatusCode::OK_200, res->status);
  10486. }
  10487. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10488. // so a host signed by a system CA verifies even though a custom CA is set
  10489. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10490. std::string cert;
  10491. read_file(SERVER_CERT2_FILE, cert);
  10492. SSLClient cli("google.com");
  10493. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10494. cli.enable_system_ca(true);
  10495. cli.enable_server_certificate_verification(true);
  10496. auto res = cli.Get("/");
  10497. ASSERT_TRUE(res);
  10498. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10499. }
  10500. // The custom CA remains effective when combined with the system CA
  10501. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10502. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10503. ASSERT_TRUE(svr.is_valid());
  10504. svr.Get("/test", [&](const Request &, Response &res) {
  10505. res.set_content("test", "text/plain");
  10506. });
  10507. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10508. auto se = detail::scope_exit([&] {
  10509. svr.stop();
  10510. t.join();
  10511. ASSERT_FALSE(svr.is_running());
  10512. });
  10513. svr.wait_until_ready();
  10514. SSLClient cli("127.0.0.1", PORT);
  10515. std::string cert;
  10516. read_file(SERVER_CERT2_FILE, cert);
  10517. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10518. cli.enable_system_ca(true);
  10519. cli.enable_server_certificate_verification(true);
  10520. cli.set_connection_timeout(30);
  10521. auto res = cli.Get("/test");
  10522. ASSERT_TRUE(res);
  10523. ASSERT_EQ(StatusCode::OK_200, res->status);
  10524. }
  10525. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10526. // skip chain verification entirely (only the certificate identity was
  10527. // checked), so a server presenting an untrusted certificate with a matching
  10528. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10529. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10530. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10531. ASSERT_TRUE(svr.is_valid());
  10532. svr.Get("/test", [&](const Request &, Response &res) {
  10533. res.set_content("test", "text/plain");
  10534. });
  10535. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10536. auto se = detail::scope_exit([&] {
  10537. svr.stop();
  10538. t.join();
  10539. ASSERT_FALSE(svr.is_running());
  10540. });
  10541. svr.wait_until_ready();
  10542. SSLClient cli("127.0.0.1", PORT);
  10543. std::string cert;
  10544. // A trusted CA that did not sign the server certificate. The server cert
  10545. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10546. // this connection.
  10547. read_file(CLIENT_CA_CERT_FILE, cert);
  10548. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10549. cli.enable_server_certificate_verification(true);
  10550. cli.set_connection_timeout(30);
  10551. auto res = cli.Get("/test");
  10552. ASSERT_FALSE(res);
  10553. }
  10554. // enable_system_ca(false) prevents system CA loading entirely
  10555. TEST(SSLClientTest, DisableSystemCa_Online) {
  10556. SSLClient cli("google.com");
  10557. cli.enable_system_ca(false);
  10558. cli.enable_server_certificate_verification(true);
  10559. auto res = cli.Get("/");
  10560. ASSERT_FALSE(res);
  10561. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10562. // itself when the CA chain is empty
  10563. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10564. res.error() == Error::SSLConnection);
  10565. }
  10566. // The universal Client forwards enable_system_ca()
  10567. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10568. std::string cert;
  10569. read_file(SERVER_CERT2_FILE, cert);
  10570. Client cli("https://google.com");
  10571. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10572. cli.enable_system_ca(true);
  10573. cli.enable_server_certificate_verification(true);
  10574. auto res = cli.Get("/");
  10575. ASSERT_TRUE(res);
  10576. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10577. }
  10578. // The system CA policy must carry over to the client created internally for
  10579. // following a cross-host HTTPS redirect
  10580. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10581. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10582. ASSERT_TRUE(svr.is_valid());
  10583. svr.Get("/index", [&](const Request &, Response &res) {
  10584. res.set_redirect("https://www.google.com/");
  10585. });
  10586. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10587. auto se = detail::scope_exit([&] {
  10588. svr.stop();
  10589. t.join();
  10590. ASSERT_FALSE(svr.is_running());
  10591. });
  10592. svr.wait_until_ready();
  10593. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10594. std::string cert;
  10595. read_file(SERVER_CERT2_FILE, cert);
  10596. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10597. cli.enable_system_ca(true);
  10598. cli.enable_server_certificate_verification(true);
  10599. cli.set_follow_location(true);
  10600. cli.set_connection_timeout(30);
  10601. // Receiving any response proves the redirect client completed the TLS
  10602. // handshake with a system-CA-signed host
  10603. auto res = cli.Get("/index");
  10604. ASSERT_TRUE(res);
  10605. }
  10606. TEST(MultipartFormDataTest, LargeData) {
  10607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10608. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10609. const ContentReader &content_reader) {
  10610. if (req.is_multipart_form_data()) {
  10611. std::vector<FormData> items;
  10612. content_reader(
  10613. [&](const FormData &file) {
  10614. items.push_back(file);
  10615. return true;
  10616. },
  10617. [&](const char *data, size_t data_length) {
  10618. items.back().content.append(data, data_length);
  10619. return true;
  10620. });
  10621. EXPECT_TRUE(std::string(items[0].name) == "document");
  10622. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10623. EXPECT_TRUE(items[0].filename == "2MB_data");
  10624. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10625. EXPECT_TRUE(items[1].name == "hello");
  10626. EXPECT_TRUE(items[1].content == "world");
  10627. EXPECT_TRUE(items[1].filename == "");
  10628. EXPECT_TRUE(items[1].content_type == "");
  10629. } else {
  10630. std::string body;
  10631. content_reader([&](const char *data, size_t data_length) {
  10632. body.append(data, data_length);
  10633. return true;
  10634. });
  10635. }
  10636. });
  10637. auto port = svr.bind_to_any_port(HOST);
  10638. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10639. auto se = detail::scope_exit([&] {
  10640. svr.stop();
  10641. t.join();
  10642. ASSERT_FALSE(svr.is_running());
  10643. });
  10644. svr.wait_until_ready();
  10645. {
  10646. std::string data(1024 * 1024 * 2, '.');
  10647. std::stringstream buffer;
  10648. buffer << data;
  10649. SSLClient cli(HOST, port);
  10650. cli.enable_server_certificate_verification(false);
  10651. UploadFormDataItems items{
  10652. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10653. {"hello", "world", "", ""},
  10654. };
  10655. auto res = cli.Post("/post", items);
  10656. ASSERT_TRUE(res);
  10657. ASSERT_EQ(StatusCode::OK_200, res->status);
  10658. }
  10659. }
  10660. TEST(MultipartFormDataTest, DataProviderItems) {
  10661. std::random_device seed_gen;
  10662. std::mt19937 random(seed_gen());
  10663. std::string rand1;
  10664. rand1.resize(1000);
  10665. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10666. std::string rand2;
  10667. rand2.resize(3000);
  10668. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10670. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10671. const ContentReader &content_reader) {
  10672. ASSERT_FALSE(req.is_multipart_form_data());
  10673. std::string body;
  10674. content_reader([&](const char *data, size_t data_length) {
  10675. body.append(data, data_length);
  10676. return true;
  10677. });
  10678. EXPECT_EQ(body, "");
  10679. });
  10680. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10681. const ContentReader &content_reader) {
  10682. ASSERT_TRUE(req.is_multipart_form_data());
  10683. std::vector<FormData> items;
  10684. content_reader(
  10685. [&](const FormData &file) {
  10686. items.push_back(file);
  10687. return true;
  10688. },
  10689. [&](const char *data, size_t data_length) {
  10690. items.back().content.append(data, data_length);
  10691. return true;
  10692. });
  10693. ASSERT_TRUE(items.size() == 2);
  10694. EXPECT_EQ(std::string(items[0].name), "name1");
  10695. EXPECT_EQ(items[0].content, "Testing123");
  10696. EXPECT_EQ(items[0].filename, "filename1");
  10697. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10698. EXPECT_EQ(items[1].name, "name2");
  10699. EXPECT_EQ(items[1].content, "Testing456");
  10700. EXPECT_EQ(items[1].filename, "");
  10701. EXPECT_EQ(items[1].content_type, "");
  10702. });
  10703. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10704. const ContentReader &content_reader) {
  10705. ASSERT_TRUE(req.is_multipart_form_data());
  10706. std::vector<FormData> items;
  10707. content_reader(
  10708. [&](const FormData &file) {
  10709. items.push_back(file);
  10710. return true;
  10711. },
  10712. [&](const char *data, size_t data_length) {
  10713. items.back().content.append(data, data_length);
  10714. return true;
  10715. });
  10716. ASSERT_TRUE(items.size() == 2);
  10717. EXPECT_EQ(items[0].name, "name3");
  10718. EXPECT_EQ(items[0].content, rand1);
  10719. EXPECT_EQ(items[0].filename, "filename3");
  10720. EXPECT_EQ(items[0].content_type, "");
  10721. EXPECT_EQ(items[1].name, "name4");
  10722. EXPECT_EQ(items[1].content, rand2);
  10723. EXPECT_EQ(items[1].filename, "filename4");
  10724. EXPECT_EQ(items[1].content_type, "");
  10725. });
  10726. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10727. const ContentReader &content_reader) {
  10728. ASSERT_TRUE(req.is_multipart_form_data());
  10729. std::vector<FormData> items;
  10730. content_reader(
  10731. [&](const FormData &file) {
  10732. items.push_back(file);
  10733. return true;
  10734. },
  10735. [&](const char *data, size_t data_length) {
  10736. items.back().content.append(data, data_length);
  10737. return true;
  10738. });
  10739. ASSERT_TRUE(items.size() == 4);
  10740. EXPECT_EQ(std::string(items[0].name), "name1");
  10741. EXPECT_EQ(items[0].content, "Testing123");
  10742. EXPECT_EQ(items[0].filename, "filename1");
  10743. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10744. EXPECT_EQ(items[1].name, "name2");
  10745. EXPECT_EQ(items[1].content, "Testing456");
  10746. EXPECT_EQ(items[1].filename, "");
  10747. EXPECT_EQ(items[1].content_type, "");
  10748. EXPECT_EQ(items[2].name, "name3");
  10749. EXPECT_EQ(items[2].content, rand1);
  10750. EXPECT_EQ(items[2].filename, "filename3");
  10751. EXPECT_EQ(items[2].content_type, "");
  10752. EXPECT_EQ(items[3].name, "name4");
  10753. EXPECT_EQ(items[3].content, rand2);
  10754. EXPECT_EQ(items[3].filename, "filename4");
  10755. EXPECT_EQ(items[3].content_type, "");
  10756. });
  10757. auto port = svr.bind_to_any_port("localhost");
  10758. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10759. auto se = detail::scope_exit([&] {
  10760. svr.stop();
  10761. t.join();
  10762. ASSERT_FALSE(svr.is_running());
  10763. });
  10764. svr.wait_until_ready();
  10765. {
  10766. SSLClient cli("localhost", port);
  10767. cli.enable_server_certificate_verification(false);
  10768. UploadFormDataItems items{
  10769. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10770. {"name2", "Testing456", "", ""}, // not a file
  10771. };
  10772. {
  10773. auto res = cli.Post("/post-none", {}, {}, {});
  10774. ASSERT_TRUE(res);
  10775. ASSERT_EQ(StatusCode::OK_200, res->status);
  10776. }
  10777. FormDataProviderItems providers;
  10778. {
  10779. auto res =
  10780. cli.Post("/post-items", {}, items, providers); // empty providers
  10781. ASSERT_TRUE(res);
  10782. ASSERT_EQ(StatusCode::OK_200, res->status);
  10783. }
  10784. providers.push_back({"name3",
  10785. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10786. // test the offset is given correctly at each step
  10787. if (!offset)
  10788. sink.os.write(rand1.data(), 30);
  10789. else if (offset == 30)
  10790. sink.os.write(rand1.data() + 30, 300);
  10791. else if (offset == 330)
  10792. sink.os.write(rand1.data() + 330, 670);
  10793. else if (offset == rand1.size())
  10794. sink.done();
  10795. return true;
  10796. },
  10797. "filename3",
  10798. {}});
  10799. providers.push_back({"name4",
  10800. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10801. // test the offset is given correctly at each step
  10802. if (!offset)
  10803. sink.os.write(rand2.data(), 2000);
  10804. else if (offset == 2000)
  10805. sink.os.write(rand2.data() + 2000, 1);
  10806. else if (offset == 2001)
  10807. sink.os.write(rand2.data() + 2001, 999);
  10808. else if (offset == rand2.size())
  10809. sink.done();
  10810. return true;
  10811. },
  10812. "filename4",
  10813. {}});
  10814. {
  10815. auto res = cli.Post("/post-providers", {}, {}, providers);
  10816. ASSERT_TRUE(res);
  10817. ASSERT_EQ(StatusCode::OK_200, res->status);
  10818. }
  10819. {
  10820. auto res = cli.Post("/post-both", {}, items, providers);
  10821. ASSERT_TRUE(res);
  10822. ASSERT_EQ(StatusCode::OK_200, res->status);
  10823. }
  10824. }
  10825. }
  10826. TEST(MultipartFormDataTest, BadHeader) {
  10827. Server svr;
  10828. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10829. res.set_content("ok", "text/plain");
  10830. });
  10831. thread t = thread([&] { svr.listen(HOST, PORT); });
  10832. auto se = detail::scope_exit([&] {
  10833. svr.stop();
  10834. t.join();
  10835. ASSERT_FALSE(svr.is_running());
  10836. });
  10837. svr.wait_until_ready();
  10838. const std::string body =
  10839. "This is the preamble. It is to be ignored, though it\r\n"
  10840. "is a handy place for composition agents to include an\r\n"
  10841. "explanatory note to non-MIME conformant readers.\r\n"
  10842. "\r\n"
  10843. "\r\n"
  10844. "--simple boundary\r\n"
  10845. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10846. ": BAD...\r\n"
  10847. "\r\n"
  10848. "value1\r\n"
  10849. "--simple boundary\r\n"
  10850. "Content-Disposition: form-data; name=\"field2\"; "
  10851. "filename=\"example.txt\"\r\n"
  10852. "\r\n"
  10853. "value2\r\n"
  10854. "--simple boundary--\r\n"
  10855. "This is the epilogue. It is also to be ignored.\r\n";
  10856. std::string content_type =
  10857. R"(multipart/form-data; boundary="simple boundary")";
  10858. Client cli(HOST, PORT);
  10859. auto res = cli.Post("/post", body, content_type.c_str());
  10860. ASSERT_TRUE(res);
  10861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10862. }
  10863. TEST(MultipartFormDataTest, WithPreamble) {
  10864. Server svr;
  10865. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10866. res.set_content("ok", "text/plain");
  10867. });
  10868. thread t = thread([&] { svr.listen(HOST, PORT); });
  10869. auto se = detail::scope_exit([&] {
  10870. svr.stop();
  10871. t.join();
  10872. ASSERT_FALSE(svr.is_running());
  10873. });
  10874. svr.wait_until_ready();
  10875. const std::string body =
  10876. "This is the preamble. It is to be ignored, though it\r\n"
  10877. "is a handy place for composition agents to include an\r\n"
  10878. "explanatory note to non-MIME conformant readers.\r\n"
  10879. "\r\n"
  10880. "\r\n"
  10881. "--simple boundary\r\n"
  10882. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10883. "\r\n"
  10884. "value1\r\n"
  10885. "--simple boundary\r\n"
  10886. "Content-Disposition: form-data; name=\"field2\"; "
  10887. "filename=\"example.txt\"\r\n"
  10888. "\r\n"
  10889. "value2\r\n"
  10890. "--simple boundary--\r\n"
  10891. "This is the epilogue. It is also to be ignored.\r\n";
  10892. std::string content_type =
  10893. R"(multipart/form-data; boundary="simple boundary")";
  10894. Client cli(HOST, PORT);
  10895. auto res = cli.Post("/post", body, content_type.c_str());
  10896. ASSERT_TRUE(res);
  10897. EXPECT_EQ(StatusCode::OK_200, res->status);
  10898. }
  10899. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10901. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10902. const ContentReader &content_reader) {
  10903. if (req.is_multipart_form_data()) {
  10904. std::vector<FormData> items;
  10905. content_reader(
  10906. [&](const FormData &file) {
  10907. items.push_back(file);
  10908. return true;
  10909. },
  10910. [&](const char *data, size_t data_length) {
  10911. items.back().content.append(data, data_length);
  10912. return true;
  10913. });
  10914. EXPECT_TRUE(std::string(items[0].name) == "document");
  10915. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10916. EXPECT_TRUE(items[0].filename == "2MB_data");
  10917. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10918. EXPECT_TRUE(items[1].name == "hello");
  10919. EXPECT_TRUE(items[1].content == "world");
  10920. EXPECT_TRUE(items[1].filename == "");
  10921. EXPECT_TRUE(items[1].content_type == "");
  10922. } else {
  10923. std::string body;
  10924. content_reader([&](const char *data, size_t data_length) {
  10925. body.append(data, data_length);
  10926. return true;
  10927. });
  10928. }
  10929. });
  10930. auto port = svr.bind_to_any_port("localhost");
  10931. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10932. auto se = detail::scope_exit([&] {
  10933. svr.stop();
  10934. t.join();
  10935. ASSERT_FALSE(svr.is_running());
  10936. });
  10937. svr.wait_until_ready();
  10938. {
  10939. std::string data(1024 * 1024 * 2, '.');
  10940. std::stringstream buffer;
  10941. buffer << data;
  10942. SSLClient cli("localhost", port);
  10943. cli.enable_server_certificate_verification(false);
  10944. UploadFormDataItems items{
  10945. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10946. {"hello", "world", "", ""},
  10947. };
  10948. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10949. ASSERT_TRUE(res);
  10950. ASSERT_EQ(StatusCode::OK_200, res->status);
  10951. }
  10952. }
  10953. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10954. std::string data(1024 * 1024 * 2, '&');
  10955. std::stringstream buffer;
  10956. buffer << data;
  10957. Client cli("https://localhost:8080");
  10958. UploadFormDataItems items{
  10959. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10960. {"hello", "world", "", ""},
  10961. };
  10962. for (const char &c : " \t\r\n") {
  10963. auto res =
  10964. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10965. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10966. ASSERT_FALSE(res);
  10967. }
  10968. }
  10969. TEST(MultipartFormDataTest, PutFormData) {
  10970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10971. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10972. const ContentReader &content_reader) {
  10973. if (req.is_multipart_form_data()) {
  10974. std::vector<FormData> items;
  10975. content_reader(
  10976. [&](const FormData &file) {
  10977. items.push_back(file);
  10978. return true;
  10979. },
  10980. [&](const char *data, size_t data_length) {
  10981. items.back().content.append(data, data_length);
  10982. return true;
  10983. });
  10984. EXPECT_TRUE(std::string(items[0].name) == "document");
  10985. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10986. EXPECT_TRUE(items[0].filename == "2MB_data");
  10987. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10988. EXPECT_TRUE(items[1].name == "hello");
  10989. EXPECT_TRUE(items[1].content == "world");
  10990. EXPECT_TRUE(items[1].filename == "");
  10991. EXPECT_TRUE(items[1].content_type == "");
  10992. } else {
  10993. std::string body;
  10994. content_reader([&](const char *data, size_t data_length) {
  10995. body.append(data, data_length);
  10996. return true;
  10997. });
  10998. }
  10999. });
  11000. auto port = svr.bind_to_any_port("localhost");
  11001. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11002. auto se = detail::scope_exit([&] {
  11003. svr.stop();
  11004. t.join();
  11005. ASSERT_FALSE(svr.is_running());
  11006. });
  11007. svr.wait_until_ready();
  11008. {
  11009. std::string data(1024 * 1024 * 2, '&');
  11010. std::stringstream buffer;
  11011. buffer << data;
  11012. SSLClient cli("localhost", port);
  11013. cli.enable_server_certificate_verification(false);
  11014. UploadFormDataItems items{
  11015. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11016. {"hello", "world", "", ""},
  11017. };
  11018. auto res = cli.Put("/put", items);
  11019. ASSERT_TRUE(res);
  11020. ASSERT_EQ(StatusCode::OK_200, res->status);
  11021. }
  11022. }
  11023. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11025. svr.Put("/put_customboundary",
  11026. [&](const Request &req, const Response & /*res*/,
  11027. const ContentReader &content_reader) {
  11028. if (req.is_multipart_form_data()) {
  11029. std::vector<FormData> items;
  11030. content_reader(
  11031. [&](const FormData &file) {
  11032. items.push_back(file);
  11033. return true;
  11034. },
  11035. [&](const char *data, size_t data_length) {
  11036. items.back().content.append(data, data_length);
  11037. return true;
  11038. });
  11039. EXPECT_TRUE(std::string(items[0].name) == "document");
  11040. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11041. EXPECT_TRUE(items[0].filename == "2MB_data");
  11042. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11043. EXPECT_TRUE(items[1].name == "hello");
  11044. EXPECT_TRUE(items[1].content == "world");
  11045. EXPECT_TRUE(items[1].filename == "");
  11046. EXPECT_TRUE(items[1].content_type == "");
  11047. } else {
  11048. std::string body;
  11049. content_reader([&](const char *data, size_t data_length) {
  11050. body.append(data, data_length);
  11051. return true;
  11052. });
  11053. }
  11054. });
  11055. auto port = svr.bind_to_any_port("localhost");
  11056. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11057. auto se = detail::scope_exit([&] {
  11058. svr.stop();
  11059. t.join();
  11060. ASSERT_FALSE(svr.is_running());
  11061. });
  11062. svr.wait_until_ready();
  11063. {
  11064. std::string data(1024 * 1024 * 2, '&');
  11065. std::stringstream buffer;
  11066. buffer << data;
  11067. SSLClient cli("localhost", port);
  11068. cli.enable_server_certificate_verification(false);
  11069. UploadFormDataItems items{
  11070. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11071. {"hello", "world", "", ""},
  11072. };
  11073. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11074. ASSERT_TRUE(res);
  11075. ASSERT_EQ(StatusCode::OK_200, res->status);
  11076. }
  11077. }
  11078. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11079. std::string data(1024 * 1024 * 2, '&');
  11080. std::stringstream buffer;
  11081. buffer << data;
  11082. Client cli("https://localhost:8080");
  11083. cli.enable_server_certificate_verification(false);
  11084. UploadFormDataItems items{
  11085. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11086. {"hello", "world", "", ""},
  11087. };
  11088. for (const char &c : " \t\r\n") {
  11089. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11090. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11091. ASSERT_FALSE(res);
  11092. }
  11093. }
  11094. TEST(MultipartFormDataTest, AlternateFilename) {
  11095. auto handled = false;
  11096. Server svr;
  11097. svr.Post("/test", [&](const Request &req, Response &res) {
  11098. ASSERT_EQ(2u, req.form.files.size());
  11099. ASSERT_EQ(1u, req.form.fields.size());
  11100. // Test files
  11101. const auto &file1 = req.form.get_file("file1");
  11102. ASSERT_EQ("file1", file1.name);
  11103. ASSERT_EQ("A.txt", file1.filename);
  11104. ASSERT_EQ("text/plain", file1.content_type);
  11105. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11106. const auto &file2 = req.form.get_file("file2");
  11107. ASSERT_EQ("file2", file2.name);
  11108. ASSERT_EQ("a.html", file2.filename);
  11109. ASSERT_EQ("text/html", file2.content_type);
  11110. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11111. file2.content);
  11112. // Test text field
  11113. const auto &text = req.form.get_field("text");
  11114. ASSERT_EQ("text default", text);
  11115. res.set_content("ok", "text/plain");
  11116. handled = true;
  11117. });
  11118. thread t = thread([&] { svr.listen(HOST, PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. ASSERT_TRUE(handled);
  11124. });
  11125. svr.wait_until_ready();
  11126. auto req = "POST /test HTTP/1.1\r\n"
  11127. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11128. "Content-Length: 399\r\n"
  11129. "\r\n"
  11130. "----------\r\n"
  11131. "Content-Disposition: form-data; name=\"text\"\r\n"
  11132. "\r\n"
  11133. "text default\r\n"
  11134. "----------\r\n"
  11135. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11136. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11137. "Content-Type: text/plain\r\n"
  11138. "\r\n"
  11139. "Content of a.txt.\r\n"
  11140. "\r\n"
  11141. "----------\r\n"
  11142. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11143. "\"a.html\"\r\n"
  11144. "Content-Type: text/html\r\n"
  11145. "\r\n"
  11146. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11147. "\r\n"
  11148. "------------\r\n";
  11149. ASSERT_TRUE(send_request(1, req));
  11150. }
  11151. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11152. auto handled = false;
  11153. Server svr;
  11154. svr.Post("/test", [&](const Request &req, Response &res) {
  11155. // Case-insensitive "utf-8''" prefix with a long value
  11156. const auto &file = req.form.get_file("file1");
  11157. ASSERT_EQ("file1", file.name);
  11158. // 8000 chars exercises both the Content-Disposition parser and the
  11159. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11160. // Prior to the fix, std::regex_match on this header would cause O(N)
  11161. // stack recursion in libstdc++, leading to SIGSEGV.
  11162. std::string expected_filename(8000, 'A');
  11163. ASSERT_EQ(expected_filename, file.filename);
  11164. res.set_content("ok", "text/plain");
  11165. handled = true;
  11166. });
  11167. thread t = thread([&] { svr.listen(HOST, PORT); });
  11168. auto se = detail::scope_exit([&] {
  11169. svr.stop();
  11170. t.join();
  11171. ASSERT_FALSE(svr.is_running());
  11172. ASSERT_TRUE(handled);
  11173. });
  11174. svr.wait_until_ready();
  11175. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11176. // Regression test for GHSA-qq6v-r583-3h69
  11177. std::string long_filename(8000, 'A');
  11178. std::string body = "----------\r\n"
  11179. "Content-Disposition: form-data; name=\"file1\"; "
  11180. "filename*=\"Utf-8''" +
  11181. long_filename +
  11182. "\"\r\n"
  11183. "\r\n"
  11184. "hello\r\n"
  11185. "------------\r\n";
  11186. auto req = "POST /test HTTP/1.1\r\n"
  11187. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11188. "Content-Length: " +
  11189. std::to_string(body.size()) + "\r\n\r\n" + body;
  11190. ASSERT_TRUE(send_request(1, req));
  11191. }
  11192. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11193. auto handled = false;
  11194. Server svr;
  11195. svr.Post("/test", [&](const Request &req, Response &) {
  11196. ASSERT_EQ(2u, req.form.fields.size());
  11197. const auto &text1 = req.form.get_field("text1");
  11198. ASSERT_EQ("text1", text1);
  11199. const auto &text2 = req.form.get_field("text2");
  11200. ASSERT_EQ("text2", text2);
  11201. handled = true;
  11202. });
  11203. thread t = thread([&] { svr.listen(HOST, PORT); });
  11204. auto se = detail::scope_exit([&] {
  11205. svr.stop();
  11206. t.join();
  11207. ASSERT_FALSE(svr.is_running());
  11208. ASSERT_TRUE(handled);
  11209. });
  11210. svr.wait_until_ready();
  11211. auto req = "POST /test HTTP/1.1\r\n"
  11212. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11213. "Content-Length: 146\r\n"
  11214. "\r\n----------\r\n"
  11215. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11216. "\r\n"
  11217. "text1"
  11218. "\r\n----------\r\n"
  11219. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11220. "\r\n"
  11221. "text2"
  11222. "\r\n------------";
  11223. std::string response;
  11224. ASSERT_TRUE(send_request(1, req, &response));
  11225. ASSERT_EQ("200", response.substr(9, 3));
  11226. }
  11227. TEST(MultipartFormDataTest, ContentLength) {
  11228. auto handled = false;
  11229. Server svr;
  11230. svr.Post("/test", [&](const Request &req, Response &) {
  11231. ASSERT_EQ(2u, req.form.fields.size());
  11232. const auto &text1 = req.form.get_field("text1");
  11233. ASSERT_EQ("text1", text1);
  11234. const auto &text2 = req.form.get_field("text2");
  11235. ASSERT_EQ("text2", text2);
  11236. handled = true;
  11237. });
  11238. thread t = thread([&] { svr.listen(HOST, PORT); });
  11239. auto se = detail::scope_exit([&] {
  11240. svr.stop();
  11241. t.join();
  11242. ASSERT_FALSE(svr.is_running());
  11243. ASSERT_TRUE(handled);
  11244. });
  11245. svr.wait_until_ready();
  11246. auto req = "POST /test HTTP/1.1\r\n"
  11247. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11248. "Content-Length: 167\r\n"
  11249. "\r\n----------\r\n"
  11250. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11251. "Content-Length: 5\r\n"
  11252. "\r\n"
  11253. "text1"
  11254. "\r\n----------\r\n"
  11255. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11256. "\r\n"
  11257. "text2"
  11258. "\r\n------------\r\n";
  11259. std::string response;
  11260. ASSERT_TRUE(send_request(1, req, &response));
  11261. ASSERT_EQ("200", response.substr(9, 3));
  11262. }
  11263. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11264. auto handled = false;
  11265. Server svr;
  11266. svr.Post("/test", [&](const Request &req, Response &) {
  11267. ASSERT_EQ(2u, req.form.fields.size());
  11268. const auto &text1 = req.form.get_field("text1");
  11269. ASSERT_EQ("text1", text1);
  11270. // TODO: Add header access for text fields if needed
  11271. const auto &text2 = req.form.get_field("text2");
  11272. ASSERT_EQ("text2", text2);
  11273. // TODO: Header access for text fields needs to be implemented
  11274. // auto &headers = it->second.headers;
  11275. // ASSERT_EQ(3U, headers.size());
  11276. // auto custom_header = headers.find("x-whatever");
  11277. // ASSERT_TRUE(custom_header != headers.end());
  11278. // ASSERT_NE("customvalue", custom_header->second);
  11279. // ASSERT_EQ("CustomValue", custom_header->second);
  11280. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11281. handled = true;
  11282. });
  11283. thread t = thread([&] { svr.listen(HOST, PORT); });
  11284. auto se = detail::scope_exit([&] {
  11285. svr.stop();
  11286. t.join();
  11287. ASSERT_FALSE(svr.is_running());
  11288. ASSERT_TRUE(handled);
  11289. });
  11290. svr.wait_until_ready();
  11291. auto req = "POST /test HTTP/1.1\r\n"
  11292. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11293. "Content-Length: 232\r\n"
  11294. "\r\n----------\r\n"
  11295. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11296. "Content-Length: 5\r\n"
  11297. "X-Test: 1\r\n"
  11298. "\r\n"
  11299. "text1"
  11300. "\r\n----------\r\n"
  11301. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11302. "Content-Type: text/plain\r\n"
  11303. "X-Whatever: CustomValue\r\n"
  11304. "\r\n"
  11305. "text2"
  11306. "\r\n------------\r\n"
  11307. "That should be disregarded. Not even read";
  11308. std::string response;
  11309. ASSERT_TRUE(send_request(1, req, &response));
  11310. ASSERT_EQ("200", response.substr(9, 3));
  11311. }
  11312. TEST(MultipartFormDataTest, LargeHeader) {
  11313. auto handled = false;
  11314. Server svr;
  11315. svr.Post("/test", [&](const Request &req, Response &) {
  11316. ASSERT_EQ(1u, req.form.fields.size());
  11317. const auto &text = req.form.get_field("name1");
  11318. ASSERT_EQ("text1", text);
  11319. handled = true;
  11320. });
  11321. thread t = thread([&] { svr.listen(HOST, PORT); });
  11322. auto se = detail::scope_exit([&] {
  11323. svr.stop();
  11324. t.join();
  11325. ASSERT_FALSE(svr.is_running());
  11326. ASSERT_TRUE(handled);
  11327. });
  11328. svr.wait_until_ready();
  11329. auto boundary = std::string("cpp-httplib-multipart-data");
  11330. std::string content = "--" + boundary +
  11331. "\r\n"
  11332. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11333. "\r\n"
  11334. "text1\r\n"
  11335. "--" +
  11336. boundary + "--\r\n";
  11337. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11338. "Content-Type: multipart/form-data;boundary=" +
  11339. boundary +
  11340. "\r\n"
  11341. "Content-Length: " +
  11342. std::to_string(content.size()) +
  11343. "\r\n"
  11344. "Dummy-Header: ";
  11345. std::string header_suffix = "\r\n"
  11346. "\r\n";
  11347. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11348. size_t header_dummy_size =
  11349. read_buff_size -
  11350. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11351. auto header_dummy = std::string(header_dummy_size, '@');
  11352. auto req = header_prefix + header_dummy + header_suffix + content;
  11353. std::string response;
  11354. ASSERT_TRUE(send_request(1, req, &response));
  11355. ASSERT_EQ("200", response.substr(9, 3));
  11356. }
  11357. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11358. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11359. // (not chunked Transfer-Encoding) after the streaming refactor.
  11360. auto handled = false;
  11361. Server svr;
  11362. svr.Post("/upload", [&](const Request &req, Response &res) {
  11363. auto cl_it = req.headers.find("Content-Length");
  11364. EXPECT_TRUE(cl_it != req.headers.end());
  11365. auto te_it = req.headers.find("Transfer-Encoding");
  11366. EXPECT_TRUE(te_it == req.headers.end());
  11367. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11368. res.set_content("ok", "text/plain");
  11369. handled = true;
  11370. });
  11371. auto port = svr.bind_to_any_port(HOST);
  11372. auto t = thread([&] { svr.listen_after_bind(); });
  11373. auto se = detail::scope_exit([&] {
  11374. svr.stop();
  11375. t.join();
  11376. ASSERT_FALSE(svr.is_running());
  11377. ASSERT_TRUE(handled);
  11378. });
  11379. svr.wait_until_ready();
  11380. UploadFormDataItems items = {
  11381. {"field1", "hello", "", "text/plain"},
  11382. {"file1", "world", "test.txt", "application/octet-stream"},
  11383. };
  11384. Client cli(HOST, port);
  11385. auto res = cli.Post("/upload", {}, items);
  11386. ASSERT_TRUE(res);
  11387. EXPECT_EQ(StatusCode::OK_200, res->status);
  11388. }
  11389. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11390. // Verify that make_multipart_content_provider coalesces many small segments
  11391. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11392. constexpr size_t kItemCount = 1000;
  11393. UploadFormDataItems items;
  11394. items.reserve(kItemCount);
  11395. for (size_t i = 0; i < kItemCount; i++) {
  11396. items.push_back(
  11397. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11398. }
  11399. const std::string boundary = "----test-boundary";
  11400. auto content_length = detail::get_multipart_content_length(items, boundary);
  11401. auto provider = detail::make_multipart_content_provider(items, boundary);
  11402. // Drive the provider the same way write_content_with_progress does
  11403. size_t write_count = 0;
  11404. size_t total_bytes = 0;
  11405. DataSink sink;
  11406. size_t offset = 0;
  11407. sink.write = [&](const char *d, size_t l) -> bool {
  11408. (void)d;
  11409. write_count++;
  11410. total_bytes += l;
  11411. offset += l;
  11412. return true;
  11413. };
  11414. sink.is_writable = []() -> bool { return true; };
  11415. while (offset < content_length) {
  11416. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11417. }
  11418. EXPECT_EQ(content_length, total_bytes);
  11419. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11420. // With buffering into 64KB blocks, write_count should be much smaller.
  11421. auto segment_count = 3 * kItemCount + 1;
  11422. EXPECT_LT(write_count, segment_count / 10);
  11423. }
  11424. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11425. // Integration test: send many UploadFormDataItems and verify the server
  11426. // receives all of them correctly (#2410).
  11427. constexpr size_t kItemCount = 500;
  11428. auto handled = false;
  11429. Server svr;
  11430. svr.Post("/upload", [&](const Request &req, Response &res) {
  11431. EXPECT_EQ(kItemCount, req.form.fields.size());
  11432. for (size_t i = 0; i < kItemCount; i++) {
  11433. auto key = "field" + std::to_string(i);
  11434. auto val = "value" + std::to_string(i);
  11435. auto it = req.form.fields.find(key);
  11436. if (it != req.form.fields.end()) {
  11437. EXPECT_EQ(val, it->second.content);
  11438. } else {
  11439. ADD_FAILURE() << "Missing field: " << key;
  11440. }
  11441. }
  11442. res.set_content("ok", "text/plain");
  11443. handled = true;
  11444. });
  11445. auto port = svr.bind_to_any_port(HOST);
  11446. auto t = thread([&] { svr.listen_after_bind(); });
  11447. auto se = detail::scope_exit([&] {
  11448. svr.stop();
  11449. t.join();
  11450. ASSERT_FALSE(svr.is_running());
  11451. ASSERT_TRUE(handled);
  11452. });
  11453. svr.wait_until_ready();
  11454. UploadFormDataItems items;
  11455. items.reserve(kItemCount);
  11456. for (size_t i = 0; i < kItemCount; i++) {
  11457. items.push_back(
  11458. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11459. }
  11460. Client cli(HOST, port);
  11461. auto res = cli.Post("/upload", items);
  11462. ASSERT_TRUE(res);
  11463. EXPECT_EQ(StatusCode::OK_200, res->status);
  11464. }
  11465. TEST(MultipartFormDataTest, MakeFileProvider) {
  11466. // Verify make_file_provider sends a file's contents correctly.
  11467. const std::string file_content(4096, 'Z');
  11468. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11469. {
  11470. std::ofstream ofs(tmp_path, std::ios::binary);
  11471. ofs.write(file_content.data(),
  11472. static_cast<std::streamsize>(file_content.size()));
  11473. }
  11474. auto handled = false;
  11475. Server svr;
  11476. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11477. const ContentReader &content_reader) {
  11478. ASSERT_TRUE(req.is_multipart_form_data());
  11479. std::vector<FormData> items;
  11480. content_reader(
  11481. [&](const FormData &file) {
  11482. items.push_back(file);
  11483. return true;
  11484. },
  11485. [&](const char *data, size_t data_length) {
  11486. items.back().content.append(data, data_length);
  11487. return true;
  11488. });
  11489. ASSERT_EQ(1u, items.size());
  11490. EXPECT_EQ("myfile", items[0].name);
  11491. EXPECT_EQ("data.bin", items[0].filename);
  11492. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11493. EXPECT_EQ(file_content, items[0].content);
  11494. handled = true;
  11495. });
  11496. auto port = svr.bind_to_any_port(HOST);
  11497. auto t = thread([&] { svr.listen_after_bind(); });
  11498. auto se = detail::scope_exit([&] {
  11499. svr.stop();
  11500. t.join();
  11501. ASSERT_FALSE(svr.is_running());
  11502. ASSERT_TRUE(handled);
  11503. std::remove(tmp_path.c_str());
  11504. });
  11505. svr.wait_until_ready();
  11506. FormDataProviderItems providers;
  11507. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11508. "application/octet-stream"));
  11509. Client cli(HOST, port);
  11510. auto res = cli.Post("/upload", {}, {}, providers);
  11511. ASSERT_TRUE(res);
  11512. EXPECT_EQ(StatusCode::OK_200, res->status);
  11513. }
  11514. TEST(MakeFileBodyTest, Basic) {
  11515. const std::string file_content(4096, 'Z');
  11516. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11517. {
  11518. std::ofstream ofs(tmp_path, std::ios::binary);
  11519. ofs.write(file_content.data(),
  11520. static_cast<std::streamsize>(file_content.size()));
  11521. }
  11522. auto handled = false;
  11523. Server svr;
  11524. svr.Post("/upload", [&](const Request &req, Response &res) {
  11525. EXPECT_EQ(file_content, req.body);
  11526. handled = true;
  11527. res.status = StatusCode::OK_200;
  11528. });
  11529. auto port = svr.bind_to_any_port(HOST);
  11530. auto t = thread([&] { svr.listen_after_bind(); });
  11531. auto se = detail::scope_exit([&] {
  11532. svr.stop();
  11533. t.join();
  11534. ASSERT_FALSE(svr.is_running());
  11535. ASSERT_TRUE(handled);
  11536. std::remove(tmp_path.c_str());
  11537. });
  11538. svr.wait_until_ready();
  11539. auto fb = make_file_body(tmp_path);
  11540. ASSERT_GT(fb.first, 0u);
  11541. Client cli(HOST, port);
  11542. auto res =
  11543. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11544. ASSERT_TRUE(res);
  11545. EXPECT_EQ(StatusCode::OK_200, res->status);
  11546. }
  11547. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11548. static constexpr unsigned int number_of_tasks{1000000};
  11549. std::atomic_uint count{0};
  11550. std::unique_ptr<TaskQueue> task_queue{
  11551. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11552. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11553. auto queued = task_queue->enqueue(
  11554. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11555. EXPECT_TRUE(queued);
  11556. }
  11557. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11558. task_queue->shutdown();
  11559. #else
  11560. EXPECT_NO_THROW(task_queue->shutdown());
  11561. #endif
  11562. EXPECT_EQ(number_of_tasks, count.load());
  11563. }
  11564. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11565. static constexpr unsigned int number_of_tasks{1000000};
  11566. static constexpr unsigned int qlimit{2};
  11567. unsigned int queued_count{0};
  11568. std::atomic_uint count{0};
  11569. std::unique_ptr<TaskQueue> task_queue{
  11570. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11571. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11572. if (task_queue->enqueue(
  11573. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11574. queued_count++;
  11575. }
  11576. }
  11577. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11578. task_queue->shutdown();
  11579. #else
  11580. EXPECT_NO_THROW(task_queue->shutdown());
  11581. #endif
  11582. EXPECT_EQ(queued_count, count.load());
  11583. EXPECT_TRUE(queued_count <= number_of_tasks);
  11584. EXPECT_TRUE(queued_count >= qlimit);
  11585. }
  11586. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11587. // Use a short idle timeout so a dynamic thread spawns, times out and
  11588. // exits during the test, and the pool keeps working afterwards.
  11589. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11590. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11591. /*idle_timeout_sec=*/1}};
  11592. std::atomic_uint count{0};
  11593. std::condition_variable cv;
  11594. std::mutex mtx;
  11595. bool release = false;
  11596. // Block the base thread so the second task spawns a dynamic thread.
  11597. EXPECT_TRUE(task_queue->enqueue([&] {
  11598. std::unique_lock<std::mutex> lock(mtx);
  11599. while (!release) {
  11600. cv.wait(lock);
  11601. }
  11602. count++;
  11603. }));
  11604. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11605. // Let the dynamic thread finish its task and exceed the idle timeout.
  11606. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11607. {
  11608. std::unique_lock<std::mutex> lock(mtx);
  11609. release = true;
  11610. }
  11611. cv.notify_all();
  11612. // The pool must still accept and run tasks after the dynamic thread exited.
  11613. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11614. task_queue->shutdown();
  11615. EXPECT_EQ(3u, count.load());
  11616. }
  11617. TEST(TaskQueueTest, MaxQueuedRequests) {
  11618. static constexpr unsigned int qlimit{3};
  11619. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11620. std::condition_variable sem_cv;
  11621. std::mutex sem_mtx;
  11622. int credits = 0;
  11623. bool queued;
  11624. /* Fill up the queue with tasks that will block until we give them credits to
  11625. * complete. */
  11626. for (unsigned int n = 0; n <= qlimit;) {
  11627. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11628. std::unique_lock<std::mutex> lock(sem_mtx);
  11629. while (credits <= 0) {
  11630. sem_cv.wait(lock);
  11631. }
  11632. /* Consume the credit and signal the test code if they are all gone. */
  11633. if (--credits == 0) { sem_cv.notify_one(); }
  11634. });
  11635. if (n < qlimit) {
  11636. /* The first qlimit enqueues must succeed. */
  11637. EXPECT_TRUE(queued);
  11638. } else {
  11639. /* The last one will succeed only when the worker thread
  11640. * starts and dequeues the first blocking task. Although
  11641. * not necessary for the correctness of this test, we sleep for
  11642. * a short while to avoid busy waiting. */
  11643. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11644. }
  11645. if (queued) { n++; }
  11646. }
  11647. /* Further enqueues must fail since the queue is full. */
  11648. for (auto i = 0; i < 4; i++) {
  11649. queued = task_queue->enqueue([] {});
  11650. EXPECT_FALSE(queued);
  11651. }
  11652. /* Give the credits to allow the previous tasks to complete. */
  11653. {
  11654. std::unique_lock<std::mutex> lock(sem_mtx);
  11655. credits += qlimit + 1;
  11656. }
  11657. sem_cv.notify_all();
  11658. /* Wait for all the credits to be consumed. */
  11659. {
  11660. std::unique_lock<std::mutex> lock(sem_mtx);
  11661. while (credits > 0) {
  11662. sem_cv.wait(lock);
  11663. }
  11664. }
  11665. /* Check that we are able again to enqueue at least qlimit tasks. */
  11666. for (unsigned int i = 0; i < qlimit; i++) {
  11667. queued = task_queue->enqueue([] {});
  11668. EXPECT_TRUE(queued);
  11669. }
  11670. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11671. task_queue->shutdown();
  11672. #else
  11673. EXPECT_NO_THROW(task_queue->shutdown());
  11674. #endif
  11675. }
  11676. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11677. Server svr;
  11678. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11679. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11680. });
  11681. svr.Get("/hello", [](const Request &req, Response &res) {
  11682. res.set_content(req.get_param_value("key"), "text/plain");
  11683. });
  11684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11685. auto se = detail::scope_exit([&] {
  11686. svr.stop();
  11687. thread.join();
  11688. ASSERT_FALSE(svr.is_running());
  11689. });
  11690. svr.wait_until_ready();
  11691. {
  11692. Client cli(HOST, PORT);
  11693. cli.set_follow_location(true);
  11694. auto res = cli.Get("/");
  11695. ASSERT_TRUE(res);
  11696. EXPECT_EQ(StatusCode::OK_200, res->status);
  11697. EXPECT_EQ("val&key2=val2", res->body);
  11698. }
  11699. }
  11700. #endif
  11701. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11702. Server svr;
  11703. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11704. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11705. });
  11706. svr.Get("/hello", [](const Request &req, Response &res) {
  11707. res.set_content(req.get_param_value("key"), "text/plain");
  11708. });
  11709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11710. auto se = detail::scope_exit([&] {
  11711. svr.stop();
  11712. thread.join();
  11713. ASSERT_FALSE(svr.is_running());
  11714. });
  11715. svr.wait_until_ready();
  11716. {
  11717. Client cli(HOST, PORT);
  11718. cli.set_follow_location(true);
  11719. auto res = cli.Get("/");
  11720. ASSERT_TRUE(res);
  11721. EXPECT_EQ(StatusCode::OK_200, res->status);
  11722. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11723. }
  11724. }
  11725. TEST(RedirectTest, RedirectWithPlusInPath) {
  11726. Server svr;
  11727. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11728. res.set_redirect("/a+b");
  11729. });
  11730. // Route pattern uses regex; escape + as \\+
  11731. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11732. res.set_content(req.path, "text/plain");
  11733. });
  11734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11735. auto se = detail::scope_exit([&] {
  11736. svr.stop();
  11737. thread.join();
  11738. ASSERT_FALSE(svr.is_running());
  11739. });
  11740. svr.wait_until_ready();
  11741. {
  11742. Client cli(HOST, PORT);
  11743. cli.set_follow_location(true);
  11744. auto res = cli.Get("/");
  11745. ASSERT_TRUE(res);
  11746. EXPECT_EQ(StatusCode::OK_200, res->status);
  11747. EXPECT_EQ("/a+b", res->body);
  11748. }
  11749. }
  11750. #ifdef CPPHTTPLIB_SSL_ENABLED
  11751. TEST(RedirectTest, Issue2185_Online) {
  11752. SSLClient client("github.com");
  11753. client.set_follow_location(true);
  11754. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11755. "Coollab-Windows.zip");
  11756. ASSERT_TRUE(res);
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. EXPECT_EQ(9920427U, res->body.size());
  11759. }
  11760. #endif
  11761. TEST(VulnerabilityTest, CRLFInjection) {
  11762. Server svr;
  11763. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11764. res.set_content("Hello 1", "text/plain");
  11765. });
  11766. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11767. res.set_content("Hello 2", "text/plain");
  11768. });
  11769. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11770. res.set_content("Hello 3", "text/plain");
  11771. });
  11772. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11773. res.set_content("Hello 4", "text/plain");
  11774. });
  11775. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11776. for (const auto &x : req.headers) {
  11777. auto key = x.first;
  11778. EXPECT_STRNE("evil", key.c_str());
  11779. }
  11780. });
  11781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11782. auto se = detail::scope_exit([&] {
  11783. svr.stop();
  11784. thread.join();
  11785. ASSERT_FALSE(svr.is_running());
  11786. });
  11787. svr.wait_until_ready();
  11788. {
  11789. Client cli(HOST, PORT);
  11790. cli.Post("/test1", "A=B",
  11791. "application/x-www-form-urlencoded\r\nevil: hello1");
  11792. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11793. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11794. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11795. }
  11796. }
  11797. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11798. auto server_thread = std::thread([] {
  11799. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11800. default_socket_options(srv);
  11801. sockaddr_in addr{};
  11802. addr.sin_family = AF_INET;
  11803. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11804. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11805. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11806. ::listen(srv, 1);
  11807. sockaddr_in cli_addr{};
  11808. socklen_t cli_len = sizeof(cli_addr);
  11809. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11810. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11811. std::string buf_all;
  11812. char buf[2048];
  11813. ssize_t n;
  11814. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11815. buf_all.append(buf, static_cast<size_t>(n));
  11816. size_t pos;
  11817. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11818. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11819. auto e = request_block.find("\r\n");
  11820. if (e != std::string::npos) {
  11821. auto request_line = request_block.substr(0, e);
  11822. std::string msg =
  11823. "CRLF injection detected in request line: '" + request_line + "'";
  11824. EXPECT_FALSE(true) << msg;
  11825. }
  11826. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11827. ::send(cli,
  11828. #ifdef _WIN32
  11829. static_cast<const char *>(resp.c_str()),
  11830. static_cast<int>(resp.size()),
  11831. #else
  11832. resp.c_str(), resp.size(),
  11833. #endif
  11834. 0);
  11835. buf_all.erase(0, pos + 4);
  11836. }
  11837. }
  11838. detail::close_socket(cli);
  11839. detail::close_socket(srv);
  11840. });
  11841. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11842. auto cli = Client("127.0.0.1", PORT + 1);
  11843. auto headers = Headers{
  11844. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11845. {"Connection", "keep-alive"}};
  11846. auto res = cli.Get("/hi", headers);
  11847. EXPECT_FALSE(res);
  11848. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11849. server_thread.join();
  11850. }
  11851. TEST(PathParamsTest, StaticMatch) {
  11852. const auto pattern = "/users/all";
  11853. detail::PathParamsMatcher matcher(pattern);
  11854. Request request;
  11855. request.path = "/users/all";
  11856. ASSERT_TRUE(matcher.match(request));
  11857. std::unordered_map<std::string, std::string> expected_params = {};
  11858. EXPECT_EQ(request.path_params, expected_params);
  11859. }
  11860. TEST(PathParamsTest, StaticMismatch) {
  11861. const auto pattern = "/users/all";
  11862. detail::PathParamsMatcher matcher(pattern);
  11863. Request request;
  11864. request.path = "/users/1";
  11865. ASSERT_FALSE(matcher.match(request));
  11866. }
  11867. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11868. const auto pattern = "/users/:id/subscriptions";
  11869. detail::PathParamsMatcher matcher(pattern);
  11870. Request request;
  11871. request.path = "/users/42/subscriptions";
  11872. ASSERT_TRUE(matcher.match(request));
  11873. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11874. EXPECT_EQ(request.path_params, expected_params);
  11875. }
  11876. TEST(PathParamsTest, SingleParamInTheEnd) {
  11877. const auto pattern = "/users/:id";
  11878. detail::PathParamsMatcher matcher(pattern);
  11879. Request request;
  11880. request.path = "/users/24";
  11881. ASSERT_TRUE(matcher.match(request));
  11882. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11883. EXPECT_EQ(request.path_params, expected_params);
  11884. }
  11885. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11886. const auto pattern = "/users/:id/";
  11887. detail::PathParamsMatcher matcher(pattern);
  11888. Request request;
  11889. request.path = "/users/42/";
  11890. ASSERT_TRUE(matcher.match(request));
  11891. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11892. EXPECT_EQ(request.path_params, expected_params);
  11893. }
  11894. TEST(PathParamsTest, EmptyParam) {
  11895. const auto pattern = "/users/:id/";
  11896. detail::PathParamsMatcher matcher(pattern);
  11897. Request request;
  11898. request.path = "/users//";
  11899. ASSERT_TRUE(matcher.match(request));
  11900. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11901. EXPECT_EQ(request.path_params, expected_params);
  11902. }
  11903. TEST(PathParamsTest, FragmentMismatch) {
  11904. const auto pattern = "/users/:id/";
  11905. detail::PathParamsMatcher matcher(pattern);
  11906. Request request;
  11907. request.path = "/admins/24/";
  11908. ASSERT_FALSE(matcher.match(request));
  11909. }
  11910. TEST(PathParamsTest, ExtraFragments) {
  11911. const auto pattern = "/users/:id";
  11912. detail::PathParamsMatcher matcher(pattern);
  11913. Request request;
  11914. request.path = "/users/42/subscriptions";
  11915. ASSERT_FALSE(matcher.match(request));
  11916. }
  11917. TEST(PathParamsTest, MissingTrailingParam) {
  11918. const auto pattern = "/users/:id";
  11919. detail::PathParamsMatcher matcher(pattern);
  11920. Request request;
  11921. request.path = "/users";
  11922. ASSERT_FALSE(matcher.match(request));
  11923. }
  11924. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11925. const auto pattern = "/users/:id/subscriptions";
  11926. detail::PathParamsMatcher matcher(pattern);
  11927. Request request;
  11928. request.path = "/users/subscriptions";
  11929. ASSERT_FALSE(matcher.match(request));
  11930. }
  11931. TEST(PathParamsTest, MultipleParams) {
  11932. const auto pattern = "/users/:userid/subscriptions/:subid";
  11933. detail::PathParamsMatcher matcher(pattern);
  11934. Request request;
  11935. request.path = "/users/42/subscriptions/2";
  11936. ASSERT_TRUE(matcher.match(request));
  11937. std::unordered_map<std::string, std::string> expected_params = {
  11938. {"userid", "42"}, {"subid", "2"}};
  11939. EXPECT_EQ(request.path_params, expected_params);
  11940. }
  11941. TEST(PathParamsTest, SequenceOfParams) {
  11942. const auto pattern = "/values/:x/:y/:z";
  11943. detail::PathParamsMatcher matcher(pattern);
  11944. Request request;
  11945. request.path = "/values/1/2/3";
  11946. ASSERT_TRUE(matcher.match(request));
  11947. std::unordered_map<std::string, std::string> expected_params = {
  11948. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11949. EXPECT_EQ(request.path_params, expected_params);
  11950. }
  11951. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11952. const auto pattern = "/prefix:suffix";
  11953. detail::PathParamsMatcher matcher(pattern);
  11954. Request request;
  11955. request.path = "/prefix:suffix";
  11956. ASSERT_TRUE(matcher.match(request));
  11957. const std::unordered_map<std::string, std::string> expected_params = {};
  11958. EXPECT_EQ(request.path_params, expected_params);
  11959. }
  11960. TEST(ParseUrlTest, VariousPatterns) {
  11961. {
  11962. detail::UrlComponents uc;
  11963. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11964. EXPECT_EQ("http", uc.scheme);
  11965. EXPECT_EQ("example.com", uc.host);
  11966. EXPECT_EQ("8080", uc.port);
  11967. EXPECT_EQ("/path", uc.path);
  11968. EXPECT_EQ("?q=1", uc.query);
  11969. }
  11970. {
  11971. detail::UrlComponents uc;
  11972. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11973. EXPECT_EQ("https", uc.scheme);
  11974. EXPECT_EQ("example.com", uc.host);
  11975. EXPECT_TRUE(uc.port.empty());
  11976. EXPECT_EQ("/path", uc.path);
  11977. }
  11978. {
  11979. detail::UrlComponents uc;
  11980. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11981. EXPECT_EQ("::1", uc.host);
  11982. EXPECT_EQ("8080", uc.port);
  11983. EXPECT_EQ("/path", uc.path);
  11984. }
  11985. {
  11986. detail::UrlComponents uc;
  11987. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11988. }
  11989. {
  11990. detail::UrlComponents uc;
  11991. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11992. EXPECT_TRUE(uc.scheme.empty());
  11993. EXPECT_EQ("example.com", uc.host);
  11994. EXPECT_EQ("/path", uc.path);
  11995. EXPECT_EQ("?q=1", uc.query);
  11996. }
  11997. {
  11998. detail::UrlComponents uc;
  11999. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12000. EXPECT_TRUE(uc.host.empty());
  12001. EXPECT_EQ("/path", uc.path);
  12002. EXPECT_EQ("?q=1", uc.query);
  12003. }
  12004. {
  12005. detail::UrlComponents uc;
  12006. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12007. EXPECT_EQ("example.com", uc.host);
  12008. EXPECT_EQ("8080", uc.port);
  12009. }
  12010. {
  12011. // Unix socket path — must not be parsed as host
  12012. detail::UrlComponents uc;
  12013. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12014. EXPECT_TRUE(uc.host.empty());
  12015. }
  12016. {
  12017. detail::UrlComponents uc;
  12018. ASSERT_TRUE(detail::parse_url("", uc));
  12019. EXPECT_TRUE(uc.host.empty());
  12020. EXPECT_TRUE(uc.path.empty());
  12021. }
  12022. {
  12023. detail::UrlComponents uc;
  12024. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12025. }
  12026. {
  12027. detail::UrlComponents uc;
  12028. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12029. }
  12030. {
  12031. // Accepted by parse_url; callers restrict to http/https
  12032. detail::UrlComponents uc;
  12033. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12034. EXPECT_EQ("ftp", uc.scheme);
  12035. }
  12036. {
  12037. detail::UrlComponents uc;
  12038. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12039. }
  12040. {
  12041. detail::UrlComponents uc;
  12042. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12043. }
  12044. }
  12045. TEST(ParseUrlTest, FragmentHandling) {
  12046. {
  12047. detail::UrlComponents uc;
  12048. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12049. EXPECT_EQ("/path", uc.path);
  12050. EXPECT_TRUE(uc.query.empty());
  12051. }
  12052. {
  12053. detail::UrlComponents uc;
  12054. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12055. EXPECT_TRUE(uc.path.empty());
  12056. EXPECT_TRUE(uc.query.empty());
  12057. }
  12058. }
  12059. TEST(ParseUrlTest, UserinfoHandling) {
  12060. // Userinfo with @ but no colon — host includes @
  12061. detail::UrlComponents uc;
  12062. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12063. EXPECT_EQ("user@host.com", uc.host);
  12064. EXPECT_EQ("/path", uc.path);
  12065. }
  12066. TEST(ParseUrlTest, IPv6EdgeCases) {
  12067. {
  12068. detail::UrlComponents uc;
  12069. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12070. EXPECT_TRUE(uc.scheme.empty());
  12071. EXPECT_EQ("::1", uc.host);
  12072. EXPECT_EQ("8080", uc.port);
  12073. }
  12074. {
  12075. // Zone ID '%25' is not in [a-fA-F0-9:]
  12076. detail::UrlComponents uc;
  12077. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12078. }
  12079. }
  12080. TEST(ParseUrlTest, SchemeEdgeCases) {
  12081. {
  12082. detail::UrlComponents uc;
  12083. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12084. }
  12085. {
  12086. detail::UrlComponents uc;
  12087. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12088. }
  12089. {
  12090. detail::UrlComponents uc;
  12091. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12092. }
  12093. }
  12094. TEST(ParseUrlTest, PortEdgeCases) {
  12095. {
  12096. detail::UrlComponents uc;
  12097. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12098. EXPECT_TRUE(uc.port.empty());
  12099. EXPECT_EQ("/path", uc.path);
  12100. }
  12101. {
  12102. // parse_url accepts any port string; validation is done by parse_port
  12103. detail::UrlComponents uc;
  12104. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12105. EXPECT_EQ("abc", uc.port);
  12106. }
  12107. }
  12108. TEST(ParseUrlTest, WebSocketPatterns) {
  12109. {
  12110. detail::UrlComponents uc;
  12111. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12112. EXPECT_EQ("ws", uc.scheme);
  12113. EXPECT_EQ("echo.example.com", uc.host);
  12114. EXPECT_EQ("8080", uc.port);
  12115. EXPECT_EQ("/ws", uc.path);
  12116. }
  12117. {
  12118. detail::UrlComponents uc;
  12119. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12120. EXPECT_EQ("wss", uc.scheme);
  12121. EXPECT_EQ("echo.example.com", uc.host);
  12122. EXPECT_TRUE(uc.port.empty());
  12123. EXPECT_EQ("/ws", uc.path);
  12124. }
  12125. }
  12126. TEST(ParseUrlTest, QueryOnly) {
  12127. detail::UrlComponents uc;
  12128. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12129. EXPECT_TRUE(uc.host.empty());
  12130. EXPECT_TRUE(uc.path.empty());
  12131. EXPECT_EQ("?q=1&r=2", uc.query);
  12132. }
  12133. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12134. detail::UrlComponents uc;
  12135. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12136. EXPECT_TRUE(uc.scheme.empty());
  12137. EXPECT_EQ("example.com", uc.host);
  12138. EXPECT_EQ("443", uc.port);
  12139. EXPECT_EQ("/path", uc.path);
  12140. }
  12141. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12142. // If ipv6 regex working, regex match codepath is taken.
  12143. // else port will default to 80 in Client impl
  12144. int clientImplMagicPort = 80;
  12145. int port = 4321;
  12146. // above ports must be different to avoid false negative
  12147. EXPECT_NE(clientImplMagicPort, port);
  12148. std::string ipV6TestURL = "http://[ff06::c3]";
  12149. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12150. CLIENT_PRIVATE_KEY_FILE);
  12151. EXPECT_EQ(cli.port(), port);
  12152. }
  12153. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12154. auto file_path = "./www/dir/index.html";
  12155. auto dir_path = "./www/dir";
  12156. detail::FileStat stat_file(file_path);
  12157. EXPECT_TRUE(stat_file.is_file());
  12158. EXPECT_FALSE(stat_file.is_dir());
  12159. detail::FileStat stat_dir(dir_path);
  12160. EXPECT_FALSE(stat_dir.is_file());
  12161. EXPECT_TRUE(stat_dir.is_dir());
  12162. }
  12163. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12164. // IPv4 with default HTTP port (80)
  12165. EXPECT_EQ("example.com",
  12166. detail::make_host_and_port_string("example.com", 80, false));
  12167. // IPv4 with default HTTPS port (443)
  12168. EXPECT_EQ("example.com",
  12169. detail::make_host_and_port_string("example.com", 443, true));
  12170. // IPv4 with non-default HTTP port
  12171. EXPECT_EQ("example.com:8080",
  12172. detail::make_host_and_port_string("example.com", 8080, false));
  12173. // IPv4 with non-default HTTPS port
  12174. EXPECT_EQ("example.com:8443",
  12175. detail::make_host_and_port_string("example.com", 8443, true));
  12176. // IPv6 with default HTTP port (80)
  12177. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12178. // IPv6 with default HTTPS port (443)
  12179. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12180. // IPv6 with non-default HTTP port
  12181. EXPECT_EQ("[::1]:8080",
  12182. detail::make_host_and_port_string("::1", 8080, false));
  12183. // IPv6 with non-default HTTPS port
  12184. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12185. // IPv6 full address with default port
  12186. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12187. detail::make_host_and_port_string(
  12188. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12189. // IPv6 full address with non-default port
  12190. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12191. detail::make_host_and_port_string(
  12192. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12193. // IPv6 localhost with non-default port
  12194. EXPECT_EQ("[::1]:3000",
  12195. detail::make_host_and_port_string("::1", 3000, false));
  12196. // IPv6 with zone ID (link-local address) with default port
  12197. EXPECT_EQ("[fe80::1%eth0]",
  12198. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12199. // IPv6 with zone ID (link-local address) with non-default port
  12200. EXPECT_EQ("[fe80::1%eth0]:8080",
  12201. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12202. // Edge case: Port 443 with is_ssl=false (should add port)
  12203. EXPECT_EQ("example.com:443",
  12204. detail::make_host_and_port_string("example.com", 443, false));
  12205. // Edge case: Port 80 with is_ssl=true (should add port)
  12206. EXPECT_EQ("example.com:80",
  12207. detail::make_host_and_port_string("example.com", 80, true));
  12208. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12209. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12210. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12211. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12212. // Security fix: Already bracketed IPv6 should not get double brackets
  12213. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12214. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12215. EXPECT_EQ("[::1]:8080",
  12216. detail::make_host_and_port_string("[::1]", 8080, false));
  12217. EXPECT_EQ("[2001:db8::1]:8080",
  12218. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12219. EXPECT_EQ("[fe80::1%eth0]",
  12220. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12221. EXPECT_EQ("[fe80::1%eth0]:8080",
  12222. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12223. // Edge case: Empty host (should return as-is)
  12224. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12225. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12226. // This is a known limitation but shouldn't crash
  12227. EXPECT_EQ("[host:name]",
  12228. detail::make_host_and_port_string("host:name", 80, false));
  12229. // Port number edge cases (no validation, but should not crash)
  12230. EXPECT_EQ("example.com:0",
  12231. detail::make_host_and_port_string("example.com", 0, false));
  12232. EXPECT_EQ("example.com:-1",
  12233. detail::make_host_and_port_string("example.com", -1, false));
  12234. EXPECT_EQ("example.com:65535",
  12235. detail::make_host_and_port_string("example.com", 65535, false));
  12236. EXPECT_EQ("example.com:65536",
  12237. detail::make_host_and_port_string("example.com", 65536, false));
  12238. }
  12239. #ifdef CPPHTTPLIB_SSL_ENABLED
  12240. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12241. httplib::SSLClient cli("roblox.com", 443);
  12242. cli.set_follow_location(true);
  12243. auto res = cli.Get("/");
  12244. ASSERT_TRUE(res);
  12245. EXPECT_EQ(StatusCode::OK_200, res->status);
  12246. }
  12247. #endif
  12248. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12249. Server svr;
  12250. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12251. EXPECT_EQ(res.status, 400);
  12252. });
  12253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12254. auto se = detail::scope_exit([&] {
  12255. svr.stop();
  12256. thread.join();
  12257. ASSERT_FALSE(svr.is_running());
  12258. });
  12259. svr.wait_until_ready();
  12260. Client cli(HOST, PORT);
  12261. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12262. }
  12263. TEST(InvalidHeaderCharsTest, is_field_name) {
  12264. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12265. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12266. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12267. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12268. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12269. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12270. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12271. EXPECT_FALSE(detail::fields::is_field_name(""));
  12272. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12273. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12274. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12275. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12276. }
  12277. TEST(InvalidHeaderCharsTest, is_field_value) {
  12278. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12279. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12280. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12281. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12282. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12283. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12284. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12285. EXPECT_TRUE(detail::fields::is_field_value(""));
  12286. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12287. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12288. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12289. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12290. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12291. }
  12292. TEST(InvalidHeaderCharsTest, OnServer) {
  12293. Server svr;
  12294. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12295. std::string header = "Not Set";
  12296. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12297. res.set_header(header, "value");
  12298. res.set_content("Page Content Page Content", "text/plain");
  12299. });
  12300. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12301. std::string header = "Not Set";
  12302. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12303. res.set_header("X-Test", header);
  12304. res.set_content("Page Content Page Content", "text/plain");
  12305. });
  12306. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12307. auto se = detail::scope_exit([&] {
  12308. svr.stop();
  12309. thread.join();
  12310. ASSERT_FALSE(svr.is_running());
  12311. });
  12312. svr.wait_until_ready();
  12313. Client cli(HOST, PORT);
  12314. {
  12315. auto res = cli.Get(
  12316. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12317. ASSERT_TRUE(res);
  12318. EXPECT_EQ("Page Content Page Content", res->body);
  12319. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12320. }
  12321. {
  12322. auto res = cli.Get(
  12323. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12324. ASSERT_TRUE(res);
  12325. EXPECT_EQ("Page Content Page Content", res->body);
  12326. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12327. }
  12328. }
  12329. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12330. auto handled = false;
  12331. Server svr;
  12332. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12333. thread t = thread([&] { svr.listen(HOST, PORT); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. t.join();
  12337. ASSERT_FALSE(svr.is_running());
  12338. ASSERT_FALSE(handled);
  12339. });
  12340. svr.wait_until_ready();
  12341. auto req = "POST /test HTTP/1.1\r\n"
  12342. "Content-Length: x\r\n"
  12343. "\r\n";
  12344. std::string response;
  12345. ASSERT_TRUE(send_request(1, req, &response));
  12346. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12347. response.substr(0, response.find("\r\n")));
  12348. }
  12349. #ifndef _WIN32
  12350. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12351. static constexpr char reject[] = "Unauthorized";
  12352. static constexpr char accept[] = "Upload accepted";
  12353. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12354. Server svr;
  12355. svr.set_expect_100_continue_handler(
  12356. [](const Request & /*req*/, Response &res) {
  12357. res.status = StatusCode::Unauthorized_401;
  12358. res.set_content(reject, "text/plain");
  12359. return res.status;
  12360. });
  12361. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12362. res.set_content(accept, "text/plain");
  12363. });
  12364. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12365. auto se = detail::scope_exit([&] {
  12366. svr.stop();
  12367. thread.join();
  12368. ASSERT_FALSE(svr.is_running());
  12369. });
  12370. svr.wait_until_ready();
  12371. {
  12372. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12373. curl_easy_init(), &curl_easy_cleanup};
  12374. ASSERT_NE(curl, nullptr);
  12375. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12376. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12377. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12378. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12379. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12380. &curl_slist_free_all};
  12381. ASSERT_NE(list, nullptr);
  12382. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12383. struct read_data {
  12384. size_t read_size;
  12385. size_t total_size;
  12386. } data = {0, total_size};
  12387. using read_callback_t =
  12388. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12389. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12390. void *userdata) -> size_t {
  12391. read_data *d = (read_data *)userdata;
  12392. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12393. std::fill_n(ptr, size * nmemb, 'A');
  12394. d->read_size += size * nmemb;
  12395. return size * nmemb;
  12396. };
  12397. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12398. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12399. std::vector<char> buffer;
  12400. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12401. using write_callback_t =
  12402. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12403. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12404. void *userdata) -> size_t {
  12405. std::vector<char> *buf = (std::vector<char> *)userdata;
  12406. buf->reserve(buf->size() + size * nmemb + 1);
  12407. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12408. return size * nmemb;
  12409. };
  12410. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12411. {
  12412. const auto res = curl_easy_perform(curl.get());
  12413. ASSERT_EQ(res, CURLE_OK);
  12414. }
  12415. {
  12416. auto response_code = long{};
  12417. const auto res =
  12418. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12419. ASSERT_EQ(res, CURLE_OK);
  12420. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12421. }
  12422. {
  12423. auto dl = curl_off_t{};
  12424. const auto res =
  12425. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12426. ASSERT_EQ(res, CURLE_OK);
  12427. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12428. }
  12429. {
  12430. buffer.push_back('\0');
  12431. ASSERT_STRCASEEQ(buffer.data(), reject);
  12432. }
  12433. }
  12434. }
  12435. #endif
  12436. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12437. // Regression test for #2458.
  12438. //
  12439. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12440. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12441. // ticket can make the client socket spuriously readable during the
  12442. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12443. // the client withholds the body and then blocks reading a response that never
  12444. // comes, failing with `Failed to read connection`.
  12445. //
  12446. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12447. // within the timeout. This raw OpenSSL server deliberately never sends
  12448. // `100 Continue`; the client must still deliver the body and receive 200.
  12449. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12450. signal(SIGPIPE, SIG_IGN);
  12451. const auto port = PORT + 4;
  12452. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12453. ASSERT_NE(srv, INVALID_SOCKET);
  12454. int opt = 1;
  12455. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12456. sockaddr_in addr{};
  12457. addr.sin_family = AF_INET;
  12458. addr.sin_port = htons(static_cast<uint16_t>(port));
  12459. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12460. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12461. ASSERT_EQ(0, ::listen(srv, 1));
  12462. std::atomic<size_t> server_body_bytes{0};
  12463. auto server_thread = std::thread([&] {
  12464. sockaddr_in cli_addr{};
  12465. socklen_t cli_len = sizeof(cli_addr);
  12466. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12467. if (cli == INVALID_SOCKET) { return; }
  12468. // Bound the lifetime of the server side so a buggy client (which never
  12469. // sends the body) cannot make this thread block forever on join.
  12470. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12471. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12472. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12473. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12474. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12475. SSL *ssl = SSL_new(ctx);
  12476. SSL_set_fd(ssl, static_cast<int>(cli));
  12477. if (SSL_accept(ssl) > 0) {
  12478. // Read the request headers. Reading here also flushes the TLS 1.3
  12479. // session tickets to the client. Deliberately do NOT send
  12480. // `100 Continue`.
  12481. std::string buf;
  12482. char tmp[1024];
  12483. while (buf.find("\r\n\r\n") == std::string::npos) {
  12484. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12485. if (n <= 0) { break; }
  12486. buf.append(tmp, static_cast<size_t>(n));
  12487. }
  12488. // A correct client sends the body now; count what arrives.
  12489. auto pos = buf.find("\r\n\r\n");
  12490. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12491. while (body < 4096) {
  12492. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12493. if (n <= 0) { break; }
  12494. body += static_cast<size_t>(n);
  12495. }
  12496. server_body_bytes = body;
  12497. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12498. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12499. SSL_shutdown(ssl);
  12500. }
  12501. SSL_free(ssl);
  12502. detail::close_socket(cli);
  12503. SSL_CTX_free(ctx);
  12504. });
  12505. auto se = detail::scope_exit([&] {
  12506. server_thread.join();
  12507. detail::close_socket(srv);
  12508. });
  12509. SSLClient cli("127.0.0.1", port);
  12510. cli.enable_server_certificate_verification(false);
  12511. cli.set_connection_timeout(5, 0);
  12512. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12513. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12514. std::string body(4096, 'A');
  12515. auto res = cli.Put("/api/test", body, "application/json");
  12516. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12517. EXPECT_EQ(StatusCode::OK_200, res->status);
  12518. EXPECT_EQ(body.size(), server_body_bytes.load());
  12519. }
  12520. #endif
  12521. template <typename S, typename C>
  12522. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12523. svr.Get("/stream", [&](const Request &, Response &res) {
  12524. auto data = new std::string("01234567890123456789");
  12525. res.set_content_provider(
  12526. data->size(), "text/plain",
  12527. [&, data](size_t offset, size_t length, DataSink &sink) {
  12528. const size_t DATA_CHUNK_SIZE = 4;
  12529. const auto &d = *data;
  12530. std::this_thread::sleep_for(std::chrono::seconds(1));
  12531. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12532. return true;
  12533. },
  12534. [data](bool success) {
  12535. EXPECT_FALSE(success);
  12536. delete data;
  12537. });
  12538. });
  12539. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12540. auto i = new size_t(0);
  12541. res.set_content_provider(
  12542. "text/plain",
  12543. [i](size_t, DataSink &sink) {
  12544. if (*i < 5) {
  12545. std::this_thread::sleep_for(std::chrono::seconds(1));
  12546. sink.write("abcd", 4);
  12547. (*i)++;
  12548. } else {
  12549. sink.done();
  12550. }
  12551. return true;
  12552. },
  12553. [i](bool success) {
  12554. EXPECT_FALSE(success);
  12555. delete i;
  12556. });
  12557. });
  12558. svr.Get("/chunked", [&](const Request &, Response &res) {
  12559. auto i = new size_t(0);
  12560. res.set_chunked_content_provider(
  12561. "text/plain",
  12562. [i](size_t, DataSink &sink) {
  12563. if (*i < 5) {
  12564. std::this_thread::sleep_for(std::chrono::seconds(1));
  12565. sink.os << "abcd";
  12566. (*i)++;
  12567. } else {
  12568. sink.done();
  12569. }
  12570. return true;
  12571. },
  12572. [i](bool success) {
  12573. EXPECT_FALSE(success);
  12574. delete i;
  12575. });
  12576. });
  12577. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12578. auto se = detail::scope_exit([&] {
  12579. svr.stop();
  12580. listen_thread.join();
  12581. ASSERT_FALSE(svr.is_running());
  12582. });
  12583. svr.wait_until_ready();
  12584. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12585. {
  12586. auto start = std::chrono::steady_clock::now();
  12587. auto res = cli.Get("/stream");
  12588. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12589. std::chrono::steady_clock::now() - start)
  12590. .count();
  12591. ASSERT_FALSE(res);
  12592. EXPECT_EQ(Error::Read, res.error());
  12593. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12594. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12595. }
  12596. {
  12597. auto start = std::chrono::steady_clock::now();
  12598. auto res = cli.Get("/stream_without_length");
  12599. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12600. std::chrono::steady_clock::now() - start)
  12601. .count();
  12602. ASSERT_FALSE(res);
  12603. EXPECT_EQ(Error::Read, res.error());
  12604. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12605. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12606. }
  12607. {
  12608. auto start = std::chrono::steady_clock::now();
  12609. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12610. EXPECT_EQ("abcd", string(data, data_length));
  12611. return true;
  12612. });
  12613. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12614. std::chrono::steady_clock::now() - start)
  12615. .count();
  12616. ASSERT_FALSE(res);
  12617. EXPECT_EQ(Error::Read, res.error());
  12618. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12619. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12620. }
  12621. }
  12622. TEST(MaxTimeoutTest, ContentStream) {
  12623. time_t timeout = 2000;
  12624. time_t threshold = 200;
  12625. Server svr;
  12626. Client cli("localhost", PORT);
  12627. max_timeout_test(svr, cli, timeout, threshold);
  12628. }
  12629. #ifdef CPPHTTPLIB_SSL_ENABLED
  12630. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12631. time_t timeout = 2000;
  12632. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12634. SSLClient cli("localhost", PORT);
  12635. cli.enable_server_certificate_verification(false);
  12636. max_timeout_test(svr, cli, timeout, threshold);
  12637. }
  12638. #endif
  12639. class EventDispatcher {
  12640. public:
  12641. EventDispatcher() {}
  12642. bool wait_event(DataSink *sink) {
  12643. unique_lock<mutex> lk(m_);
  12644. int id = id_;
  12645. // Wait with timeout to prevent hanging if client disconnects
  12646. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12647. [&] { return cid_ == id; })) {
  12648. return false; // Timeout occurred
  12649. }
  12650. sink->write(message_.data(), message_.size());
  12651. return true;
  12652. }
  12653. void send_event(const string &message) {
  12654. lock_guard<mutex> lk(m_);
  12655. cid_ = id_++;
  12656. message_ = message;
  12657. cv_.notify_all();
  12658. }
  12659. private:
  12660. mutex m_;
  12661. condition_variable cv_;
  12662. atomic_int id_{0};
  12663. atomic_int cid_{-1};
  12664. string message_;
  12665. };
  12666. TEST(ClientInThreadTest, Issue2068) {
  12667. EventDispatcher ed;
  12668. Server svr;
  12669. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12670. res.set_chunked_content_provider("text/event-stream",
  12671. [&](size_t /*offset*/, DataSink &sink) {
  12672. return ed.wait_event(&sink);
  12673. });
  12674. });
  12675. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12676. svr.wait_until_ready();
  12677. thread event_thread([&] {
  12678. int id = 0;
  12679. while (svr.is_running()) {
  12680. this_thread::sleep_for(chrono::milliseconds(500));
  12681. std::stringstream ss;
  12682. ss << "data: " << id << "\n\n";
  12683. ed.send_event(ss.str());
  12684. id++;
  12685. }
  12686. });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop();
  12689. listen_thread.join();
  12690. event_thread.join();
  12691. ASSERT_FALSE(svr.is_running());
  12692. });
  12693. {
  12694. auto client = detail::make_unique<Client>(HOST, PORT);
  12695. client->set_read_timeout(std::chrono::minutes(10));
  12696. std::atomic<bool> stop{false};
  12697. std::thread t([&] {
  12698. client->Get("/event1",
  12699. [&](const char *, size_t) -> bool { return !stop; });
  12700. });
  12701. std::this_thread::sleep_for(std::chrono::seconds(2));
  12702. stop = true;
  12703. client->stop();
  12704. t.join();
  12705. // Reset client after thread has finished
  12706. client.reset();
  12707. }
  12708. }
  12709. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12710. auto handled = false;
  12711. Server svr;
  12712. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12713. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12714. auto se = detail::scope_exit([&] {
  12715. svr.stop();
  12716. t.join();
  12717. ASSERT_FALSE(svr.is_running());
  12718. ASSERT_FALSE(handled);
  12719. });
  12720. svr.wait_until_ready();
  12721. // Two Content-Length headers with different values — must be rejected
  12722. auto req = "POST /test HTTP/1.1\r\n"
  12723. "Content-Length: 5\r\n"
  12724. "Content-Length: 10\r\n"
  12725. "\r\n"
  12726. "hello";
  12727. std::string response;
  12728. ASSERT_TRUE(send_request(1, req, &response));
  12729. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12730. response.substr(0, response.find("\r\n")));
  12731. }
  12732. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12733. auto handled = false;
  12734. Server svr;
  12735. svr.Post("/test", [&](const Request &, Response &res) {
  12736. handled = true;
  12737. res.set_content("ok", "text/plain");
  12738. });
  12739. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12740. auto se = detail::scope_exit([&] {
  12741. svr.stop();
  12742. t.join();
  12743. ASSERT_FALSE(svr.is_running());
  12744. ASSERT_TRUE(handled);
  12745. });
  12746. svr.wait_until_ready();
  12747. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12748. auto req = "POST /test HTTP/1.1\r\n"
  12749. "Content-Length: 5\r\n"
  12750. "Content-Length: 5\r\n"
  12751. "\r\n"
  12752. "hello";
  12753. std::string response;
  12754. ASSERT_TRUE(send_request(1, req, &response));
  12755. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12756. }
  12757. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12758. Server svr;
  12759. svr.Get("/", [](const Request &req, Response &res) {
  12760. EXPECT_EQ(2U, req.trailers.size());
  12761. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12762. // Denied
  12763. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12764. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12765. // Accepted
  12766. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12767. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12768. EXPECT_TRUE(req.has_trailer("X-World"));
  12769. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12770. res.set_content("ok", "text/plain");
  12771. });
  12772. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12773. auto se = detail::scope_exit([&] {
  12774. svr.stop();
  12775. t.join();
  12776. ASSERT_FALSE(svr.is_running());
  12777. });
  12778. svr.wait_until_ready();
  12779. const std::string req = "GET / HTTP/1.1\r\n"
  12780. "Transfer-Encoding: chunked\r\n"
  12781. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12782. "\r\n"
  12783. "0\r\n"
  12784. "Content-Length: 10\r\n"
  12785. "Host: internal.local\r\n"
  12786. "Content-Type: malicious/content\r\n"
  12787. "Cookie: any\r\n"
  12788. "Set-Cookie: any\r\n"
  12789. "X-Forwarded-For: attacker.com\r\n"
  12790. "X-Real-Ip: 1.1.1.1\r\n"
  12791. "X-Hello: hello\r\n"
  12792. "X-World: world\r\n"
  12793. "\r\n";
  12794. std::string res;
  12795. ASSERT_TRUE(send_request(1, req, &res));
  12796. }
  12797. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12798. Server svr;
  12799. std::string observed_remote_addr;
  12800. std::string observed_xff;
  12801. svr.Get("/ip", [&](const Request &req, Response &res) {
  12802. observed_remote_addr = req.remote_addr;
  12803. observed_xff = req.get_header_value("X-Forwarded-For");
  12804. res.set_content("ok", "text/plain");
  12805. });
  12806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12807. auto se = detail::scope_exit([&] {
  12808. svr.stop();
  12809. t.join();
  12810. ASSERT_FALSE(svr.is_running());
  12811. });
  12812. svr.wait_until_ready();
  12813. Client cli(HOST, PORT);
  12814. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12815. ASSERT_TRUE(res);
  12816. EXPECT_EQ(StatusCode::OK_200, res->status);
  12817. EXPECT_EQ(observed_xff, "203.0.113.66");
  12818. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12819. observed_remote_addr == "127.0.0.1");
  12820. }
  12821. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12822. Server svr;
  12823. svr.set_trusted_proxies({"203.0.113.66"});
  12824. std::string observed_remote_addr;
  12825. std::string observed_xff;
  12826. svr.Get("/ip", [&](const Request &req, Response &res) {
  12827. observed_remote_addr = req.remote_addr;
  12828. observed_xff = req.get_header_value("X-Forwarded-For");
  12829. res.set_content("ok", "text/plain");
  12830. });
  12831. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12832. auto se = detail::scope_exit([&] {
  12833. svr.stop();
  12834. t.join();
  12835. ASSERT_FALSE(svr.is_running());
  12836. });
  12837. svr.wait_until_ready();
  12838. Client cli(HOST, PORT);
  12839. auto res = cli.Get("/ip");
  12840. ASSERT_TRUE(res);
  12841. EXPECT_EQ(StatusCode::OK_200, res->status);
  12842. EXPECT_EQ(observed_xff, "");
  12843. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12844. observed_remote_addr == "127.0.0.1");
  12845. }
  12846. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12847. Server svr;
  12848. svr.set_trusted_proxies({"203.0.113.66"});
  12849. std::string observed_remote_addr;
  12850. std::string observed_xff;
  12851. svr.Get("/ip", [&](const Request &req, Response &res) {
  12852. observed_remote_addr = req.remote_addr;
  12853. observed_xff = req.get_header_value("X-Forwarded-For");
  12854. res.set_content("ok", "text/plain");
  12855. });
  12856. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12857. auto se = detail::scope_exit([&] {
  12858. svr.stop();
  12859. t.join();
  12860. ASSERT_FALSE(svr.is_running());
  12861. });
  12862. svr.wait_until_ready();
  12863. Client cli(HOST, PORT);
  12864. auto res = cli.Get(
  12865. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12866. ASSERT_TRUE(res);
  12867. EXPECT_EQ(StatusCode::OK_200, res->status);
  12868. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12869. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12870. }
  12871. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12872. Server svr;
  12873. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12874. std::string observed_remote_addr;
  12875. std::string observed_xff;
  12876. svr.Get("/ip", [&](const Request &req, Response &res) {
  12877. observed_remote_addr = req.remote_addr;
  12878. observed_xff = req.get_header_value("X-Forwarded-For");
  12879. res.set_content("ok", "text/plain");
  12880. });
  12881. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12882. auto se = detail::scope_exit([&] {
  12883. svr.stop();
  12884. t.join();
  12885. ASSERT_FALSE(svr.is_running());
  12886. });
  12887. svr.wait_until_ready();
  12888. Client cli(HOST, PORT);
  12889. auto res = cli.Get(
  12890. "/ip",
  12891. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12892. ASSERT_TRUE(res);
  12893. EXPECT_EQ(StatusCode::OK_200, res->status);
  12894. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12895. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12896. }
  12897. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12898. Server svr;
  12899. svr.set_trusted_proxies({"192.0.2.45"});
  12900. std::string observed_remote_addr;
  12901. std::string observed_xff;
  12902. svr.Get("/ip", [&](const Request &req, Response &res) {
  12903. observed_remote_addr = req.remote_addr;
  12904. observed_xff = req.get_header_value("X-Forwarded-For");
  12905. res.set_content("ok", "text/plain");
  12906. });
  12907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12908. auto se = detail::scope_exit([&] {
  12909. svr.stop();
  12910. t.join();
  12911. ASSERT_FALSE(svr.is_running());
  12912. });
  12913. svr.wait_until_ready();
  12914. Client cli(HOST, PORT);
  12915. auto res = cli.Get(
  12916. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12917. ASSERT_TRUE(res);
  12918. EXPECT_EQ(StatusCode::OK_200, res->status);
  12919. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12920. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12921. }
  12922. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12923. Server svr;
  12924. svr.set_trusted_proxies({"192.0.2.45"});
  12925. std::string observed_remote_addr;
  12926. std::string observed_xff;
  12927. svr.Get("/ip", [&](const Request &req, Response &res) {
  12928. observed_remote_addr = req.remote_addr;
  12929. observed_xff = req.get_header_value("X-Forwarded-For");
  12930. res.set_content("ok", "text/plain");
  12931. });
  12932. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12933. auto se = detail::scope_exit([&] {
  12934. svr.stop();
  12935. t.join();
  12936. ASSERT_FALSE(svr.is_running());
  12937. });
  12938. svr.wait_until_ready();
  12939. Client cli(HOST, PORT);
  12940. auto res = cli.Get(
  12941. "/ip",
  12942. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12943. ASSERT_TRUE(res);
  12944. EXPECT_EQ(StatusCode::OK_200, res->status);
  12945. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12946. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12947. }
  12948. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12949. Server svr;
  12950. svr.set_trusted_proxies({"192.0.2.45"});
  12951. std::string observed_remote_addr;
  12952. std::string observed_xff;
  12953. svr.Get("/ip", [&](const Request &req, Response &res) {
  12954. observed_remote_addr = req.remote_addr;
  12955. observed_xff = req.get_header_value("X-Forwarded-For");
  12956. res.set_content("ok", "text/plain");
  12957. });
  12958. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12959. auto se = detail::scope_exit([&] {
  12960. svr.stop();
  12961. t.join();
  12962. ASSERT_FALSE(svr.is_running());
  12963. });
  12964. svr.wait_until_ready();
  12965. std::string raw_req =
  12966. "GET /ip HTTP/1.1\r\n"
  12967. "Host: localhost\r\n"
  12968. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12969. "Connection: close\r\n"
  12970. "\r\n";
  12971. std::string out;
  12972. ASSERT_TRUE(send_request(5, raw_req, &out));
  12973. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12974. // Header parser trims surrounding whitespace of the header value
  12975. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12976. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12977. }
  12978. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12979. // crash the server (it used to call front() on an empty vector inside
  12980. // get_client_ip). The connection-level remote address must be retained instead.
  12981. static void run_malformed_xff_test(const std::string &xff_value) {
  12982. Server svr;
  12983. svr.set_trusted_proxies({"192.0.2.45"});
  12984. std::string observed_remote_addr;
  12985. svr.Get("/ip", [&](const Request &req, Response &res) {
  12986. observed_remote_addr = req.remote_addr;
  12987. res.set_content("ok", "text/plain");
  12988. });
  12989. int port = 0;
  12990. thread t = thread([&]() {
  12991. port = svr.bind_to_any_port(HOST);
  12992. svr.listen_after_bind();
  12993. });
  12994. auto se = detail::scope_exit([&] {
  12995. svr.stop();
  12996. t.join();
  12997. ASSERT_FALSE(svr.is_running());
  12998. });
  12999. svr.wait_until_ready();
  13000. Client cli(HOST, port);
  13001. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13002. ASSERT_TRUE(res);
  13003. EXPECT_EQ(StatusCode::OK_200, res->status);
  13004. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13005. observed_remote_addr == "127.0.0.1");
  13006. }
  13007. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13008. run_malformed_xff_test("");
  13009. }
  13010. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13011. run_malformed_xff_test(",");
  13012. }
  13013. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13014. run_malformed_xff_test(", , ,");
  13015. }
  13016. #ifndef _WIN32
  13017. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13018. Server svr;
  13019. svr.Post("/post", [&](const Request &req, Response &res) {
  13020. res.set_content(req.body, "text/plain");
  13021. });
  13022. svr.Put("/put", [&](const Request &req, Response &res) {
  13023. res.set_content(req.body, "text/plain");
  13024. });
  13025. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13026. res.set_content(req.body, "text/plain");
  13027. });
  13028. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13029. res.set_content(req.body, "text/plain");
  13030. });
  13031. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13032. auto se = detail::scope_exit([&] {
  13033. svr.stop();
  13034. t.join();
  13035. ASSERT_FALSE(svr.is_running());
  13036. });
  13037. svr.wait_until_ready();
  13038. std::string resp;
  13039. // POST without Content-Length
  13040. ASSERT_TRUE(send_request(5,
  13041. "POST /post HTTP/1.1\r\n"
  13042. "Host: localhost\r\n"
  13043. "Connection: close\r\n"
  13044. "\r\n",
  13045. &resp));
  13046. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13047. // PUT without Content-Length
  13048. resp.clear();
  13049. ASSERT_TRUE(send_request(5,
  13050. "PUT /put HTTP/1.1\r\n"
  13051. "Host: localhost\r\n"
  13052. "Connection: close\r\n"
  13053. "\r\n",
  13054. &resp));
  13055. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13056. // PATCH without Content-Length
  13057. resp.clear();
  13058. ASSERT_TRUE(send_request(5,
  13059. "PATCH /patch HTTP/1.1\r\n"
  13060. "Host: localhost\r\n"
  13061. "Connection: close\r\n"
  13062. "\r\n",
  13063. &resp));
  13064. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13065. // DELETE without Content-Length
  13066. resp.clear();
  13067. ASSERT_TRUE(send_request(5,
  13068. "DELETE /delete HTTP/1.1\r\n"
  13069. "Host: localhost\r\n"
  13070. "Connection: close\r\n"
  13071. "\r\n",
  13072. &resp));
  13073. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13074. }
  13075. #endif
  13076. //==============================================================================
  13077. // open_stream() Tests
  13078. //==============================================================================
  13079. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13080. std::string result;
  13081. char buf[8192];
  13082. ssize_t n;
  13083. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13084. result.append(buf, static_cast<size_t>(n));
  13085. }
  13086. return result;
  13087. }
  13088. // Mock stream for unit tests
  13089. class MockStream : public Stream {
  13090. public:
  13091. std::string data;
  13092. size_t pos = 0;
  13093. ssize_t error_after = -1; // -1 = no error
  13094. explicit MockStream(const std::string &d, ssize_t err = -1)
  13095. : data(d), error_after(err) {}
  13096. bool is_readable() const override { return true; }
  13097. bool wait_readable() const override { return true; }
  13098. bool wait_writable() const override { return true; }
  13099. ssize_t read(char *ptr, size_t size) override {
  13100. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13101. if (pos >= data.size()) return 0;
  13102. size_t limit =
  13103. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13104. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13105. std::memcpy(ptr, data.data() + pos, to_read);
  13106. pos += to_read;
  13107. return static_cast<ssize_t>(to_read);
  13108. }
  13109. ssize_t write(const char *, size_t) override { return -1; }
  13110. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13111. ip = "127.0.0.1";
  13112. port = 0;
  13113. }
  13114. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13115. ip = "127.0.0.1";
  13116. port = 0;
  13117. }
  13118. socket_t socket() const override { return INVALID_SOCKET; }
  13119. time_t duration() const override { return 0; }
  13120. };
  13121. TEST(StreamHandleTest, Basic) {
  13122. ClientImpl::StreamHandle handle;
  13123. EXPECT_FALSE(handle.is_valid());
  13124. handle.response = detail::make_unique<Response>();
  13125. handle.error = Error::Connection;
  13126. EXPECT_FALSE(handle.is_valid());
  13127. handle.error = Error::Success;
  13128. EXPECT_TRUE(handle.is_valid());
  13129. }
  13130. TEST(BodyReaderTest, Basic) {
  13131. MockStream stream("Hello, World!");
  13132. detail::BodyReader reader;
  13133. reader.stream = &stream;
  13134. reader.content_length = 13;
  13135. char buf[32];
  13136. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13137. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13138. EXPECT_TRUE(reader.eof);
  13139. }
  13140. TEST(BodyReaderTest, NoStream) {
  13141. detail::BodyReader reader;
  13142. char buf[32];
  13143. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13144. EXPECT_EQ(Error::Connection, reader.last_error);
  13145. }
  13146. TEST(BodyReaderTest, Error) {
  13147. MockStream stream("Hello, World!", 5);
  13148. detail::BodyReader reader;
  13149. reader.stream = &stream;
  13150. reader.content_length = 13;
  13151. char buf[32];
  13152. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13153. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13154. EXPECT_EQ(Error::Read, reader.last_error);
  13155. }
  13156. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13157. // Mock-based StreamHandle tests relying on private internals are removed.
  13158. class OpenStreamTest : public ::testing::Test {
  13159. protected:
  13160. void SetUp() override {
  13161. svr_.Get("/hello", [](const Request &, Response &res) {
  13162. res.set_content("Hello World!", "text/plain");
  13163. });
  13164. svr_.Get("/large", [](const Request &, Response &res) {
  13165. res.set_content(std::string(10000, 'X'), "text/plain");
  13166. });
  13167. svr_.Get("/chunked", [](const Request &, Response &res) {
  13168. res.set_chunked_content_provider("text/plain",
  13169. [](size_t offset, DataSink &sink) {
  13170. if (offset < 15) {
  13171. sink.write("chunk", 5);
  13172. return true;
  13173. }
  13174. sink.done();
  13175. return true;
  13176. });
  13177. });
  13178. svr_.Get("/compressible", [](const Request &, Response &res) {
  13179. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13180. DataSink &sink) {
  13181. if (offset < 100 * 1024) {
  13182. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13183. sink.write(chunk.data(), chunk.size());
  13184. return true;
  13185. }
  13186. sink.done();
  13187. return true;
  13188. });
  13189. });
  13190. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13191. [](const Request & /*req*/, Response &res) {
  13192. auto i = new int(0);
  13193. res.set_header("Trailer", "Content-Length, X-Allowed");
  13194. res.set_chunked_content_provider(
  13195. "text/plain",
  13196. [i](size_t /*offset*/, DataSink &sink) {
  13197. switch (*i) {
  13198. case 0: sink.os << "123"; break;
  13199. case 1: sink.os << "456"; break;
  13200. case 2: sink.os << "789"; break;
  13201. case 3: {
  13202. sink.done_with_trailer(
  13203. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13204. } break;
  13205. }
  13206. (*i)++;
  13207. return true;
  13208. },
  13209. [i](bool success) {
  13210. EXPECT_TRUE(success);
  13211. delete i;
  13212. });
  13213. });
  13214. // Echo headers endpoint for header-related tests
  13215. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13216. std::string body;
  13217. for (const auto &h : req.headers) {
  13218. body.append(h.first);
  13219. body.push_back(':');
  13220. body.append(h.second);
  13221. body.push_back('\n');
  13222. }
  13223. res.set_content(body, "text/plain");
  13224. });
  13225. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13226. std::string body;
  13227. for (const auto &h : req.headers) {
  13228. body.append(h.first);
  13229. body.push_back(':');
  13230. body.append(h.second);
  13231. body.push_back('\n');
  13232. }
  13233. res.set_content(body, "text/plain");
  13234. });
  13235. port_ = svr_.bind_to_any_port("127.0.0.1");
  13236. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13237. svr_.wait_until_ready();
  13238. }
  13239. void TearDown() override {
  13240. svr_.stop();
  13241. if (thread_.joinable()) thread_.join();
  13242. }
  13243. Server svr_;
  13244. std::thread thread_;
  13245. int port_ = 0;
  13246. };
  13247. TEST_F(OpenStreamTest, Basic) {
  13248. Client cli("127.0.0.1", port_);
  13249. auto handle = cli.open_stream("GET", "/hello");
  13250. EXPECT_TRUE(handle.is_valid());
  13251. EXPECT_EQ("Hello World!", read_all(handle));
  13252. }
  13253. TEST_F(OpenStreamTest, SmallBuffer) {
  13254. Client cli("127.0.0.1", port_);
  13255. auto handle = cli.open_stream("GET", "/hello");
  13256. std::string result;
  13257. char buf[4];
  13258. ssize_t n;
  13259. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13260. result.append(buf, static_cast<size_t>(n));
  13261. EXPECT_EQ("Hello World!", result);
  13262. }
  13263. TEST_F(OpenStreamTest, DefaultHeaders) {
  13264. Client cli("127.0.0.1", port_);
  13265. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13266. {
  13267. auto handle = cli.open_stream("GET", "/echo-headers");
  13268. ASSERT_TRUE(handle.is_valid());
  13269. auto body = read_all(handle);
  13270. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13271. std::string::npos);
  13272. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13273. std::string::npos);
  13274. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13275. }
  13276. // open_stream POST with body and no explicit content_type should NOT add
  13277. // text/plain Content-Type (behavior differs from non-streaming path), but
  13278. // should include Content-Length
  13279. {
  13280. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13281. ASSERT_TRUE(handle.is_valid());
  13282. auto body = read_all(handle);
  13283. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13284. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13285. }
  13286. // open_stream POST with explicit Content-Type should preserve it
  13287. {
  13288. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13289. {{"Content-Type", "application/custom"}},
  13290. "{}", "application/custom");
  13291. ASSERT_TRUE(handle.is_valid());
  13292. auto body = read_all(handle);
  13293. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13294. }
  13295. // User-specified User-Agent must not be overwritten for stream API
  13296. {
  13297. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13298. {{"User-Agent", "MyAgent/1.2"}});
  13299. ASSERT_TRUE(handle.is_valid());
  13300. auto body = read_all(handle);
  13301. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13302. }
  13303. }
  13304. TEST_F(OpenStreamTest, Large) {
  13305. Client cli("127.0.0.1", port_);
  13306. auto handle = cli.open_stream("GET", "/large");
  13307. EXPECT_EQ(10000u, read_all(handle).size());
  13308. }
  13309. TEST_F(OpenStreamTest, ConnectionError) {
  13310. Client cli("127.0.0.1", 9999);
  13311. auto handle = cli.open_stream("GET", "/hello");
  13312. EXPECT_FALSE(handle.is_valid());
  13313. }
  13314. TEST_F(OpenStreamTest, Chunked) {
  13315. Client cli("127.0.0.1", port_);
  13316. auto handle = cli.open_stream("GET", "/chunked");
  13317. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13318. "Transfer-Encoding") == "chunked");
  13319. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13320. }
  13321. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13322. Client cli("127.0.0.1", port_);
  13323. auto handle =
  13324. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13325. ASSERT_TRUE(handle.is_valid());
  13326. // Consume body to allow trailers to be received/parsed
  13327. auto body = read_all(handle);
  13328. // Explicitly parse trailers (ensure trailers are available for assertion)
  13329. handle.parse_trailers_if_needed();
  13330. EXPECT_EQ(std::string("123456789"), body);
  13331. // The response should include a Trailer header declaring both names
  13332. ASSERT_TRUE(handle.response);
  13333. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13334. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13335. handle.response->get_header_value("Trailer"));
  13336. // Prohibited trailer must not be present
  13337. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13338. // Allowed trailer should be present
  13339. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13340. EXPECT_EQ(std::string("yes"),
  13341. handle.response->get_trailer_value("X-Allowed"));
  13342. // Verify trailers are NOT present as regular headers
  13343. EXPECT_EQ(std::string(""),
  13344. handle.response->get_header_value("Content-Length"));
  13345. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13346. }
  13347. static std::thread serve_single_response(std::promise<int> &port_promise,
  13348. const std::string &response) {
  13349. return std::thread([&port_promise, response] {
  13350. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13351. default_socket_options(srv);
  13352. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13353. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13354. sockaddr_in addr{};
  13355. addr.sin_family = AF_INET;
  13356. addr.sin_port = htons(0); // Let OS assign a free port
  13357. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13358. int opt = 1;
  13359. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13360. #ifdef _WIN32
  13361. reinterpret_cast<const char *>(&opt),
  13362. #else
  13363. &opt,
  13364. #endif
  13365. sizeof(opt));
  13366. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13367. ::listen(srv, 1) != 0) {
  13368. port_promise.set_value(-1);
  13369. detail::close_socket(srv);
  13370. return;
  13371. }
  13372. socklen_t addr_len = sizeof(addr);
  13373. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13374. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13375. sockaddr_in cli_addr{};
  13376. socklen_t cli_len = sizeof(cli_addr);
  13377. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13378. if (cli != INVALID_SOCKET) {
  13379. // Read the complete HTTP request (until the blank line that terminates
  13380. // headers) before sending the response. If the server closes the socket
  13381. // while the client's request data is still unread in the kernel receive
  13382. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13383. // connection on both sides: it discards the client's receive buffer
  13384. // (which already holds our response) and causes any in-progress write on
  13385. // the client to fail with ECONNRESET. Reading all request data first
  13386. // ensures close() emits a graceful FIN.
  13387. {
  13388. char rbuf[256];
  13389. std::string req;
  13390. while (req.find("\r\n\r\n") == std::string::npos) {
  13391. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13392. if (n <= 0) { break; }
  13393. req.append(rbuf, static_cast<size_t>(n));
  13394. }
  13395. }
  13396. ::send(cli,
  13397. #ifdef _WIN32
  13398. static_cast<const char *>(response.c_str()),
  13399. static_cast<int>(response.size()),
  13400. #else
  13401. response.c_str(), response.size(),
  13402. #endif
  13403. 0);
  13404. detail::close_socket(cli);
  13405. }
  13406. detail::close_socket(srv);
  13407. });
  13408. }
  13409. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13410. #ifndef _WIN32
  13411. signal(SIGPIPE, SIG_IGN);
  13412. #endif
  13413. std::promise<int> port_promise;
  13414. auto port_future = port_promise.get_future();
  13415. auto server_thread =
  13416. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13417. "Content-Type: text/plain\r\n"
  13418. "Content-Length: not-a-number\r\n"
  13419. "Connection: close\r\n"
  13420. "\r\n"
  13421. "hello");
  13422. auto port = port_future.get();
  13423. ASSERT_GT(port, 0);
  13424. Client cli("127.0.0.1", port);
  13425. auto handle = cli.open_stream("GET", "/");
  13426. EXPECT_FALSE(handle.is_valid());
  13427. server_thread.join();
  13428. }
  13429. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13430. #ifndef _WIN32
  13431. signal(SIGPIPE, SIG_IGN);
  13432. #endif
  13433. std::promise<int> port_promise;
  13434. auto port_future = port_promise.get_future();
  13435. auto server_thread = serve_single_response(
  13436. port_promise, "HTTP/1.1 200 OK\r\n"
  13437. "Content-Type: text/plain\r\n"
  13438. "Content-Length: 99999999999999999999999999\r\n"
  13439. "Connection: close\r\n"
  13440. "\r\n"
  13441. "hello");
  13442. auto port = port_future.get();
  13443. ASSERT_GT(port, 0);
  13444. // Historically std::stoull would throw std::out_of_range here and crash
  13445. // the process, then parsing silently clamped to a bogus framing length and
  13446. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13447. // so the stream fails to open, matching the not-a-number case above. The
  13448. // process still must NOT terminate.
  13449. Client cli("127.0.0.1", port);
  13450. auto handle = cli.open_stream("GET", "/");
  13451. EXPECT_FALSE(handle.is_valid());
  13452. server_thread.join();
  13453. }
  13454. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13455. TEST_F(OpenStreamTest, Gzip) {
  13456. Client cli("127.0.0.1", port_);
  13457. auto handle = cli.open_stream("GET", "/compressible", {},
  13458. {{"Accept-Encoding", "gzip"}});
  13459. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13460. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13461. }
  13462. #endif
  13463. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13464. TEST_F(OpenStreamTest, Brotli) {
  13465. Client cli("127.0.0.1", port_);
  13466. auto handle =
  13467. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13468. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13469. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13470. }
  13471. #endif
  13472. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13473. TEST_F(OpenStreamTest, Zstd) {
  13474. Client cli("127.0.0.1", port_);
  13475. auto handle = cli.open_stream("GET", "/compressible", {},
  13476. {{"Accept-Encoding", "zstd"}});
  13477. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13478. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13479. }
  13480. #endif
  13481. #ifdef CPPHTTPLIB_SSL_ENABLED
  13482. class SSLOpenStreamTest : public ::testing::Test {
  13483. protected:
  13484. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13485. void SetUp() override {
  13486. svr_.Get("/hello", [](const Request &, Response &res) {
  13487. res.set_content("Hello SSL World!", "text/plain");
  13488. });
  13489. svr_.Get("/chunked", [](const Request &, Response &res) {
  13490. res.set_chunked_content_provider("text/plain",
  13491. [](size_t offset, DataSink &sink) {
  13492. if (offset < 15) {
  13493. sink.write("chunk", 5);
  13494. return true;
  13495. }
  13496. sink.done();
  13497. return true;
  13498. });
  13499. });
  13500. svr_.Post("/echo", [](const Request &req, Response &res) {
  13501. res.set_content(req.body, req.get_header_value("Content-Type"));
  13502. });
  13503. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13504. std::string body = req.body;
  13505. res.set_chunked_content_provider(
  13506. "text/plain", [body](size_t offset, DataSink &sink) {
  13507. if (offset < body.size()) {
  13508. sink.write(body.data() + offset, body.size() - offset);
  13509. }
  13510. sink.done();
  13511. return true;
  13512. });
  13513. });
  13514. port_ = svr_.bind_to_any_port("127.0.0.1");
  13515. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13516. svr_.wait_until_ready();
  13517. }
  13518. void TearDown() override {
  13519. svr_.stop();
  13520. if (thread_.joinable()) thread_.join();
  13521. }
  13522. SSLServer svr_;
  13523. std::thread thread_;
  13524. int port_ = 0;
  13525. };
  13526. TEST_F(SSLOpenStreamTest, Basic) {
  13527. SSLClient cli("127.0.0.1", port_);
  13528. cli.enable_server_certificate_verification(false);
  13529. auto handle = cli.open_stream("GET", "/hello");
  13530. ASSERT_TRUE(handle.is_valid());
  13531. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13532. }
  13533. TEST_F(SSLOpenStreamTest, Chunked) {
  13534. SSLClient cli("127.0.0.1", port_);
  13535. cli.enable_server_certificate_verification(false);
  13536. auto handle = cli.open_stream("GET", "/chunked");
  13537. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13538. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13539. "Transfer-Encoding") == "chunked");
  13540. auto body = read_all(handle);
  13541. EXPECT_EQ("chunkchunkchunk", body);
  13542. }
  13543. TEST_F(SSLOpenStreamTest, Post) {
  13544. SSLClient cli("127.0.0.1", port_);
  13545. cli.enable_server_certificate_verification(false);
  13546. auto handle =
  13547. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13548. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13549. EXPECT_EQ(200, handle.response->status);
  13550. auto body = read_all(handle);
  13551. EXPECT_EQ("Hello SSL POST", body);
  13552. }
  13553. TEST_F(SSLOpenStreamTest, PostChunked) {
  13554. SSLClient cli("127.0.0.1", port_);
  13555. cli.enable_server_certificate_verification(false);
  13556. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13557. "Chunked SSL Data", "text/plain");
  13558. ASSERT_TRUE(handle.is_valid());
  13559. EXPECT_EQ(200, handle.response->status);
  13560. auto body = read_all(handle);
  13561. EXPECT_EQ("Chunked SSL Data", body);
  13562. }
  13563. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13564. // Content-Length is terminated by the server closing the connection. When the
  13565. // SSL peer sends a close_notify after the body, the client must treat it as a
  13566. // clean EOF and return a successful response rather than an error.
  13567. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13569. ASSERT_TRUE(svr.is_valid());
  13570. svr.set_keep_alive_max_count(1);
  13571. const std::string expected_body = "Hello from connection-close response!";
  13572. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13573. res.set_content_provider("text/plain",
  13574. [&](size_t offset, DataSink &sink) -> bool {
  13575. if (offset < expected_body.size()) {
  13576. sink.write(expected_body.data() + offset,
  13577. expected_body.size() - offset);
  13578. }
  13579. sink.done();
  13580. return true;
  13581. });
  13582. });
  13583. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13584. auto se = detail::scope_exit([&] {
  13585. svr.stop();
  13586. listen_thread.join();
  13587. ASSERT_FALSE(svr.is_running());
  13588. });
  13589. svr.wait_until_ready();
  13590. SSLClient cli(HOST, PORT);
  13591. cli.enable_server_certificate_verification(false);
  13592. auto res = cli.Get("/no-content-length");
  13593. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13594. EXPECT_EQ(StatusCode::OK_200, res->status);
  13595. EXPECT_EQ(expected_body, res->body);
  13596. }
  13597. #endif // CPPHTTPLIB_SSL_ENABLED
  13598. //==============================================================================
  13599. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13600. // results for various scenarios.
  13601. //==============================================================================
  13602. TEST(ParityTest, GetVsOpenStream) {
  13603. Server svr;
  13604. const std::string path = "/parity";
  13605. const std::string content = "Parity test content: hello world";
  13606. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13607. res.set_content(content, "text/plain");
  13608. });
  13609. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13610. auto se = detail::scope_exit([&] {
  13611. svr.stop();
  13612. t.join();
  13613. ASSERT_FALSE(svr.is_running());
  13614. });
  13615. svr.wait_until_ready();
  13616. Client cli(HOST, PORT);
  13617. // Non-stream path
  13618. auto r1 = cli.Get(path);
  13619. ASSERT_TRUE(r1);
  13620. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13621. // Stream path
  13622. auto h = cli.open_stream("GET", path);
  13623. ASSERT_TRUE(h.is_valid());
  13624. EXPECT_EQ(r1->body, read_all(h));
  13625. }
  13626. // Helper to compress data with provided compressor type T
  13627. template <typename Compressor>
  13628. static std::string compress_payload_for_parity(const std::string &in) {
  13629. std::string out;
  13630. Compressor compressor;
  13631. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13632. [&](const char *data, size_t n) {
  13633. out.append(data, n);
  13634. return true;
  13635. });
  13636. EXPECT_TRUE(ok);
  13637. return out;
  13638. }
  13639. // Helper function for compression parity tests
  13640. template <typename Compressor>
  13641. static void test_compression_parity(const std::string &original,
  13642. const std::string &path,
  13643. const std::string &encoding) {
  13644. const std::string compressed =
  13645. compress_payload_for_parity<Compressor>(original);
  13646. Server svr;
  13647. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13648. res.set_content(compressed, "application/octet-stream");
  13649. res.set_header("Content-Encoding", encoding);
  13650. });
  13651. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13652. auto se = detail::scope_exit([&] {
  13653. svr.stop();
  13654. t.join();
  13655. ASSERT_FALSE(svr.is_running());
  13656. });
  13657. svr.wait_until_ready();
  13658. Client cli(HOST, PORT);
  13659. // Non-streaming
  13660. {
  13661. auto res = cli.Get(path);
  13662. ASSERT_TRUE(res);
  13663. EXPECT_EQ(StatusCode::OK_200, res->status);
  13664. EXPECT_EQ(original, res->body);
  13665. }
  13666. // Streaming
  13667. {
  13668. auto h = cli.open_stream("GET", path);
  13669. ASSERT_TRUE(h.is_valid());
  13670. EXPECT_EQ(original, read_all(h));
  13671. }
  13672. }
  13673. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13674. TEST(ParityTest, Gzip) {
  13675. test_compression_parity<detail::gzip_compressor>(
  13676. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13677. }
  13678. #endif
  13679. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13680. TEST(ParityTest, Brotli) {
  13681. test_compression_parity<detail::brotli_compressor>(
  13682. "Hello, brotli parity test payload", "/parity-br", "br");
  13683. }
  13684. #endif
  13685. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13686. TEST(ParityTest, Zstd) {
  13687. test_compression_parity<detail::zstd_compressor>(
  13688. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13689. }
  13690. #endif
  13691. //==============================================================================
  13692. // New Stream API Tests
  13693. //==============================================================================
  13694. inline std::string read_body(httplib::stream::Result &result) {
  13695. std::string body;
  13696. while (result.next()) {
  13697. body.append(result.data(), result.size());
  13698. }
  13699. return body;
  13700. }
  13701. TEST(ClientConnectionTest, Basic) {
  13702. httplib::ClientConnection conn;
  13703. EXPECT_FALSE(conn.is_open());
  13704. conn.sock = 1;
  13705. EXPECT_TRUE(conn.is_open());
  13706. httplib::ClientConnection conn2(std::move(conn));
  13707. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13708. conn2.sock = INVALID_SOCKET;
  13709. }
  13710. // Unified test server for all stream::* tests
  13711. class StreamApiTest : public ::testing::Test {
  13712. protected:
  13713. void SetUp() override {
  13714. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13715. res.set_content("Hello World!", "text/plain");
  13716. });
  13717. svr_.Get("/echo-params",
  13718. [](const httplib::Request &req, httplib::Response &res) {
  13719. std::string r;
  13720. for (const auto &p : req.params) {
  13721. if (!r.empty()) r += "&";
  13722. r += p.first + "=" + p.second;
  13723. }
  13724. res.set_content(r, "text/plain");
  13725. });
  13726. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13727. res.set_content(req.body, req.get_header_value("Content-Type"));
  13728. });
  13729. svr_.Post("/echo-headers",
  13730. [](const httplib::Request &req, httplib::Response &res) {
  13731. std::string r;
  13732. for (const auto &h : req.headers)
  13733. r += h.first + ": " + h.second + "\n";
  13734. res.set_content(r, "text/plain");
  13735. });
  13736. svr_.Post("/echo-params",
  13737. [](const httplib::Request &req, httplib::Response &res) {
  13738. std::string r = "params:";
  13739. for (const auto &p : req.params)
  13740. r += p.first + "=" + p.second + ";";
  13741. res.set_content(r + " body:" + req.body, "text/plain");
  13742. });
  13743. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13744. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13745. });
  13746. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13747. res.set_content("PUT:" + req.body, "text/plain");
  13748. });
  13749. svr_.Patch("/echo",
  13750. [](const httplib::Request &req, httplib::Response &res) {
  13751. res.set_content("PATCH:" + req.body, "text/plain");
  13752. });
  13753. svr_.Delete(
  13754. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13755. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13756. "text/plain");
  13757. });
  13758. svr_.Get("/head-test",
  13759. [](const httplib::Request &, httplib::Response &res) {
  13760. res.set_content("body for HEAD", "text/plain");
  13761. });
  13762. svr_.Options("/options",
  13763. [](const httplib::Request &, httplib::Response &res) {
  13764. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13765. });
  13766. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13767. svr_.wait_until_ready();
  13768. }
  13769. void TearDown() override {
  13770. svr_.stop();
  13771. if (thread_.joinable()) thread_.join();
  13772. }
  13773. httplib::Server svr_;
  13774. std::thread thread_;
  13775. };
  13776. // stream::Get tests
  13777. TEST_F(StreamApiTest, GetBasic) {
  13778. httplib::Client cli(HOST, PORT);
  13779. auto result = httplib::stream::Get(cli, "/hello");
  13780. ASSERT_TRUE(result.is_valid());
  13781. EXPECT_EQ(200, result.status());
  13782. EXPECT_EQ("Hello World!", read_body(result));
  13783. }
  13784. TEST_F(StreamApiTest, GetWithParams) {
  13785. httplib::Client cli(HOST, PORT);
  13786. httplib::Params params{{"foo", "bar"}};
  13787. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13788. ASSERT_TRUE(result.is_valid());
  13789. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13790. }
  13791. TEST_F(StreamApiTest, GetConnectionError) {
  13792. httplib::Client cli(HOST, 9999);
  13793. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13794. }
  13795. TEST_F(StreamApiTest, Get404) {
  13796. httplib::Client cli(HOST, PORT);
  13797. auto result = httplib::stream::Get(cli, "/nonexistent");
  13798. EXPECT_TRUE(result.is_valid());
  13799. EXPECT_EQ(404, result.status());
  13800. }
  13801. // stream::Post tests
  13802. TEST_F(StreamApiTest, PostBasic) {
  13803. httplib::Client cli(HOST, PORT);
  13804. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13805. "application/json");
  13806. ASSERT_TRUE(result.is_valid());
  13807. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13808. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13809. }
  13810. TEST_F(StreamApiTest, PostWithHeaders) {
  13811. httplib::Client cli(HOST, PORT);
  13812. httplib::Headers headers{{"X-Custom", "value"}};
  13813. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13814. "text/plain");
  13815. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13816. }
  13817. TEST_F(StreamApiTest, PostWithParams) {
  13818. httplib::Client cli(HOST, PORT);
  13819. httplib::Params params{{"k", "v"}};
  13820. auto result =
  13821. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13822. auto body = read_body(result);
  13823. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13824. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13825. }
  13826. TEST_F(StreamApiTest, PostLarge) {
  13827. httplib::Client cli(HOST, PORT);
  13828. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13829. size_t total = 0;
  13830. while (result.next()) {
  13831. total += result.size();
  13832. }
  13833. EXPECT_EQ(100u * 1024u, total);
  13834. }
  13835. // stream::Put/Patch tests
  13836. TEST_F(StreamApiTest, PutAndPatch) {
  13837. httplib::Client cli(HOST, PORT);
  13838. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13839. EXPECT_EQ("PUT:test", read_body(put));
  13840. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13841. EXPECT_EQ("PATCH:test", read_body(patch));
  13842. }
  13843. // stream::Delete tests
  13844. TEST_F(StreamApiTest, Delete) {
  13845. httplib::Client cli(HOST, PORT);
  13846. auto del1 = httplib::stream::Delete(cli, "/resource");
  13847. EXPECT_EQ("Deleted", read_body(del1));
  13848. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13849. EXPECT_EQ("Deleted:data", read_body(del2));
  13850. }
  13851. // stream::Head/Options tests
  13852. TEST_F(StreamApiTest, HeadAndOptions) {
  13853. httplib::Client cli(HOST, PORT);
  13854. auto head = httplib::stream::Head(cli, "/head-test");
  13855. EXPECT_TRUE(head.is_valid());
  13856. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13857. auto opts = httplib::stream::Options(cli, "/options");
  13858. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13859. }
  13860. // SSL stream::* tests
  13861. #ifdef CPPHTTPLIB_SSL_ENABLED
  13862. class SSLStreamApiTest : public ::testing::Test {
  13863. protected:
  13864. void SetUp() override {
  13865. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13866. res.set_content("Hello SSL!", "text/plain");
  13867. });
  13868. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13869. res.set_content(req.body, "text/plain");
  13870. });
  13871. port_ = svr_.bind_to_any_port("127.0.0.1");
  13872. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13873. svr_.wait_until_ready();
  13874. }
  13875. void TearDown() override {
  13876. svr_.stop();
  13877. if (thread_.joinable()) thread_.join();
  13878. }
  13879. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13880. std::thread thread_;
  13881. int port_ = 0;
  13882. };
  13883. TEST_F(SSLStreamApiTest, GetAndPost) {
  13884. httplib::SSLClient cli("127.0.0.1", port_);
  13885. cli.enable_server_certificate_verification(false);
  13886. auto get = httplib::stream::Get(cli, "/hello");
  13887. EXPECT_EQ("Hello SSL!", read_body(get));
  13888. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13889. EXPECT_EQ("test", read_body(post));
  13890. }
  13891. #endif
  13892. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13893. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13894. // BodyReader
  13895. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13896. // Test that read timeout during streaming is detected
  13897. // Use a large content-length response where server delays mid-stream
  13898. Server svr;
  13899. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13900. // Send a large response with delay in the middle
  13901. res.set_content_provider(
  13902. 1000, // content_length
  13903. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13904. if (offset < 100) {
  13905. // Send first 100 bytes immediately
  13906. std::string data(100, 'A');
  13907. sink.write(data.c_str(), data.size());
  13908. return true;
  13909. }
  13910. // Then delay longer than client timeout
  13911. std::this_thread::sleep_for(std::chrono::seconds(3));
  13912. std::string data(900, 'B');
  13913. sink.write(data.c_str(), data.size());
  13914. return true;
  13915. });
  13916. });
  13917. auto port = 8091;
  13918. std::thread t([&]() { svr.listen("localhost", port); });
  13919. svr.wait_until_ready();
  13920. Client cli("localhost", port);
  13921. cli.set_read_timeout(1, 0); // 1 second timeout
  13922. auto handle = cli.open_stream("GET", "/slow-stream");
  13923. ASSERT_TRUE(handle.is_valid());
  13924. char buf[256];
  13925. ssize_t total = 0;
  13926. ssize_t n;
  13927. bool got_error = false;
  13928. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13929. total += n;
  13930. }
  13931. if (n < 0) {
  13932. got_error = true;
  13933. // Should be timeout or read error
  13934. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13935. handle.get_read_error() == Error::Read)
  13936. << "Actual error: " << to_string(handle.get_read_error());
  13937. }
  13938. // Either we got an error, or we got less data than expected
  13939. EXPECT_TRUE(got_error || total < 1000)
  13940. << "Expected timeout but got all " << total << " bytes";
  13941. svr.stop();
  13942. t.join();
  13943. }
  13944. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13945. // Test connection closed detection via BodyReader
  13946. Server svr;
  13947. std::atomic<bool> close_now{false};
  13948. svr.Get("/will-close", [&](const Request &, Response &res) {
  13949. res.set_content_provider(
  13950. 10000, // Large content_length that we won't fully send
  13951. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13952. if (offset < 100) {
  13953. std::string data(100, 'X');
  13954. sink.write(data.c_str(), data.size());
  13955. return true;
  13956. }
  13957. // Wait for signal then abort
  13958. while (!close_now) {
  13959. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13960. }
  13961. return false; // Abort - server will close connection
  13962. });
  13963. });
  13964. auto port = 8092;
  13965. std::thread t([&]() { svr.listen("localhost", port); });
  13966. svr.wait_until_ready();
  13967. Client cli("localhost", port);
  13968. auto handle = cli.open_stream("GET", "/will-close");
  13969. ASSERT_TRUE(handle.is_valid());
  13970. char buf[256];
  13971. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13972. EXPECT_GT(n, 0) << "First read should succeed";
  13973. // Signal server to close
  13974. close_now = true;
  13975. // Keep reading until error or EOF
  13976. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13977. // Keep reading
  13978. }
  13979. // Should get an error since content_length wasn't satisfied
  13980. if (n < 0) {
  13981. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13982. handle.get_read_error() == Error::Read)
  13983. << "Actual error: " << to_string(handle.get_read_error());
  13984. }
  13985. svr.stop();
  13986. t.join();
  13987. }
  13988. #ifdef CPPHTTPLIB_SSL_ENABLED
  13989. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13990. // Test that read timeout during SSL streaming is detected
  13991. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13992. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13993. res.set_content_provider(
  13994. 1000, "text/plain",
  13995. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13996. if (offset < 100) {
  13997. std::string data(100, 'A');
  13998. sink.write(data.c_str(), data.size());
  13999. return true;
  14000. }
  14001. std::this_thread::sleep_for(std::chrono::seconds(3));
  14002. std::string data(900, 'B');
  14003. sink.write(data.c_str(), data.size());
  14004. return true;
  14005. });
  14006. });
  14007. auto port = 8093;
  14008. std::thread t([&]() { svr.listen("localhost", port); });
  14009. svr.wait_until_ready();
  14010. SSLClient cli("localhost", port);
  14011. cli.enable_server_certificate_verification(false);
  14012. cli.set_read_timeout(1, 0); // 1 second timeout
  14013. auto handle = cli.open_stream("GET", "/slow-stream");
  14014. ASSERT_TRUE(handle.is_valid());
  14015. char buf[256];
  14016. ssize_t total = 0;
  14017. ssize_t n;
  14018. bool got_error = false;
  14019. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14020. total += n;
  14021. }
  14022. if (n < 0) {
  14023. got_error = true;
  14024. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14025. handle.get_read_error() == Error::Read)
  14026. << "Actual error: " << to_string(handle.get_read_error());
  14027. }
  14028. EXPECT_TRUE(got_error || total < 1000)
  14029. << "Expected timeout but got all " << total << " bytes";
  14030. svr.stop();
  14031. t.join();
  14032. }
  14033. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14034. // Test SSL connection closed detection
  14035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14036. std::atomic<bool> close_now{false};
  14037. svr.Get("/will-close", [&](const Request &, Response &res) {
  14038. res.set_content_provider(
  14039. 10000, "text/plain",
  14040. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14041. if (offset < 100) {
  14042. std::string data(100, 'X');
  14043. sink.write(data.c_str(), data.size());
  14044. return true;
  14045. }
  14046. while (!close_now) {
  14047. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14048. }
  14049. return false;
  14050. });
  14051. });
  14052. auto port = 8094;
  14053. std::thread t([&]() { svr.listen("localhost", port); });
  14054. svr.wait_until_ready();
  14055. SSLClient cli("localhost", port);
  14056. cli.enable_server_certificate_verification(false);
  14057. auto handle = cli.open_stream("GET", "/will-close");
  14058. ASSERT_TRUE(handle.is_valid());
  14059. char buf[256];
  14060. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14061. EXPECT_GT(n, 0);
  14062. // Signal server to close
  14063. close_now = true;
  14064. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14065. // Keep reading
  14066. }
  14067. if (n < 0) {
  14068. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14069. handle.get_read_error() == Error::Read)
  14070. << "Actual error: " << to_string(handle.get_read_error());
  14071. }
  14072. svr.stop();
  14073. t.join();
  14074. }
  14075. #endif
  14076. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14077. using namespace httplib;
  14078. // Create a test file
  14079. const char *fname = "etag_testfile.txt";
  14080. const char *content = "etag-content";
  14081. {
  14082. std::ofstream ofs(fname);
  14083. ofs << content;
  14084. ASSERT_TRUE(ofs.good());
  14085. }
  14086. Server svr;
  14087. svr.set_mount_point("/static", ".");
  14088. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14089. svr.wait_until_ready();
  14090. Client cli(HOST, PORT);
  14091. // First request: should get 200 with ETag header
  14092. auto res1 = cli.Get("/static/etag_testfile.txt");
  14093. ASSERT_TRUE(res1);
  14094. ASSERT_EQ(200, res1->status);
  14095. ASSERT_TRUE(res1->has_header("ETag"));
  14096. std::string etag = res1->get_header_value("ETag");
  14097. EXPECT_FALSE(etag.empty());
  14098. // Verify ETag format: W/"hex-hex"
  14099. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14100. EXPECT_EQ('W', etag[0]);
  14101. EXPECT_EQ('/', etag[1]);
  14102. EXPECT_EQ('"', etag[2]);
  14103. EXPECT_EQ('"', etag.back());
  14104. // Exact match: expect 304 Not Modified
  14105. Headers h2 = {{"If-None-Match", etag}};
  14106. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14107. ASSERT_TRUE(res2);
  14108. EXPECT_EQ(304, res2->status);
  14109. // Wildcard match: expect 304 Not Modified
  14110. Headers h3 = {{"If-None-Match", "*"}};
  14111. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14112. ASSERT_TRUE(res3);
  14113. EXPECT_EQ(304, res3->status);
  14114. // Non-matching ETag: expect 200
  14115. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14116. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14117. ASSERT_TRUE(res4);
  14118. EXPECT_EQ(200, res4->status);
  14119. // Multiple ETags with one matching: expect 304
  14120. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14121. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14122. ASSERT_TRUE(res5);
  14123. EXPECT_EQ(304, res5->status);
  14124. svr.stop();
  14125. t.join();
  14126. std::remove(fname);
  14127. }
  14128. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14129. using namespace httplib;
  14130. Server svr;
  14131. svr.set_mount_point("/static", ".");
  14132. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14133. svr.wait_until_ready();
  14134. Client cli(HOST, PORT);
  14135. // Send If-None-Match: * to a non-existent file
  14136. Headers h = {{"If-None-Match", "*"}};
  14137. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14138. ASSERT_TRUE(res);
  14139. EXPECT_EQ(404, res->status);
  14140. svr.stop();
  14141. t.join();
  14142. }
  14143. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14144. using namespace httplib;
  14145. // Create a test file
  14146. const char *fname = "etag_boundary_testfile.txt";
  14147. const char *content = "boundary-test";
  14148. {
  14149. std::ofstream ofs(fname);
  14150. ofs << content;
  14151. ASSERT_TRUE(ofs.good());
  14152. }
  14153. Server svr;
  14154. svr.set_mount_point("/static", ".");
  14155. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14156. svr.wait_until_ready();
  14157. Client cli(HOST, PORT);
  14158. // Get the actual ETag
  14159. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14160. ASSERT_TRUE(res1);
  14161. ASSERT_EQ(200, res1->status);
  14162. ASSERT_TRUE(res1->has_header("ETag"));
  14163. std::string etag = res1->get_header_value("ETag");
  14164. // Test 1: Very long ETag value (longer than actual ETag)
  14165. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14166. Headers h1 = {{"If-None-Match", "W/"
  14167. "\"very-long-etag-value-that-is-much-longer-"
  14168. "than-the-actual-etag-value\""}};
  14169. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14170. ASSERT_TRUE(res2);
  14171. EXPECT_EQ(200, res2->status); // Should not match
  14172. // Test 2: Long string followed by wildcard
  14173. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14174. // string)
  14175. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14176. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14177. ASSERT_TRUE(res3);
  14178. EXPECT_EQ(304, res3->status); // Should match on "*"
  14179. // Test 3: Wildcard followed by long string
  14180. // Should match on "*" immediately and return 304
  14181. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14182. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14183. ASSERT_TRUE(res4);
  14184. EXPECT_EQ(304, res4->status); // Should match on "*"
  14185. // Test 4: Multiple long non-matching values
  14186. // Should NOT match and return 200 (test that all comparisons are safe)
  14187. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14188. "W/\"second-long-non-matching-value\", "
  14189. "W/\"third-long-non-matching-value\""}};
  14190. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14191. ASSERT_TRUE(res5);
  14192. EXPECT_EQ(200, res5->status); // Should not match
  14193. // Test 5: Single character that is not "*" (edge case)
  14194. Headers h5 = {{"If-None-Match", "X"}};
  14195. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14196. ASSERT_TRUE(res6);
  14197. EXPECT_EQ(200, res6->status); // Should not match
  14198. svr.stop();
  14199. t.join();
  14200. std::remove(fname);
  14201. }
  14202. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14203. using namespace httplib;
  14204. // Create a test file
  14205. const char *fname = "ims_testfile.txt";
  14206. const char *content = "if-modified-since-test";
  14207. {
  14208. std::ofstream ofs(fname);
  14209. ofs << content;
  14210. ASSERT_TRUE(ofs.good());
  14211. }
  14212. Server svr;
  14213. svr.set_mount_point("/static", ".");
  14214. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14215. svr.wait_until_ready();
  14216. Client cli(HOST, PORT);
  14217. // First request: should get 200 with Last-Modified header
  14218. auto res1 = cli.Get("/static/ims_testfile.txt");
  14219. ASSERT_TRUE(res1);
  14220. ASSERT_EQ(200, res1->status);
  14221. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14222. std::string last_modified = res1->get_header_value("Last-Modified");
  14223. EXPECT_FALSE(last_modified.empty());
  14224. // If-Modified-Since with same time: expect 304
  14225. Headers h2 = {{"If-Modified-Since", last_modified}};
  14226. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14227. ASSERT_TRUE(res2);
  14228. EXPECT_EQ(304, res2->status);
  14229. // If-Modified-Since with future time: expect 304
  14230. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14231. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14232. ASSERT_TRUE(res3);
  14233. EXPECT_EQ(304, res3->status);
  14234. // If-Modified-Since with past time: expect 200
  14235. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14236. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14237. ASSERT_TRUE(res4);
  14238. EXPECT_EQ(200, res4->status);
  14239. // If-None-Match takes precedence over If-Modified-Since
  14240. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14241. ASSERT_TRUE(res1->has_header("ETag"));
  14242. std::string etag = res1->get_header_value("ETag");
  14243. Headers h5 = {{"If-None-Match", etag},
  14244. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14245. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14246. ASSERT_TRUE(res5);
  14247. EXPECT_EQ(304, res5->status);
  14248. svr.stop();
  14249. t.join();
  14250. std::remove(fname);
  14251. }
  14252. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14253. using namespace httplib;
  14254. Server svr;
  14255. // Endpoint that returns compressible content
  14256. svr.Get("/compressible", [](const Request &, Response &res) {
  14257. // Return a large enough body to trigger compression
  14258. std::string body(1000, 'a');
  14259. res.set_content(body, "text/plain");
  14260. });
  14261. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14262. svr.wait_until_ready();
  14263. Client cli(HOST, PORT);
  14264. // Request with gzip support: should get Vary header when compressed
  14265. cli.set_compress(true);
  14266. auto res1 = cli.Get("/compressible");
  14267. ASSERT_TRUE(res1);
  14268. EXPECT_EQ(200, res1->status);
  14269. // If Content-Encoding is set, Vary should also be set
  14270. if (res1->has_header("Content-Encoding")) {
  14271. EXPECT_TRUE(res1->has_header("Vary"));
  14272. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14273. }
  14274. // Request without Accept-Encoding header: should not have compression
  14275. Headers h_no_compress;
  14276. auto res2 = cli.Get("/compressible", h_no_compress);
  14277. ASSERT_TRUE(res2);
  14278. EXPECT_EQ(200, res2->status);
  14279. // Verify Vary header is present when compression is applied
  14280. // (the exact behavior depends on server configuration)
  14281. svr.stop();
  14282. t.join();
  14283. }
  14284. TEST(ETagTest, IfRangeWithETag) {
  14285. using namespace httplib;
  14286. // Create a test file with known content
  14287. const char *fname = "if_range_testfile.txt";
  14288. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14289. {
  14290. std::ofstream ofs(fname);
  14291. ofs << content;
  14292. ASSERT_TRUE(ofs.good());
  14293. }
  14294. Server svr;
  14295. svr.set_mount_point("/static", ".");
  14296. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14297. svr.wait_until_ready();
  14298. Client cli(HOST, PORT);
  14299. // First request: get ETag
  14300. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14301. ASSERT_TRUE(res1);
  14302. ASSERT_EQ(200, res1->status);
  14303. ASSERT_TRUE(res1->has_header("ETag"));
  14304. std::string etag = res1->get_header_value("ETag");
  14305. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14306. // Since our server generates weak ETags (W/"..."), If-Range with our
  14307. // ETag should NOT result in partial content - it should return full content.
  14308. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14309. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14310. ASSERT_TRUE(res2);
  14311. // Weak ETag in If-Range -> full content (200), not partial (206)
  14312. EXPECT_EQ(200, res2->status);
  14313. EXPECT_EQ(content, res2->body);
  14314. EXPECT_FALSE(res2->has_header("Content-Range"));
  14315. // Range request with non-matching If-Range (ETag): should get 200 (full
  14316. // content)
  14317. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14318. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14319. ASSERT_TRUE(res3);
  14320. EXPECT_EQ(200, res3->status);
  14321. EXPECT_EQ(content, res3->body);
  14322. EXPECT_FALSE(res3->has_header("Content-Range"));
  14323. // Range request with strong ETag (hypothetical - our server doesn't generate
  14324. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14325. // should return full content)
  14326. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14327. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14328. ASSERT_TRUE(res4);
  14329. EXPECT_EQ(200, res4->status);
  14330. EXPECT_EQ(content, res4->body);
  14331. EXPECT_FALSE(res4->has_header("Content-Range"));
  14332. svr.stop();
  14333. t.join();
  14334. std::remove(fname);
  14335. }
  14336. TEST(ETagTest, IfRangeWithDate) {
  14337. using namespace httplib;
  14338. // Create a test file
  14339. const char *fname = "if_range_date_testfile.txt";
  14340. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14341. {
  14342. std::ofstream ofs(fname);
  14343. ofs << content;
  14344. ASSERT_TRUE(ofs.good());
  14345. }
  14346. Server svr;
  14347. svr.set_mount_point("/static", ".");
  14348. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14349. svr.wait_until_ready();
  14350. Client cli(HOST, PORT);
  14351. // First request: get Last-Modified
  14352. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14353. ASSERT_TRUE(res1);
  14354. ASSERT_EQ(200, res1->status);
  14355. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14356. std::string last_modified = res1->get_header_value("Last-Modified");
  14357. // Range request with matching If-Range (date): should get 206
  14358. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14359. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14360. ASSERT_TRUE(res2);
  14361. EXPECT_EQ(206, res2->status);
  14362. EXPECT_EQ("FGHIJ", res2->body);
  14363. // Range request with old If-Range date: should get 200 (full content)
  14364. Headers h3 = {{"Range", "bytes=5-9"},
  14365. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14366. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14367. ASSERT_TRUE(res3);
  14368. EXPECT_EQ(200, res3->status);
  14369. EXPECT_EQ(content, res3->body);
  14370. // Range request with future If-Range date: should get 206
  14371. Headers h4 = {{"Range", "bytes=0-4"},
  14372. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14373. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14374. ASSERT_TRUE(res4);
  14375. EXPECT_EQ(206, res4->status);
  14376. EXPECT_EQ("ABCDE", res4->body);
  14377. svr.stop();
  14378. t.join();
  14379. std::remove(fname);
  14380. }
  14381. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14382. using namespace httplib;
  14383. const char *fname = "etag_malformed.txt";
  14384. const char *content = "malformed-etag";
  14385. {
  14386. std::ofstream ofs(fname);
  14387. ofs << content;
  14388. ASSERT_TRUE(ofs.good());
  14389. }
  14390. Server svr;
  14391. svr.set_mount_point("/static", ".");
  14392. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14393. svr.wait_until_ready();
  14394. Client cli(HOST, PORT);
  14395. // baseline: should get 200 and an ETag
  14396. auto res1 = cli.Get("/static/etag_malformed.txt");
  14397. ASSERT_TRUE(res1);
  14398. ASSERT_EQ(200, res1->status);
  14399. ASSERT_TRUE(res1->has_header("ETag"));
  14400. // Malformed ETag value (missing quotes) should be treated as non-matching
  14401. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14402. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14403. ASSERT_TRUE(res_bad);
  14404. EXPECT_EQ(200, res_bad->status);
  14405. // Whitespace-only header value should be considered invalid / non-matching
  14406. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14407. "Host: localhost\r\n"
  14408. "If-None-Match: \r\n"
  14409. "Connection: close\r\n"
  14410. "\r\n";
  14411. std::string out;
  14412. ASSERT_TRUE(send_request(5, raw_req, &out));
  14413. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14414. svr.stop();
  14415. t.join();
  14416. std::remove(fname);
  14417. }
  14418. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14419. using namespace httplib;
  14420. const char *fname = "ims_invalid_format.txt";
  14421. const char *content = "ims-bad-format";
  14422. {
  14423. std::ofstream ofs(fname);
  14424. ofs << content;
  14425. ASSERT_TRUE(ofs.good());
  14426. }
  14427. Server svr;
  14428. svr.set_mount_point("/static", ".");
  14429. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14430. svr.wait_until_ready();
  14431. Client cli(HOST, PORT);
  14432. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14433. ASSERT_TRUE(res1);
  14434. ASSERT_EQ(200, res1->status);
  14435. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14436. // If-Modified-Since with invalid format should not result in 304
  14437. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14438. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14439. ASSERT_TRUE(res_bad);
  14440. EXPECT_EQ(200, res_bad->status);
  14441. // If-Range with invalid date format should be treated as mismatch -> full
  14442. // content (200)
  14443. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14444. {"If-Range", "invalid-date"}};
  14445. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14446. ASSERT_TRUE(res_ifrange);
  14447. EXPECT_EQ(200, res_ifrange->status);
  14448. svr.stop();
  14449. t.join();
  14450. std::remove(fname);
  14451. }
  14452. TEST(ETagTest, IfRangeWithMalformedETag) {
  14453. using namespace httplib;
  14454. const char *fname = "ifrange_malformed.txt";
  14455. const std::string content = "0123456789";
  14456. {
  14457. std::ofstream ofs(fname);
  14458. ofs << content;
  14459. ASSERT_TRUE(ofs.good());
  14460. }
  14461. Server svr;
  14462. svr.set_mount_point("/static", ".");
  14463. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14464. svr.wait_until_ready();
  14465. Client cli(HOST, PORT);
  14466. // First request: get ETag
  14467. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14468. ASSERT_TRUE(res1);
  14469. ASSERT_EQ(200, res1->status);
  14470. ASSERT_TRUE(res1->has_header("ETag"));
  14471. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14472. // full content (200)
  14473. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14474. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14475. ASSERT_TRUE(res2);
  14476. EXPECT_EQ(200, res2->status);
  14477. EXPECT_EQ(content, res2->body);
  14478. svr.stop();
  14479. t.join();
  14480. std::remove(fname);
  14481. }
  14482. TEST(ETagTest, ExtremeLargeDateValues) {
  14483. using namespace httplib;
  14484. const char *fname = "ims_extreme_date.txt";
  14485. const char *content = "ims-extreme-date";
  14486. {
  14487. std::ofstream ofs(fname);
  14488. ofs << content;
  14489. ASSERT_TRUE(ofs.good());
  14490. }
  14491. Server svr;
  14492. svr.set_mount_point("/static", ".");
  14493. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14494. svr.wait_until_ready();
  14495. Client cli(HOST, PORT);
  14496. auto res1 = cli.Get(std::string("/static/") + fname);
  14497. ASSERT_TRUE(res1);
  14498. ASSERT_EQ(200, res1->status);
  14499. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14500. // Extremely large year that may overflow date parsing routines.
  14501. Headers h_large_date = {
  14502. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14503. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14504. ASSERT_TRUE(res_bad);
  14505. // Expect server to treat this as invalid/mismatch and return full content
  14506. EXPECT_EQ(200, res_bad->status);
  14507. // If-Range with extremely large date should be treated as mismatch -> full
  14508. // content (200)
  14509. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14510. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14511. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14512. ASSERT_TRUE(res_ifrange);
  14513. EXPECT_EQ(200, res_ifrange->status);
  14514. svr.stop();
  14515. t.join();
  14516. std::remove(fname);
  14517. }
  14518. TEST(ETagTest, NegativeFileModificationTime) {
  14519. using namespace httplib;
  14520. const char *fname = "ims_negative_mtime.txt";
  14521. const std::string content = "negative-mtime";
  14522. {
  14523. std::ofstream ofs(fname);
  14524. ofs << content;
  14525. ASSERT_TRUE(ofs.good());
  14526. }
  14527. // Try to set file mtime to a negative value. This may fail on some
  14528. // platforms/filesystems; if it fails, the test will still verify server
  14529. // behaves safely by performing a regular conditional request.
  14530. #if defined(__APPLE__) || defined(__linux__)
  14531. bool set_negative = false;
  14532. do {
  14533. struct timeval times[2];
  14534. // access time: now
  14535. times[0].tv_sec = time(nullptr);
  14536. times[0].tv_usec = 0;
  14537. // modification time: negative (e.g., -1)
  14538. times[1].tv_sec = -1;
  14539. times[1].tv_usec = 0;
  14540. if (utimes(fname, times) == 0) { set_negative = true; }
  14541. } while (0);
  14542. #else
  14543. bool set_negative = false;
  14544. #endif
  14545. Server svr;
  14546. svr.set_mount_point("/static", ".");
  14547. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14548. svr.wait_until_ready();
  14549. Client cli(HOST, PORT);
  14550. auto res1 = cli.Get(std::string("/static/") + fname);
  14551. ASSERT_TRUE(res1);
  14552. ASSERT_EQ(200, res1->status);
  14553. bool has_last_modified = res1->has_header("Last-Modified");
  14554. std::string last_modified;
  14555. if (has_last_modified) {
  14556. last_modified = res1->get_header_value("Last-Modified");
  14557. }
  14558. if (set_negative) {
  14559. // If we successfully set a negative mtime, ensure server returns a
  14560. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14561. // with an old date and ensure server handles it without crash.
  14562. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14563. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14564. ASSERT_TRUE(res2);
  14565. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14566. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14567. } else {
  14568. // Could not set negative mtime on this platform; fall back to verifying
  14569. // that normal invalid/malformed dates are treated safely (non-304).
  14570. Headers h_bad_date = {
  14571. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14572. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14573. ASSERT_TRUE(res_bad);
  14574. EXPECT_EQ(200, res_bad->status);
  14575. }
  14576. svr.stop();
  14577. t.join();
  14578. std::remove(fname);
  14579. }
  14580. //==============================================================================
  14581. // SSE Parsing Tests
  14582. //==============================================================================
  14583. class SSEParsingTest : public ::testing::Test {
  14584. protected:
  14585. // Test helper that mimics SSE parsing behavior
  14586. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14587. int &retry_ms) {
  14588. // Blank line signals end of event
  14589. if (line.empty() || line == "\r") { return true; }
  14590. // Lines starting with ':' are comments (ignored)
  14591. if (!line.empty() && line[0] == ':') { return false; }
  14592. // Find the colon separator
  14593. auto colon_pos = line.find(':');
  14594. if (colon_pos == std::string::npos) {
  14595. // Line with no colon is treated as field name with empty value
  14596. return false;
  14597. }
  14598. std::string field = line.substr(0, colon_pos);
  14599. std::string value;
  14600. // Value starts after colon, skip optional single space
  14601. if (colon_pos + 1 < line.size()) {
  14602. size_t value_start = colon_pos + 1;
  14603. if (line[value_start] == ' ') { value_start++; }
  14604. value = line.substr(value_start);
  14605. // Remove trailing \r if present
  14606. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14607. }
  14608. // Handle known fields
  14609. if (field == "event") {
  14610. msg.event = value;
  14611. } else if (field == "data") {
  14612. // Multiple data lines are concatenated with newlines
  14613. if (!msg.data.empty()) { msg.data += "\n"; }
  14614. msg.data += value;
  14615. } else if (field == "id") {
  14616. // Empty id is valid (clears the last event ID)
  14617. msg.id = value;
  14618. } else if (field == "retry") {
  14619. // Parse retry interval in milliseconds
  14620. {
  14621. int v = 0;
  14622. auto res =
  14623. detail::from_chars(value.data(), value.data() + value.size(), v);
  14624. if (res.ec == std::errc{}) { retry_ms = v; }
  14625. }
  14626. }
  14627. // Unknown fields are ignored per SSE spec
  14628. return false;
  14629. }
  14630. };
  14631. // Test: Single-line data
  14632. TEST_F(SSEParsingTest, SingleLineData) {
  14633. sse::SSEMessage msg;
  14634. int retry_ms = 3000;
  14635. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14636. EXPECT_EQ(msg.data, "hello");
  14637. EXPECT_EQ(msg.event, "message");
  14638. // Blank line ends event
  14639. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14640. }
  14641. // Test: Multi-line data
  14642. TEST_F(SSEParsingTest, MultiLineData) {
  14643. sse::SSEMessage msg;
  14644. int retry_ms = 3000;
  14645. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14646. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14647. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14648. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14649. }
  14650. // Test: Custom event types
  14651. TEST_F(SSEParsingTest, CustomEventType) {
  14652. sse::SSEMessage msg;
  14653. int retry_ms = 3000;
  14654. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14655. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14656. EXPECT_EQ(msg.event, "update");
  14657. EXPECT_EQ(msg.data, "payload");
  14658. }
  14659. // Test: Event ID handling
  14660. TEST_F(SSEParsingTest, EventIdHandling) {
  14661. sse::SSEMessage msg;
  14662. int retry_ms = 3000;
  14663. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14664. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14665. EXPECT_EQ(msg.id, "12345");
  14666. }
  14667. // Test: Empty event ID (clears last event ID)
  14668. TEST_F(SSEParsingTest, EmptyEventId) {
  14669. sse::SSEMessage msg;
  14670. msg.id = "previous";
  14671. int retry_ms = 3000;
  14672. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14673. EXPECT_EQ(msg.id, "");
  14674. }
  14675. // Test: Retry field parsing
  14676. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14677. sse::SSEMessage msg;
  14678. int retry_ms = 3000;
  14679. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14680. EXPECT_EQ(retry_ms, 5000);
  14681. }
  14682. // Test: Invalid retry value
  14683. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14684. sse::SSEMessage msg;
  14685. int retry_ms = 3000;
  14686. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14687. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14688. }
  14689. // Test: Comments (lines starting with :)
  14690. TEST_F(SSEParsingTest, CommentsIgnored) {
  14691. sse::SSEMessage msg;
  14692. int retry_ms = 3000;
  14693. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14694. EXPECT_EQ(msg.data, "");
  14695. EXPECT_EQ(msg.event, "message");
  14696. }
  14697. // Test: Colon in value
  14698. TEST_F(SSEParsingTest, ColonInValue) {
  14699. sse::SSEMessage msg;
  14700. int retry_ms = 3000;
  14701. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14702. EXPECT_EQ(msg.data, "hello:world:test");
  14703. }
  14704. // Test: Line with no colon (field name only)
  14705. TEST_F(SSEParsingTest, FieldNameOnly) {
  14706. sse::SSEMessage msg;
  14707. int retry_ms = 3000;
  14708. // According to SSE spec, this is treated as field name with empty value
  14709. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14710. // Since we don't recognize "data" without colon, data should be empty
  14711. EXPECT_EQ(msg.data, "");
  14712. }
  14713. // Test: Trailing \r handling
  14714. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14715. sse::SSEMessage msg;
  14716. int retry_ms = 3000;
  14717. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14718. EXPECT_EQ(msg.data, "hello");
  14719. }
  14720. // Test: Unknown fields ignored
  14721. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14722. sse::SSEMessage msg;
  14723. int retry_ms = 3000;
  14724. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14725. EXPECT_EQ(msg.data, "");
  14726. EXPECT_EQ(msg.event, "message");
  14727. }
  14728. // Test: Space after colon is optional
  14729. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14730. sse::SSEMessage msg1, msg2;
  14731. int retry_ms = 3000;
  14732. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14733. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14734. EXPECT_EQ(msg1.data, "hello");
  14735. EXPECT_EQ(msg2.data, "hello");
  14736. }
  14737. // Test: SSEMessage clear
  14738. TEST_F(SSEParsingTest, MessageClear) {
  14739. sse::SSEMessage msg;
  14740. msg.event = "custom";
  14741. msg.data = "some data";
  14742. msg.id = "123";
  14743. msg.clear();
  14744. EXPECT_EQ(msg.event, "message");
  14745. EXPECT_EQ(msg.data, "");
  14746. EXPECT_EQ(msg.id, "");
  14747. }
  14748. // Test: Complete event parsing
  14749. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14750. sse::SSEMessage msg;
  14751. int retry_ms = 3000;
  14752. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14753. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14754. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14755. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14756. // Blank line ends event
  14757. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14758. EXPECT_EQ(msg.event, "notification");
  14759. EXPECT_EQ(msg.id, "evt-42");
  14760. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14761. EXPECT_EQ(retry_ms, 1000);
  14762. }
  14763. //==============================================================================
  14764. // Integration Tests with Server
  14765. //==============================================================================
  14766. class SSEIntegrationTest : public ::testing::Test {
  14767. protected:
  14768. void SetUp() override {
  14769. stop_server_.store(false);
  14770. events_.clear();
  14771. server_ = httplib::detail::make_unique<Server>();
  14772. setup_server();
  14773. start_server();
  14774. }
  14775. void TearDown() override {
  14776. stop_server_.store(true);
  14777. event_cv_.notify_all();
  14778. server_->stop();
  14779. if (server_thread_.joinable()) { server_thread_.join(); }
  14780. }
  14781. void setup_server() {
  14782. // Simple SSE endpoint
  14783. server_->Get("/events", [this](const Request &req, Response &res) {
  14784. auto last_id = req.get_header_value("Last-Event-ID");
  14785. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14786. res.set_chunked_content_provider(
  14787. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14788. std::unique_lock<std::mutex> lock(event_mutex_);
  14789. if (event_cv_.wait_for(
  14790. lock, std::chrono::milliseconds(200), [this] {
  14791. return !events_.empty() || stop_server_.load();
  14792. })) {
  14793. if (stop_server_.load()) { return false; }
  14794. if (!events_.empty()) {
  14795. std::string event = events_.front();
  14796. events_.erase(events_.begin());
  14797. sink.write(event.data(), event.size());
  14798. return true;
  14799. }
  14800. }
  14801. return !stop_server_.load();
  14802. });
  14803. });
  14804. // Endpoint that returns error
  14805. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14806. res.status = 500;
  14807. res.set_content("Internal Server Error", "text/plain");
  14808. });
  14809. // Endpoint for custom event types
  14810. server_->Get("/custom-events", [](const Request &, Response &res) {
  14811. res.set_chunked_content_provider(
  14812. "text/event-stream", [](size_t offset, DataSink &sink) {
  14813. if (offset == 0) {
  14814. std::string event = "event: update\ndata: updated\n\n"
  14815. "event: delete\ndata: deleted\n\n";
  14816. sink.write(event.data(), event.size());
  14817. }
  14818. return false; // End stream after sending
  14819. });
  14820. });
  14821. }
  14822. void start_server() {
  14823. port_ = server_->bind_to_any_port(HOST);
  14824. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14825. // Wait for server to start
  14826. while (!server_->is_running()) {
  14827. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14828. }
  14829. }
  14830. int get_port() const { return port_; }
  14831. void send_event(const std::string &event) {
  14832. std::lock_guard<std::mutex> lock(event_mutex_);
  14833. events_.push_back(event);
  14834. event_cv_.notify_all();
  14835. }
  14836. std::unique_ptr<Server> server_;
  14837. std::thread server_thread_;
  14838. std::mutex event_mutex_;
  14839. std::condition_variable event_cv_;
  14840. std::vector<std::string> events_;
  14841. std::atomic<bool> stop_server_{false};
  14842. std::string last_received_event_id_;
  14843. int port_ = 0;
  14844. };
  14845. // Test: Successful connection and on_open callback
  14846. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14847. // Add a simple endpoint that sends one event and closes
  14848. server_->Get("/simple-event", [](const Request &, Response &res) {
  14849. res.set_chunked_content_provider(
  14850. "text/event-stream", [](size_t offset, DataSink &sink) {
  14851. if (offset == 0) {
  14852. std::string event = "data: hello\n\n";
  14853. sink.write(event.data(), event.size());
  14854. }
  14855. return false; // Close stream after sending
  14856. });
  14857. });
  14858. Client client("localhost", get_port());
  14859. sse::SSEClient sse(client, "/simple-event");
  14860. std::atomic<bool> open_called{false};
  14861. std::atomic<bool> message_received{false};
  14862. sse.on_open([&open_called]() { open_called.store(true); });
  14863. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14864. if (msg.data == "hello") { message_received.store(true); }
  14865. });
  14866. sse.set_reconnect_interval(100);
  14867. sse.set_max_reconnect_attempts(1);
  14868. // Start async
  14869. sse.start_async();
  14870. // Wait for message to be processed
  14871. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14872. sse.stop();
  14873. EXPECT_TRUE(open_called.load());
  14874. EXPECT_TRUE(message_received.load());
  14875. }
  14876. // Test: on_message callback
  14877. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14878. // Endpoint that sends multiple events then closes
  14879. server_->Get("/multi-event", [](const Request &, Response &res) {
  14880. res.set_chunked_content_provider(
  14881. "text/event-stream", [](size_t offset, DataSink &sink) {
  14882. if (offset == 0) {
  14883. std::string events = "data: message1\n\ndata: message2\n\n";
  14884. sink.write(events.data(), events.size());
  14885. }
  14886. return false;
  14887. });
  14888. });
  14889. Client client("localhost", get_port());
  14890. sse::SSEClient sse(client, "/multi-event");
  14891. std::vector<std::string> received_messages;
  14892. std::mutex messages_mutex;
  14893. sse.on_message([&](const sse::SSEMessage &msg) {
  14894. std::lock_guard<std::mutex> lock(messages_mutex);
  14895. received_messages.push_back(msg.data);
  14896. });
  14897. sse.set_reconnect_interval(100);
  14898. sse.set_max_reconnect_attempts(1);
  14899. sse.start_async();
  14900. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14901. sse.stop();
  14902. std::lock_guard<std::mutex> lock(messages_mutex);
  14903. EXPECT_GE(received_messages.size(), 2u);
  14904. if (received_messages.size() >= 2) {
  14905. EXPECT_EQ(received_messages[0], "message1");
  14906. EXPECT_EQ(received_messages[1], "message2");
  14907. }
  14908. }
  14909. // Test: on_event for specific types
  14910. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14911. Client client("localhost", get_port());
  14912. sse::SSEClient sse(client, "/custom-events");
  14913. std::atomic<bool> update_received{false};
  14914. std::atomic<bool> delete_received{false};
  14915. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14916. if (msg.data == "updated") { update_received.store(true); }
  14917. });
  14918. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14919. if (msg.data == "deleted") { delete_received.store(true); }
  14920. });
  14921. sse.set_max_reconnect_attempts(1);
  14922. sse.start_async();
  14923. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14924. sse.stop();
  14925. EXPECT_TRUE(update_received.load());
  14926. EXPECT_TRUE(delete_received.load());
  14927. }
  14928. // Test: on_error callback on connection failure
  14929. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14930. // Connect to a non-existent port
  14931. Client client("localhost", 59999);
  14932. sse::SSEClient sse(client, "/events");
  14933. std::atomic<bool> error_called{false};
  14934. Error received_error = Error::Success;
  14935. sse.on_error([&](Error err) {
  14936. error_called.store(true);
  14937. received_error = err;
  14938. });
  14939. sse.set_reconnect_interval(50);
  14940. sse.set_max_reconnect_attempts(1);
  14941. sse.start_async();
  14942. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14943. sse.stop();
  14944. EXPECT_TRUE(error_called.load());
  14945. EXPECT_NE(received_error, Error::Success);
  14946. }
  14947. // Test: Last-Event-ID header sent on reconnect
  14948. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14949. // Endpoint that sends event with ID
  14950. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14951. res.set_chunked_content_provider(
  14952. "text/event-stream", [](size_t offset, DataSink &sink) {
  14953. if (offset == 0) {
  14954. std::string event = "id: evt-123\ndata: test\n\n";
  14955. sink.write(event.data(), event.size());
  14956. }
  14957. return false;
  14958. });
  14959. });
  14960. Client client("localhost", get_port());
  14961. sse::SSEClient sse(client, "/event-with-id");
  14962. std::atomic<bool> id_received{false};
  14963. sse.on_message([&](const sse::SSEMessage &msg) {
  14964. if (!msg.id.empty()) { id_received.store(true); }
  14965. });
  14966. sse.set_reconnect_interval(100);
  14967. sse.set_max_reconnect_attempts(1);
  14968. sse.start_async();
  14969. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14970. sse.stop();
  14971. EXPECT_TRUE(id_received.load());
  14972. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14973. }
  14974. // Test: Manual stop
  14975. TEST_F(SSEIntegrationTest, ManualStop) {
  14976. // Endpoint that sends one event and stays open briefly
  14977. std::atomic<bool> handler_running{true};
  14978. server_->Get("/stay-open", [&handler_running](const Request &,
  14979. Response &res) {
  14980. res.set_chunked_content_provider(
  14981. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14982. if (offset == 0) {
  14983. std::string event = "data: connected\n\n";
  14984. sink.write(event.data(), event.size());
  14985. }
  14986. // Keep connection open while handler_running is true
  14987. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14988. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14989. }
  14990. return false;
  14991. });
  14992. });
  14993. Client client("localhost", get_port());
  14994. sse::SSEClient sse(client, "/stay-open");
  14995. std::atomic<bool> connected{false};
  14996. sse.on_open([&connected]() { connected.store(true); });
  14997. sse.set_reconnect_interval(100);
  14998. sse.set_max_reconnect_attempts(1);
  14999. sse.start_async();
  15000. // Wait for connection to establish
  15001. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15002. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15003. }
  15004. EXPECT_TRUE(connected.load());
  15005. EXPECT_TRUE(sse.is_connected());
  15006. // Signal handler to stop
  15007. handler_running.store(false);
  15008. // Stop SSE client
  15009. sse.stop();
  15010. EXPECT_FALSE(sse.is_connected());
  15011. }
  15012. // Test: SSEClient with custom headers
  15013. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15014. // Setup a server endpoint that checks for custom header
  15015. std::atomic<bool> header_received{false};
  15016. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15017. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15018. header_received.store(true);
  15019. }
  15020. res.set_chunked_content_provider("text/event-stream",
  15021. [](size_t, DataSink &) { return false; });
  15022. });
  15023. Client client("localhost", get_port());
  15024. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15025. sse::SSEClient sse(client, "/header-check", headers);
  15026. sse.set_max_reconnect_attempts(1);
  15027. sse.start_async();
  15028. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15029. sse.stop();
  15030. EXPECT_TRUE(header_received.load());
  15031. }
  15032. // Test: Reconnect interval configuration
  15033. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15034. Client client("localhost", get_port());
  15035. sse::SSEClient sse(client, "/events");
  15036. auto &result = sse.set_reconnect_interval(500);
  15037. // Builder pattern should return reference to self
  15038. EXPECT_EQ(&result, &sse);
  15039. }
  15040. // Test: Max reconnect attempts
  15041. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15042. // Connect to non-existent port to force reconnects
  15043. Client client("localhost", 59998);
  15044. sse::SSEClient sse(client, "/events");
  15045. std::atomic<int> error_count{0};
  15046. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15047. sse.set_reconnect_interval(50);
  15048. sse.set_max_reconnect_attempts(2);
  15049. auto start = std::chrono::steady_clock::now();
  15050. sse.start(); // Blocking call
  15051. auto end = std::chrono::steady_clock::now();
  15052. // Should have stopped after 2 failed attempts
  15053. EXPECT_GE(error_count.load(), 2);
  15054. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15055. auto duration =
  15056. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15057. #ifdef _WIN32
  15058. // Windows is much slower for socket connection failures
  15059. EXPECT_LT(duration.count(), 7000);
  15060. #else
  15061. EXPECT_LT(duration.count(), 1000);
  15062. #endif
  15063. }
  15064. // Test: Multi-line data in integration
  15065. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15066. // Endpoint with multi-line data
  15067. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15068. res.set_chunked_content_provider(
  15069. "text/event-stream", [](size_t offset, DataSink &sink) {
  15070. if (offset == 0) {
  15071. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15072. sink.write(event.data(), event.size());
  15073. }
  15074. return false;
  15075. });
  15076. });
  15077. Client client("localhost", get_port());
  15078. sse::SSEClient sse(client, "/multiline-data");
  15079. std::string received_data;
  15080. std::mutex data_mutex;
  15081. sse.on_message([&](const sse::SSEMessage &msg) {
  15082. std::lock_guard<std::mutex> lock(data_mutex);
  15083. received_data = msg.data;
  15084. });
  15085. sse.set_reconnect_interval(100);
  15086. sse.set_max_reconnect_attempts(1);
  15087. sse.start_async();
  15088. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15089. sse.stop();
  15090. std::lock_guard<std::mutex> lock(data_mutex);
  15091. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15092. }
  15093. // Test: Auto-reconnect after server disconnection
  15094. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15095. std::atomic<int> connection_count{0};
  15096. std::atomic<int> message_count{0};
  15097. // Endpoint that sends one event and closes, forcing reconnect
  15098. server_->Get("/reconnect-test",
  15099. [&connection_count](const Request &, Response &res) {
  15100. connection_count.fetch_add(1);
  15101. res.set_chunked_content_provider(
  15102. "text/event-stream", [](size_t offset, DataSink &sink) {
  15103. if (offset == 0) {
  15104. std::string event = "data: hello\n\n";
  15105. sink.write(event.data(), event.size());
  15106. }
  15107. return false; // Close connection after sending
  15108. });
  15109. });
  15110. Client client("localhost", get_port());
  15111. sse::SSEClient sse(client, "/reconnect-test");
  15112. sse.on_message([&message_count](const sse::SSEMessage &) {
  15113. message_count.fetch_add(1);
  15114. });
  15115. sse.set_reconnect_interval(100);
  15116. sse.set_max_reconnect_attempts(3);
  15117. sse.start_async();
  15118. // Wait long enough for multiple reconnects
  15119. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15120. sse.stop();
  15121. // Should have connected multiple times (initial + reconnects)
  15122. EXPECT_GE(connection_count.load(), 2);
  15123. // Should have received messages from multiple connections
  15124. EXPECT_GE(message_count.load(), 2);
  15125. }
  15126. // Test: Last-Event-ID sent on reconnect
  15127. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15128. std::atomic<int> connection_count{0};
  15129. std::vector<std::string> received_last_event_ids;
  15130. std::mutex id_mutex;
  15131. // Endpoint that checks Last-Event-ID header and sends event with ID
  15132. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15133. int conn = connection_count.fetch_add(1);
  15134. // Capture the Last-Event-ID header from each connection
  15135. {
  15136. std::lock_guard<std::mutex> lock(id_mutex);
  15137. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15138. }
  15139. res.set_chunked_content_provider(
  15140. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15141. if (offset == 0) {
  15142. std::string event =
  15143. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15144. sink.write(event.data(), event.size());
  15145. }
  15146. return false;
  15147. });
  15148. });
  15149. Client client("localhost", get_port());
  15150. sse::SSEClient sse(client, "/reconnect-with-id");
  15151. sse.set_reconnect_interval(100);
  15152. sse.set_max_reconnect_attempts(3);
  15153. sse.start_async();
  15154. // Wait for at least 2 connections
  15155. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15156. sse.stop();
  15157. // Verify behavior
  15158. std::lock_guard<std::mutex> lock(id_mutex);
  15159. EXPECT_GE(received_last_event_ids.size(), 2u);
  15160. // First connection should have no Last-Event-ID
  15161. if (!received_last_event_ids.empty()) {
  15162. EXPECT_EQ(received_last_event_ids[0], "");
  15163. }
  15164. // Second connection should have Last-Event-ID from first connection
  15165. if (received_last_event_ids.size() >= 2) {
  15166. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15167. }
  15168. }
  15169. // Test: set_headers updates headers used on reconnect
  15170. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15171. std::vector<std::string> received_tokens;
  15172. std::mutex token_mutex;
  15173. // Endpoint that captures Authorization header
  15174. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15175. {
  15176. std::lock_guard<std::mutex> lock(token_mutex);
  15177. received_tokens.push_back(req.get_header_value("Authorization"));
  15178. }
  15179. res.set_chunked_content_provider(
  15180. "text/event-stream", [](size_t offset, DataSink &sink) {
  15181. if (offset == 0) {
  15182. std::string event = "data: hello\n\n";
  15183. sink.write(event.data(), event.size());
  15184. }
  15185. return false; // Close connection to trigger reconnect
  15186. });
  15187. });
  15188. Client client("localhost", get_port());
  15189. Headers headers = {{"Authorization", "Bearer old-token"}};
  15190. sse::SSEClient sse(client, "/auth-check", headers);
  15191. // Update headers on each successful connection
  15192. sse.on_open(
  15193. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15194. sse.set_reconnect_interval(100);
  15195. sse.set_max_reconnect_attempts(3);
  15196. sse.start_async();
  15197. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15198. sse.stop();
  15199. std::lock_guard<std::mutex> lock(token_mutex);
  15200. ASSERT_GE(received_tokens.size(), 2u);
  15201. // First connection uses original header
  15202. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15203. // Second connection uses updated header from set_headers
  15204. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15205. }
  15206. // Test: 401 allows reconnection (so on_error can refresh headers)
  15207. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15208. std::atomic<int> connection_count{0};
  15209. // Endpoint: returns 401 on first attempt, 200 on second
  15210. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15211. int conn = connection_count.fetch_add(1);
  15212. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15213. res.status = StatusCode::Unauthorized_401;
  15214. res.set_content("Unauthorized", "text/plain");
  15215. return;
  15216. }
  15217. res.set_chunked_content_provider(
  15218. "text/event-stream", [](size_t offset, DataSink &sink) {
  15219. if (offset == 0) {
  15220. std::string event = "data: authenticated\n\n";
  15221. sink.write(event.data(), event.size());
  15222. }
  15223. return false;
  15224. });
  15225. });
  15226. Client client("localhost", get_port());
  15227. Headers headers = {{"Authorization", "Bearer expired"}};
  15228. sse::SSEClient sse(client, "/auth-retry", headers);
  15229. std::atomic<bool> message_received{false};
  15230. // Refresh token on error
  15231. sse.on_error(
  15232. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15233. sse.on_message([&](const sse::SSEMessage &msg) {
  15234. if (msg.data == "authenticated") { message_received.store(true); }
  15235. });
  15236. sse.set_reconnect_interval(100);
  15237. sse.set_max_reconnect_attempts(3);
  15238. sse.start_async();
  15239. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15240. sse.stop();
  15241. // Should have reconnected after 401 and succeeded with new token
  15242. EXPECT_GE(connection_count.load(), 2);
  15243. EXPECT_TRUE(message_received.load());
  15244. }
  15245. TEST(Issue2318Test, EmptyHostString) {
  15246. {
  15247. httplib::Client cli_empty("", PORT);
  15248. auto res = cli_empty.Get("/");
  15249. ASSERT_FALSE(res);
  15250. EXPECT_EQ(httplib::Error::Connection, res.error());
  15251. }
  15252. {
  15253. httplib::Client cli(" ", PORT);
  15254. auto res = cli.Get("/");
  15255. ASSERT_FALSE(res);
  15256. EXPECT_EQ(httplib::Error::Connection, res.error());
  15257. }
  15258. }
  15259. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15260. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15261. Server svr;
  15262. // Set a small payload limit (1KB)
  15263. svr.set_payload_max_length(1024);
  15264. svr.Post("/test", [&](const Request &req, Response &res) {
  15265. res.set_content("Body size: " + std::to_string(req.body.size()),
  15266. "text/plain");
  15267. });
  15268. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15269. auto se = detail::scope_exit([&] {
  15270. svr.stop();
  15271. listen_thread.join();
  15272. });
  15273. svr.wait_until_ready();
  15274. // Create data that compresses well but exceeds limit when decompressed
  15275. // 8KB of repeated null bytes compresses to a very small size
  15276. std::string original_data(8 * 1024, '\0');
  15277. // Compress the data using gzip
  15278. std::string compressed_data;
  15279. detail::gzip_compressor compressor;
  15280. compressor.compress(original_data.data(), original_data.size(), true,
  15281. [&](const char *data, size_t size) {
  15282. compressed_data.append(data, size);
  15283. return true;
  15284. });
  15285. // Verify compression worked (compressed should be much smaller)
  15286. ASSERT_LT(compressed_data.size(), original_data.size());
  15287. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15288. // Send compressed data with Content-Encoding: gzip
  15289. Client cli(HOST, PORT);
  15290. Headers headers = {{"Content-Encoding", "gzip"}};
  15291. auto res =
  15292. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15293. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15294. ASSERT_TRUE(res);
  15295. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15296. }
  15297. #endif
  15298. // ============================================================================
  15299. // OpenSSL-Specific Tests
  15300. // ============================================================================
  15301. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15302. X509 *readCertificate(const std::string &strFileName) {
  15303. std::ifstream inStream(strFileName);
  15304. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15305. std::istreambuf_iterator<char>());
  15306. if (strCertPEM.empty()) return (nullptr);
  15307. BIO *pbCert = BIO_new(BIO_s_mem());
  15308. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15309. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15310. BIO_free(pbCert);
  15311. return (pCert);
  15312. }
  15313. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15314. std::ifstream inStream(strFileName);
  15315. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15316. std::istreambuf_iterator<char>());
  15317. if (strPrivateKeyPEM.empty()) return (nullptr);
  15318. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15319. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15320. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15321. BIO_free(pbPrivKey);
  15322. return (pPrivateKey);
  15323. }
  15324. TEST(BindServerTest, UpdateCerts) {
  15325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15326. int port = svr.bind_to_any_port("0.0.0.0");
  15327. ASSERT_TRUE(svr.is_valid());
  15328. ASSERT_TRUE(port > 0);
  15329. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15330. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15331. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15332. ASSERT_TRUE(cert != nullptr);
  15333. ASSERT_TRUE(ca_cert != nullptr);
  15334. ASSERT_TRUE(key != nullptr);
  15335. X509_STORE *cert_store = X509_STORE_new();
  15336. X509_STORE_add_cert(cert_store, ca_cert);
  15337. // svr.update_certs(cert, key, cert_store); // deprecated
  15338. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15339. CLIENT_CA_CERT_FILE);
  15340. ASSERT_TRUE(svr.is_valid());
  15341. svr.stop();
  15342. X509_STORE_free(cert_store);
  15343. X509_free(cert);
  15344. X509_free(ca_cert);
  15345. EVP_PKEY_free(key);
  15346. }
  15347. // Test that update_certs() updates client CA list correctly
  15348. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15349. // Start with file-based constructor
  15350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15351. ASSERT_TRUE(svr.is_valid());
  15352. // Initially no client CA list should be set
  15353. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15354. ASSERT_TRUE(ssl_ctx != nullptr);
  15355. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15356. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15357. EXPECT_EQ(0, count_before);
  15358. // Now update with client CA (PEM string)
  15359. std::string cert_pem, key_pem, ca_pem;
  15360. read_file(SERVER_CERT_FILE, cert_pem);
  15361. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15362. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15363. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15364. ASSERT_TRUE(svr.is_valid());
  15365. // Now client CA list should be set
  15366. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15367. ASSERT_TRUE(ca_list_after != nullptr);
  15368. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15369. }
  15370. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15371. // Test that the file-path SSLServer constructor properly sets the client CA
  15372. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15374. ASSERT_TRUE(svr.is_valid());
  15375. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15376. ASSERT_TRUE(ssl_ctx != nullptr);
  15377. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15378. ASSERT_TRUE(ca_list != nullptr);
  15379. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15380. }
  15381. #endif
  15382. // ============================================================================
  15383. // MbedTLS-Specific Tests
  15384. // ============================================================================
  15385. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15386. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15387. using namespace httplib::tls;
  15388. // Track if callback was invoked
  15389. bool callback_invoked = false;
  15390. // The callback receives void* ctx which is actually MbedTlsContext*
  15391. // We can access the mbedtls_ssl_config via the context
  15392. auto setup_callback = [&callback_invoked](void *ctx) {
  15393. callback_invoked = true;
  15394. // Cast to MbedTlsContext* to access the ssl config
  15395. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15396. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15397. // Use static variables to hold certificate data (simplified for test)
  15398. static mbedtls_x509_crt own_cert;
  15399. static mbedtls_pk_context own_key;
  15400. static mbedtls_x509_crt ca_chain;
  15401. static bool initialized = false;
  15402. if (!initialized) {
  15403. mbedtls_x509_crt_init(&own_cert);
  15404. mbedtls_pk_init(&own_key);
  15405. mbedtls_x509_crt_init(&ca_chain);
  15406. // Load server certificate
  15407. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15408. return false;
  15409. }
  15410. // Load server private key
  15411. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15412. #if MBEDTLS_VERSION_MAJOR >= 3
  15413. ,
  15414. mbedtls_ctr_drbg_random, nullptr
  15415. #endif
  15416. ) != 0) {
  15417. return false;
  15418. }
  15419. // Load CA chain for client verification
  15420. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15421. return false;
  15422. }
  15423. initialized = true;
  15424. }
  15425. // Configure the SSL config
  15426. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15427. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15428. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15429. // Set minimum TLS version using mbedTLS native API
  15430. #if MBEDTLS_VERSION_MAJOR >= 3
  15431. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15432. #else
  15433. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15434. MBEDTLS_SSL_MINOR_VERSION_3);
  15435. #endif
  15436. return true;
  15437. };
  15438. SSLServer svr(setup_callback);
  15439. ASSERT_TRUE(svr.is_valid());
  15440. ASSERT_TRUE(callback_invoked);
  15441. svr.Get("/test", [&](const Request &req, Response &res) {
  15442. res.set_content("test", "text/plain");
  15443. auto cert = req.peer_cert();
  15444. ASSERT_TRUE(static_cast<bool>(cert));
  15445. auto common_name = cert.subject_cn();
  15446. EXPECT_EQ("Common Name", common_name);
  15447. });
  15448. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15449. auto se = detail::scope_exit([&] {
  15450. svr.stop();
  15451. t.join();
  15452. ASSERT_FALSE(svr.is_running());
  15453. });
  15454. svr.wait_until_ready();
  15455. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15456. cli.enable_server_certificate_verification(false);
  15457. cli.set_connection_timeout(30);
  15458. auto res = cli.Get("/test");
  15459. ASSERT_TRUE(res);
  15460. ASSERT_EQ(StatusCode::OK_200, res->status);
  15461. }
  15462. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15463. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15464. // keep-alive SSL session, which reads through that config in
  15465. // mbedtls_ssl_close_notify.
  15466. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15468. ASSERT_TRUE(svr.is_valid());
  15469. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15470. res.set_content("test", "text/plain");
  15471. });
  15472. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15473. auto se = detail::scope_exit([&] {
  15474. svr.stop();
  15475. t.join();
  15476. ASSERT_FALSE(svr.is_running());
  15477. });
  15478. svr.wait_until_ready();
  15479. {
  15480. SSLClient cli(HOST, PORT);
  15481. cli.enable_server_certificate_verification(false);
  15482. cli.set_keep_alive(true);
  15483. auto res = cli.Get("/test");
  15484. ASSERT_TRUE(res);
  15485. ASSERT_EQ(StatusCode::OK_200, res->status);
  15486. // cli is destructed here with the keep-alive SSL session still open.
  15487. }
  15488. }
  15489. #endif
  15490. // WebSocket Tests
  15491. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15492. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15493. // defining the meaning of these bits has been negotiated.
  15494. auto make_frame = [](uint8_t first_byte) {
  15495. std::string frame;
  15496. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15497. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15498. frame += "Hello";
  15499. return frame;
  15500. };
  15501. // RSV1 set (0x40)
  15502. {
  15503. detail::BufferStream strm;
  15504. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15505. ws::Opcode opcode;
  15506. std::string payload;
  15507. bool fin;
  15508. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15509. false, 1024));
  15510. }
  15511. // RSV2 set (0x20)
  15512. {
  15513. detail::BufferStream strm;
  15514. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15515. ws::Opcode opcode;
  15516. std::string payload;
  15517. bool fin;
  15518. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15519. false, 1024));
  15520. }
  15521. // RSV3 set (0x10)
  15522. {
  15523. detail::BufferStream strm;
  15524. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15525. ws::Opcode opcode;
  15526. std::string payload;
  15527. bool fin;
  15528. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15529. false, 1024));
  15530. }
  15531. // No RSV bits set - should succeed
  15532. {
  15533. detail::BufferStream strm;
  15534. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15535. ws::Opcode opcode;
  15536. std::string payload;
  15537. bool fin;
  15538. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15539. false, 1024));
  15540. EXPECT_EQ(ws::Opcode::Text, opcode);
  15541. EXPECT_EQ("Hello", payload);
  15542. EXPECT_TRUE(fin);
  15543. }
  15544. }
  15545. TEST(WebSocketTest, ControlFrameValidation) {
  15546. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15547. // payload length <= 125.
  15548. // Ping with FIN=0 - must be rejected
  15549. {
  15550. detail::BufferStream strm;
  15551. std::string frame;
  15552. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15553. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15554. strm.write(frame.data(), frame.size());
  15555. ws::Opcode opcode;
  15556. std::string payload;
  15557. bool fin;
  15558. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15559. false, 1024));
  15560. }
  15561. // Close with FIN=0 - must be rejected
  15562. {
  15563. detail::BufferStream strm;
  15564. std::string frame;
  15565. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15566. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15567. strm.write(frame.data(), frame.size());
  15568. ws::Opcode opcode;
  15569. std::string payload;
  15570. bool fin;
  15571. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15572. false, 1024));
  15573. }
  15574. // Ping with payload_len=126 (extended length) - must be rejected
  15575. {
  15576. detail::BufferStream strm;
  15577. std::string frame;
  15578. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15579. frame += static_cast<char>(126); // payload_len=126 (>125)
  15580. frame += static_cast<char>(0x00); // extended length high byte
  15581. frame += static_cast<char>(126); // extended length low byte
  15582. frame += std::string(126, 'x');
  15583. strm.write(frame.data(), frame.size());
  15584. ws::Opcode opcode;
  15585. std::string payload;
  15586. bool fin;
  15587. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15588. false, 1024));
  15589. }
  15590. // Ping with FIN=1 and payload_len=125 - should succeed
  15591. {
  15592. detail::BufferStream strm;
  15593. std::string frame;
  15594. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15595. frame += static_cast<char>(125); // payload_len=125
  15596. frame += std::string(125, 'x');
  15597. strm.write(frame.data(), frame.size());
  15598. ws::Opcode opcode;
  15599. std::string payload;
  15600. bool fin;
  15601. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15602. false, 1024));
  15603. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15604. EXPECT_EQ(125u, payload.size());
  15605. EXPECT_TRUE(fin);
  15606. }
  15607. }
  15608. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15609. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15610. // length MUST be 0.
  15611. // MSB set - must be rejected
  15612. {
  15613. detail::BufferStream strm;
  15614. std::string frame;
  15615. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15616. frame += static_cast<char>(127); // 64-bit extended length
  15617. frame += static_cast<char>(0x80); // MSB set (invalid)
  15618. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15619. strm.write(frame.data(), frame.size());
  15620. ws::Opcode opcode;
  15621. std::string payload;
  15622. bool fin;
  15623. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15624. false, 1024));
  15625. }
  15626. // MSB clear - should pass length parsing (will be rejected by max_len,
  15627. // but that's a different check; use a small length to verify)
  15628. {
  15629. detail::BufferStream strm;
  15630. std::string frame;
  15631. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15632. frame += static_cast<char>(127); // 64-bit extended length
  15633. frame += std::string(7, '\0'); // high bytes = 0
  15634. frame += static_cast<char>(0x03); // length = 3
  15635. frame += "abc";
  15636. strm.write(frame.data(), frame.size());
  15637. ws::Opcode opcode;
  15638. std::string payload;
  15639. bool fin;
  15640. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15641. false, 1024));
  15642. EXPECT_EQ(ws::Opcode::Text, opcode);
  15643. EXPECT_EQ("abc", payload);
  15644. }
  15645. }
  15646. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15647. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15648. // Valid UTF-8
  15649. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15650. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15651. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15652. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15653. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15654. // Invalid UTF-8
  15655. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15656. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15657. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15658. EXPECT_FALSE(
  15659. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15660. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15661. }
  15662. TEST(WebSocketTest, ConnectAndDisconnect) {
  15663. Server svr;
  15664. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15665. std::string msg;
  15666. while (ws.read(msg)) {}
  15667. });
  15668. auto port = svr.bind_to_any_port(HOST);
  15669. std::thread t([&]() { svr.listen_after_bind(); });
  15670. svr.wait_until_ready();
  15671. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15672. ASSERT_TRUE(client.connect());
  15673. EXPECT_TRUE(client.is_open());
  15674. client.close();
  15675. EXPECT_FALSE(client.is_open());
  15676. svr.stop();
  15677. t.join();
  15678. }
  15679. TEST(WebSocketTest, ValidURL) {
  15680. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15681. EXPECT_TRUE(ws1.is_valid());
  15682. ws::WebSocketClient ws2("ws://example.com/path");
  15683. EXPECT_TRUE(ws2.is_valid());
  15684. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15685. EXPECT_TRUE(ws3.is_valid());
  15686. #ifdef CPPHTTPLIB_SSL_ENABLED
  15687. ws::WebSocketClient wss1("wss://example.com/path");
  15688. EXPECT_TRUE(wss1.is_valid());
  15689. ws::WebSocketClient wss2("wss://example.com:443/path");
  15690. EXPECT_TRUE(wss2.is_valid());
  15691. #endif
  15692. }
  15693. TEST(WebSocketTest, InvalidURL) {
  15694. // No scheme
  15695. ws::WebSocketClient ws1("localhost:8080/path");
  15696. EXPECT_FALSE(ws1.is_valid());
  15697. // No path
  15698. ws::WebSocketClient ws2("ws://localhost:8080");
  15699. EXPECT_FALSE(ws2.is_valid());
  15700. // Empty string
  15701. ws::WebSocketClient ws3("");
  15702. EXPECT_FALSE(ws3.is_valid());
  15703. // Missing host
  15704. ws::WebSocketClient ws4("ws://:8080/path");
  15705. EXPECT_FALSE(ws4.is_valid());
  15706. // Port number overflow — should not crash
  15707. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15708. EXPECT_FALSE(ws5.is_valid());
  15709. // Port out of range
  15710. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15711. EXPECT_FALSE(ws6.is_valid());
  15712. }
  15713. TEST(WebSocketTest, UnsupportedScheme) {
  15714. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15715. ws::WebSocketClient ws1("http://localhost:8080/path");
  15716. EXPECT_FALSE(ws1.is_valid());
  15717. ws::WebSocketClient ws2("https://localhost:8080/path");
  15718. EXPECT_FALSE(ws2.is_valid());
  15719. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15720. EXPECT_FALSE(ws3.is_valid());
  15721. #else
  15722. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15723. std::invalid_argument);
  15724. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15725. std::invalid_argument);
  15726. #endif
  15727. }
  15728. TEST(WebSocketTest, ConnectWhenInvalid) {
  15729. ws::WebSocketClient ws("not a valid url");
  15730. EXPECT_FALSE(ws.is_valid());
  15731. EXPECT_FALSE(ws.connect());
  15732. }
  15733. TEST(WebSocketTest, DefaultPort) {
  15734. ws::WebSocketClient ws1("ws://example.com/path");
  15735. EXPECT_TRUE(ws1.is_valid());
  15736. // ws:// defaults to port 80 (verified by successful parse)
  15737. #ifdef CPPHTTPLIB_SSL_ENABLED
  15738. ws::WebSocketClient ws2("wss://example.com/path");
  15739. EXPECT_TRUE(ws2.is_valid());
  15740. // wss:// defaults to port 443 (verified by successful parse)
  15741. #endif
  15742. }
  15743. TEST(WebSocketTest, IPv6LiteralAddress) {
  15744. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15745. EXPECT_TRUE(ws1.is_valid());
  15746. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15747. EXPECT_TRUE(ws2.is_valid());
  15748. }
  15749. TEST(WebSocketTest, ComplexPath) {
  15750. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15751. EXPECT_TRUE(ws1.is_valid());
  15752. ws::WebSocketClient ws2("ws://localhost:8080/");
  15753. EXPECT_TRUE(ws2.is_valid());
  15754. }
  15755. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15756. Server svr;
  15757. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15758. std::string msg;
  15759. while (ws.read(msg)) {}
  15760. });
  15761. auto port = svr.bind_to_any_port(HOST);
  15762. std::thread t([&]() { svr.listen_after_bind(); });
  15763. svr.wait_until_ready();
  15764. auto another_host = "example.com";
  15765. auto wrong_ip = "192.0.2.1";
  15766. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15767. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15768. ASSERT_TRUE(client.connect());
  15769. EXPECT_TRUE(client.is_open());
  15770. client.close();
  15771. svr.stop();
  15772. t.join();
  15773. }
  15774. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15775. Server svr;
  15776. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15777. std::string msg;
  15778. while (ws.read(msg)) {}
  15779. });
  15780. auto port = svr.bind_to_any_port(HOST);
  15781. std::thread t([&]() { svr.listen_after_bind(); });
  15782. svr.wait_until_ready();
  15783. auto wrong_ip = "192.0.2.1";
  15784. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15785. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15786. client.set_connection_timeout(1);
  15787. client.set_read_timeout(1);
  15788. client.set_write_timeout(1);
  15789. EXPECT_FALSE(client.connect());
  15790. EXPECT_FALSE(client.is_open());
  15791. svr.stop();
  15792. t.join();
  15793. }
  15794. class WebSocketIntegrationTest : public ::testing::Test {
  15795. protected:
  15796. void SetUp() override {
  15797. server_ = httplib::detail::make_unique<Server>();
  15798. setup_server();
  15799. start_server();
  15800. }
  15801. void TearDown() override {
  15802. server_->stop();
  15803. if (server_thread_.joinable()) { server_thread_.join(); }
  15804. }
  15805. void setup_server() {
  15806. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15807. std::string msg;
  15808. ws::ReadResult ret;
  15809. while ((ret = ws.read(msg))) {
  15810. if (ret == ws::Binary) {
  15811. ws.send(msg.data(), msg.size());
  15812. } else {
  15813. ws.send(msg);
  15814. }
  15815. }
  15816. });
  15817. server_->WebSocket("/ws-echo-string",
  15818. [](const Request &, ws::WebSocket &ws) {
  15819. std::string msg;
  15820. while (ws.read(msg)) {
  15821. ws.send("echo: " + msg);
  15822. }
  15823. });
  15824. server_->WebSocket(
  15825. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15826. // Echo back request metadata
  15827. ws.send("path:" + req.path);
  15828. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15829. std::string msg;
  15830. while (ws.read(msg)) {}
  15831. });
  15832. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15833. std::string msg;
  15834. ws.read(msg); // wait for a message
  15835. ws.close();
  15836. });
  15837. server_->WebSocket("/ws-close-status",
  15838. [](const Request &, ws::WebSocket &ws) {
  15839. std::string msg;
  15840. ws.read(msg); // wait for a message
  15841. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15842. });
  15843. server_->WebSocket(
  15844. "/ws-subprotocol",
  15845. [](const Request &, ws::WebSocket &ws) {
  15846. std::string msg;
  15847. while (ws.read(msg)) {
  15848. ws.send(msg);
  15849. }
  15850. },
  15851. [](const std::vector<std::string> &protocols) -> std::string {
  15852. for (const auto &p : protocols) {
  15853. if (p == "graphql-ws") { return p; }
  15854. }
  15855. return "";
  15856. });
  15857. }
  15858. void start_server() {
  15859. port_ = server_->bind_to_any_port(HOST);
  15860. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15861. server_->wait_until_ready();
  15862. }
  15863. std::unique_ptr<Server> server_;
  15864. std::thread server_thread_;
  15865. int port_ = 0;
  15866. };
  15867. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15869. "/ws-echo");
  15870. ASSERT_TRUE(client.connect());
  15871. ASSERT_TRUE(client.is_open());
  15872. ASSERT_TRUE(client.send("Hello WebSocket"));
  15873. std::string msg;
  15874. EXPECT_EQ(ws::Text, client.read(msg));
  15875. EXPECT_EQ("Hello WebSocket", msg);
  15876. client.close();
  15877. }
  15878. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15879. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15880. "/ws-echo");
  15881. ASSERT_TRUE(client.connect());
  15882. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15883. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15884. std::string msg;
  15885. EXPECT_EQ(ws::Binary, client.read(msg));
  15886. EXPECT_EQ(binary_data, msg);
  15887. client.close();
  15888. }
  15889. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15890. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15891. "/ws-echo");
  15892. ASSERT_TRUE(client.connect());
  15893. for (int i = 0; i < 10; i++) {
  15894. auto text = "message " + std::to_string(i);
  15895. ASSERT_TRUE(client.send(text));
  15896. std::string msg;
  15897. ASSERT_TRUE(client.read(msg));
  15898. EXPECT_EQ(text, msg);
  15899. }
  15900. client.close();
  15901. }
  15902. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15904. "/ws-close");
  15905. ASSERT_TRUE(client.connect());
  15906. // Send a message to trigger the server to close
  15907. ASSERT_TRUE(client.send("trigger close"));
  15908. // The server will close, so read should return false
  15909. std::string msg;
  15910. EXPECT_FALSE(client.read(msg));
  15911. EXPECT_FALSE(client.is_open());
  15912. }
  15913. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15915. "/ws-echo");
  15916. ASSERT_TRUE(client.connect());
  15917. // 128KB message
  15918. std::string large_data(128 * 1024, 'X');
  15919. ASSERT_TRUE(client.send(large_data));
  15920. std::string msg;
  15921. ASSERT_TRUE(client.read(msg));
  15922. EXPECT_EQ(large_data, msg);
  15923. client.close();
  15924. }
  15925. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15926. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15927. "/ws-echo");
  15928. ASSERT_TRUE(client.connect());
  15929. const int num_threads = 4;
  15930. std::vector<std::thread> threads;
  15931. std::atomic<int> send_count{0};
  15932. for (int t = 0; t < num_threads; t++) {
  15933. threads.emplace_back([&client, &send_count, t]() {
  15934. for (int i = 0; i < 5; i++) {
  15935. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15936. if (client.send(text)) { send_count++; }
  15937. }
  15938. });
  15939. }
  15940. for (auto &th : threads) {
  15941. th.join();
  15942. }
  15943. int received = 0;
  15944. std::string msg;
  15945. while (received < send_count.load()) {
  15946. if (!client.read(msg)) { break; }
  15947. received++;
  15948. }
  15949. EXPECT_EQ(send_count.load(), received);
  15950. client.close();
  15951. }
  15952. TEST_F(WebSocketIntegrationTest, ReadString) {
  15953. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15954. "/ws-echo-string");
  15955. ASSERT_TRUE(client.connect());
  15956. ASSERT_TRUE(client.send("hello"));
  15957. std::string msg;
  15958. ASSERT_TRUE(client.read(msg));
  15959. EXPECT_EQ("echo: hello", msg);
  15960. ASSERT_TRUE(client.send("world"));
  15961. ASSERT_TRUE(client.read(msg));
  15962. EXPECT_EQ("echo: world", msg);
  15963. client.close();
  15964. }
  15965. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15966. Headers headers = {{"X-Test-Header", "test-value"}};
  15967. ws::WebSocketClient client(
  15968. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15969. ASSERT_TRUE(client.connect());
  15970. std::string msg;
  15971. ASSERT_TRUE(client.read(msg));
  15972. EXPECT_EQ("path:/ws-request-info", msg);
  15973. ASSERT_TRUE(client.read(msg));
  15974. EXPECT_EQ("header:test-value", msg);
  15975. client.close();
  15976. }
  15977. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15978. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15979. "/ws-echo");
  15980. client.set_read_timeout(1, 0); // 1 second
  15981. ASSERT_TRUE(client.connect());
  15982. // Don't send anything — server echo handler waits for a message,
  15983. // so read() should time out and return false.
  15984. std::string msg;
  15985. EXPECT_FALSE(client.read(msg));
  15986. }
  15987. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15989. "/ws-echo");
  15990. client.set_read_timeout(5, 0);
  15991. ASSERT_TRUE(client.connect());
  15992. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15993. // The server should reject it and close the connection.
  15994. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15995. client.send(oversized);
  15996. // The server's read() should have failed due to payload limit,
  15997. // so our read() should return false (connection closed).
  15998. std::string msg;
  15999. EXPECT_FALSE(client.read(msg));
  16000. }
  16001. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16002. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16003. "/ws-echo");
  16004. client.set_read_timeout(10, 0);
  16005. ASSERT_TRUE(client.connect());
  16006. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16007. // This should succeed.
  16008. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16009. ASSERT_TRUE(client.send(at_limit));
  16010. std::string msg;
  16011. ASSERT_TRUE(client.read(msg));
  16012. EXPECT_EQ(at_limit.size(), msg.size());
  16013. client.close();
  16014. }
  16015. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16016. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16017. "/nonexistent");
  16018. EXPECT_FALSE(client.connect());
  16019. EXPECT_FALSE(client.is_open());
  16020. }
  16021. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16023. "/ws-echo");
  16024. ASSERT_TRUE(client.connect());
  16025. ASSERT_TRUE(client.send(""));
  16026. std::string msg;
  16027. EXPECT_EQ(ws::Text, client.read(msg));
  16028. EXPECT_EQ("", msg);
  16029. client.close();
  16030. }
  16031. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16032. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16033. "/ws-echo");
  16034. // First connection
  16035. ASSERT_TRUE(client.connect());
  16036. ASSERT_TRUE(client.send("first"));
  16037. std::string msg;
  16038. ASSERT_TRUE(client.read(msg));
  16039. EXPECT_EQ("first", msg);
  16040. client.close();
  16041. EXPECT_FALSE(client.is_open());
  16042. // Reconnect using the same client object
  16043. ASSERT_TRUE(client.connect());
  16044. ASSERT_TRUE(client.is_open());
  16045. ASSERT_TRUE(client.send("second"));
  16046. ASSERT_TRUE(client.read(msg));
  16047. EXPECT_EQ("second", msg);
  16048. client.close();
  16049. }
  16050. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16051. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16052. "/ws-close-status");
  16053. ASSERT_TRUE(client.connect());
  16054. // Trigger the server to close with GoingAway status
  16055. ASSERT_TRUE(client.send("trigger"));
  16056. // read() should return false after receiving the close frame
  16057. std::string msg;
  16058. EXPECT_FALSE(client.read(msg));
  16059. EXPECT_FALSE(client.is_open());
  16060. }
  16061. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16062. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16063. "/ws-echo");
  16064. ASSERT_TRUE(client.connect());
  16065. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16066. EXPECT_FALSE(client.is_open());
  16067. }
  16068. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16069. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16070. ws::WebSocketClient client(
  16071. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16072. ASSERT_TRUE(client.connect());
  16073. // Server should have selected graphql-ws
  16074. EXPECT_EQ("graphql-ws", client.subprotocol());
  16075. client.close();
  16076. }
  16077. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16078. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16079. ws::WebSocketClient client(
  16080. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16081. ASSERT_TRUE(client.connect());
  16082. // Server should not have selected any subprotocol
  16083. EXPECT_TRUE(client.subprotocol().empty());
  16084. client.close();
  16085. }
  16086. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16087. // Connect without requesting any subprotocol
  16088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16089. "/ws-subprotocol");
  16090. ASSERT_TRUE(client.connect());
  16091. EXPECT_TRUE(client.subprotocol().empty());
  16092. client.close();
  16093. }
  16094. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16095. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16096. "/ws-echo");
  16097. client.set_tcp_nodelay(true);
  16098. client.set_connection_timeout(3, 0);
  16099. bool socket_options_called = false;
  16100. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16101. ASSERT_TRUE(client.connect());
  16102. ASSERT_TRUE(client.is_open());
  16103. EXPECT_TRUE(socket_options_called);
  16104. ASSERT_TRUE(client.send("hello"));
  16105. std::string msg;
  16106. auto result = client.read(msg);
  16107. EXPECT_EQ(result, ws::ReadResult::Text);
  16108. EXPECT_EQ(msg, "hello");
  16109. client.close();
  16110. }
  16111. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16112. Server svr;
  16113. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16114. if (!req.has_header("Authorization")) {
  16115. res.status = StatusCode::Unauthorized_401;
  16116. res.set_content("Unauthorized", "text/plain");
  16117. return Server::HandlerResponse::Handled;
  16118. }
  16119. return Server::HandlerResponse::Unhandled;
  16120. });
  16121. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16122. std::string msg;
  16123. while (ws.read(msg)) {
  16124. ws.send(msg);
  16125. }
  16126. });
  16127. auto port = svr.bind_to_any_port("localhost");
  16128. std::thread t([&]() { svr.listen_after_bind(); });
  16129. svr.wait_until_ready();
  16130. // Without Authorization header - should be rejected before upgrade
  16131. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16132. EXPECT_FALSE(client1.connect());
  16133. // With Authorization header - should succeed
  16134. Headers headers = {{"Authorization", "Bearer token123"}};
  16135. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16136. headers);
  16137. ASSERT_TRUE(client2.connect());
  16138. ASSERT_TRUE(client2.send("hello"));
  16139. std::string msg;
  16140. ASSERT_TRUE(client2.read(msg));
  16141. EXPECT_EQ("hello", msg);
  16142. client2.close();
  16143. svr.stop();
  16144. t.join();
  16145. }
  16146. TEST(WebSocketTest, QueryStringInHandshake) {
  16147. Server svr;
  16148. std::mutex mtx;
  16149. std::string received_target;
  16150. std::string received_token;
  16151. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16152. {
  16153. std::lock_guard<std::mutex> lock(mtx);
  16154. received_target = req.target;
  16155. if (req.has_param("token")) {
  16156. received_token = req.get_param_value("token");
  16157. }
  16158. }
  16159. std::string msg;
  16160. while (ws.read(msg)) {
  16161. ws.send(msg);
  16162. }
  16163. });
  16164. auto port = svr.bind_to_any_port("localhost");
  16165. std::thread t([&]() { svr.listen_after_bind(); });
  16166. svr.wait_until_ready();
  16167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16168. "/ws?token=ABC&session=123");
  16169. ASSERT_TRUE(client.connect());
  16170. // Round-trip ensures the handler has run and captured the request.
  16171. ASSERT_TRUE(client.send("hello"));
  16172. std::string msg;
  16173. ASSERT_TRUE(client.read(msg));
  16174. EXPECT_EQ("hello", msg);
  16175. client.close();
  16176. {
  16177. std::lock_guard<std::mutex> lock(mtx);
  16178. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16179. EXPECT_EQ("ABC", received_token);
  16180. }
  16181. svr.stop();
  16182. t.join();
  16183. }
  16184. TEST(WebSocketTest, HostHeaderInHandshake) {
  16185. Server svr;
  16186. std::mutex mtx;
  16187. std::string received_host;
  16188. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16189. {
  16190. std::lock_guard<std::mutex> lock(mtx);
  16191. received_host = req.get_header_value("Host");
  16192. }
  16193. std::string msg;
  16194. while (ws.read(msg)) {
  16195. ws.send(msg);
  16196. }
  16197. });
  16198. auto port = svr.bind_to_any_port("localhost");
  16199. std::thread t([&]() { svr.listen_after_bind(); });
  16200. svr.wait_until_ready();
  16201. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16202. ASSERT_TRUE(client.connect());
  16203. // Round-trip ensures the handler has run and captured the request.
  16204. ASSERT_TRUE(client.send("hello"));
  16205. std::string msg;
  16206. ASSERT_TRUE(client.read(msg));
  16207. client.close();
  16208. {
  16209. std::lock_guard<std::mutex> lock(mtx);
  16210. // Non-default port must be present in the Host header. Default ports
  16211. // (80/443) are omitted; that logic is covered by
  16212. // MakeHostAndPortStringTest.
  16213. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16214. }
  16215. svr.stop();
  16216. t.join();
  16217. }
  16218. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16219. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16220. protected:
  16221. void SetUp() override {
  16222. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16223. SERVER_PRIVATE_KEY_FILE);
  16224. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16225. std::string msg;
  16226. ws::ReadResult ret;
  16227. while ((ret = ws.read(msg))) {
  16228. if (ret == ws::Binary) {
  16229. ws.send(msg.data(), msg.size());
  16230. } else {
  16231. ws.send(msg);
  16232. }
  16233. }
  16234. });
  16235. port_ = server_->bind_to_any_port(HOST);
  16236. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16237. server_->wait_until_ready();
  16238. }
  16239. void TearDown() override {
  16240. server_->stop();
  16241. if (server_thread_.joinable()) { server_thread_.join(); }
  16242. }
  16243. std::unique_ptr<SSLServer> server_;
  16244. std::thread server_thread_;
  16245. int port_ = 0;
  16246. };
  16247. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16248. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16249. "/ws-echo");
  16250. client.enable_server_certificate_verification(false);
  16251. ASSERT_TRUE(client.connect());
  16252. ASSERT_TRUE(client.is_open());
  16253. ASSERT_TRUE(client.send("Hello WSS"));
  16254. std::string msg;
  16255. EXPECT_EQ(ws::Text, client.read(msg));
  16256. EXPECT_EQ("Hello WSS", msg);
  16257. client.close();
  16258. }
  16259. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16260. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16261. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16262. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16263. // client (without calling close() first) is the only path that runs
  16264. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16265. // bug exactly.
  16266. //
  16267. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16268. // when linked against an instrumented libssl; run under Valgrind to catch it
  16269. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16270. // suite (the freed session otherwise stalls on the close handshake) — this test
  16271. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16272. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16273. {
  16274. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16275. "/ws-echo");
  16276. client.enable_server_certificate_verification(false);
  16277. client.set_read_timeout(2, 0);
  16278. client.set_write_timeout(2, 0);
  16279. ASSERT_TRUE(client.connect());
  16280. ASSERT_TRUE(client.is_open());
  16281. ASSERT_TRUE(client.send("still open"));
  16282. // Intentionally do NOT call client.close(): leaving scope runs
  16283. // shutdown_and_close() with the WebSocket still open, which must send the
  16284. // close frame while the TLS session is still alive.
  16285. }
  16286. }
  16287. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16288. // shutdown_and_close() at the start of connect(), reproducing the same
  16289. // use-after-free within the test body rather than at scope exit. The second
  16290. // connect must succeed and echo, proving the close handshake ran over a live
  16291. // session. See the note above about memory-tool requirements.
  16292. TEST_F(WebSocketSSLIntegrationTest,
  16293. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16294. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16295. "/ws-echo");
  16296. client.enable_server_certificate_verification(false);
  16297. client.set_read_timeout(2, 0);
  16298. client.set_write_timeout(2, 0);
  16299. ASSERT_TRUE(client.connect());
  16300. ASSERT_TRUE(client.is_open());
  16301. ASSERT_TRUE(client.send("still open"));
  16302. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16303. // the still-open connection, which must not touch a freed TLS session.
  16304. ASSERT_TRUE(client.connect());
  16305. ASSERT_TRUE(client.is_open());
  16306. ASSERT_TRUE(client.send("after reconnect"));
  16307. std::string msg;
  16308. EXPECT_EQ(ws::Text, client.read(msg));
  16309. EXPECT_EQ("after reconnect", msg);
  16310. client.close();
  16311. }
  16312. #endif
  16313. #ifdef CPPHTTPLIB_SSL_ENABLED
  16314. class WebSocketSSLCATest : public ::testing::Test {
  16315. protected:
  16316. void SetUp() override {
  16317. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16318. SERVER_PRIVATE_KEY_FILE);
  16319. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16320. std::string msg;
  16321. while (ws.read(msg)) {
  16322. ws.send(msg);
  16323. }
  16324. });
  16325. port_ = server_->bind_to_any_port("127.0.0.1");
  16326. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16327. server_->wait_until_ready();
  16328. }
  16329. void TearDown() override {
  16330. server_->stop();
  16331. if (server_thread_.joinable()) { server_thread_.join(); }
  16332. }
  16333. std::string url() const {
  16334. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16335. }
  16336. std::unique_ptr<SSLServer> server_;
  16337. std::thread server_thread_;
  16338. int port_ = 0;
  16339. };
  16340. // A custom CA loaded as PEM verifies the server with full certificate
  16341. // verification enabled
  16342. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16343. ws::WebSocketClient client(url());
  16344. std::string cert;
  16345. read_file(SERVER_CERT2_FILE, cert);
  16346. client.load_ca_cert_store(cert.c_str(), cert.size());
  16347. ASSERT_TRUE(client.connect());
  16348. ASSERT_TRUE(client.send("hello"));
  16349. std::string msg;
  16350. EXPECT_EQ(ws::Text, client.read(msg));
  16351. EXPECT_EQ("hello", msg);
  16352. client.close();
  16353. }
  16354. // A custom CA that does not cover the server must fail verification (the
  16355. // custom CA is exclusive; system certs are not loaded alongside it)
  16356. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16357. ws::WebSocketClient client(url());
  16358. std::string cert;
  16359. read_file(CLIENT_CA_CERT_FILE, cert);
  16360. client.load_ca_cert_store(cert.c_str(), cert.size());
  16361. ASSERT_FALSE(client.connect());
  16362. }
  16363. // Regression test: reconnecting with a native custom CA store used to reuse
  16364. // a store handle the previous TLS context had already freed (use-after-free
  16365. // under the OpenSSL backend). The context now lives as long as the client.
  16366. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16367. ws::WebSocketClient client(url());
  16368. std::string cert;
  16369. read_file(SERVER_CERT2_FILE, cert);
  16370. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16371. ASSERT_TRUE(client.connect());
  16372. client.close();
  16373. ASSERT_TRUE(client.connect());
  16374. ASSERT_TRUE(client.send("again"));
  16375. std::string msg;
  16376. EXPECT_EQ(ws::Text, client.read(msg));
  16377. EXPECT_EQ("again", msg);
  16378. client.close();
  16379. }
  16380. // Regression test: a certificate with a trusted chain but no identity match
  16381. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16382. // verification entirely for IP hosts, so this connection succeeded there.
  16383. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16384. // chain verification while the identity check must still fail.
  16385. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16387. ASSERT_TRUE(svr.is_valid());
  16388. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16389. std::string msg;
  16390. while (ws.read(msg)) {
  16391. ws.send(msg);
  16392. }
  16393. });
  16394. auto port = svr.bind_to_any_port("127.0.0.1");
  16395. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16396. auto se = detail::scope_exit([&] {
  16397. svr.stop();
  16398. t.join();
  16399. });
  16400. svr.wait_until_ready();
  16401. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16402. "/echo");
  16403. std::string cert;
  16404. read_file(SERVER_CERT_FILE, cert);
  16405. client.load_ca_cert_store(cert.c_str(), cert.size());
  16406. ASSERT_FALSE(client.connect());
  16407. }
  16408. #endif
  16409. #if !defined(_WIN32)
  16410. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16411. auto secret_dir = std::string("./symlink_test_secret");
  16412. auto served_dir = std::string("./symlink_test_served");
  16413. auto secret_file = secret_dir + "/secret.txt";
  16414. auto symlink_path = served_dir + "/escape";
  16415. // Setup: create directories and files
  16416. mkdir(secret_dir.c_str(), 0755);
  16417. mkdir(served_dir.c_str(), 0755);
  16418. {
  16419. std::ofstream ofs(secret_file);
  16420. ofs << "SECRET_DATA";
  16421. }
  16422. // Create symlink using absolute path so it resolves correctly
  16423. #ifdef PATH_MAX
  16424. char abs_secret[PATH_MAX];
  16425. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16426. #else
  16427. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16428. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16429. ASSERT_NE(nullptr, abs_secret);
  16430. #endif
  16431. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16432. auto se = detail::scope_exit([&] {
  16433. unlink(symlink_path.c_str());
  16434. unlink(secret_file.c_str());
  16435. rmdir(served_dir.c_str());
  16436. rmdir(secret_dir.c_str());
  16437. });
  16438. Server svr;
  16439. svr.set_mount_point("/", served_dir);
  16440. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16441. auto se2 = detail::scope_exit([&] {
  16442. svr.stop();
  16443. listen_thread.join();
  16444. });
  16445. svr.wait_until_ready();
  16446. Client cli("localhost", PORT);
  16447. // Symlink pointing outside base dir should be blocked
  16448. auto res = cli.Get("/escape/secret.txt");
  16449. ASSERT_TRUE(res);
  16450. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16451. }
  16452. #endif
  16453. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16454. // A GET request with Content-Length to a static file handler must have its
  16455. // body drained before the keep-alive connection is reused. Otherwise the
  16456. // unread body bytes are interpreted as the next HTTP request.
  16457. //
  16458. // The body is sent AFTER receiving the first response (as in the original
  16459. // PoC) so that the stream_line_reader cannot buffer it together with the
  16460. // headers of the first request.
  16461. Server svr;
  16462. svr.set_mount_point("/", "./www");
  16463. std::atomic<int> smuggled_count(0);
  16464. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16465. smuggled_count++;
  16466. res.set_content("oops", "text/plain");
  16467. });
  16468. auto port = svr.bind_to_any_port("localhost");
  16469. thread t = thread([&] { svr.listen_after_bind(); });
  16470. auto se = detail::scope_exit([&] {
  16471. svr.stop();
  16472. t.join();
  16473. });
  16474. svr.wait_until_ready();
  16475. auto error = Error::Success;
  16476. auto sock = detail::create_client_socket(
  16477. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16478. /*connection_timeout_sec=*/2, 0,
  16479. /*read_timeout_sec=*/2, 0,
  16480. /*write_timeout_sec=*/2, 0, std::string(), error);
  16481. ASSERT_NE(INVALID_SOCKET, sock);
  16482. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16483. // The "smuggled" request will be sent as the body of the outer GET
  16484. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16485. "Host: localhost\r\n"
  16486. "Connection: close\r\n"
  16487. "\r\n";
  16488. // Step 1: Send only the outer request headers (no body yet)
  16489. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16490. "Host: localhost\r\n"
  16491. "Content-Length: " +
  16492. std::to_string(smuggled.size()) +
  16493. "\r\n"
  16494. "\r\n";
  16495. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16496. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16497. // Step 2: Read the first response (server serves file without reading body)
  16498. std::string first_response;
  16499. char buf[4096];
  16500. for (;;) {
  16501. auto n = recv(sock, buf, sizeof(buf), 0);
  16502. if (n <= 0) break;
  16503. first_response.append(buf, static_cast<size_t>(n));
  16504. // Stop once we have a complete response (headers + body)
  16505. auto hdr_end = first_response.find("\r\n\r\n");
  16506. if (hdr_end != std::string::npos) {
  16507. // Check for Content-Length to know when the body is complete
  16508. auto cl_pos = first_response.find("Content-Length:");
  16509. if (cl_pos != std::string::npos) {
  16510. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16511. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16512. auto cl = std::stoul(
  16513. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16514. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16515. } else {
  16516. break; // No Content-Length, assume headers-only response
  16517. }
  16518. }
  16519. }
  16520. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16521. // Step 3: Now send the body, which looks like a new HTTP request.
  16522. // On a vulnerable server the keep-alive loop reads this as a second request.
  16523. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16524. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16525. // Step 4: Try to read a second response (should NOT exist after fix)
  16526. std::string second_response;
  16527. for (;;) {
  16528. auto n = recv(sock, buf, sizeof(buf), 0);
  16529. if (n <= 0) break;
  16530. second_response.append(buf, static_cast<size_t>(n));
  16531. }
  16532. // The smuggled request must NOT have been processed
  16533. EXPECT_EQ(0, smuggled_count.load());
  16534. }
  16535. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16536. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16537. // must be rejected with 400 Bad Request.
  16538. Server svr;
  16539. svr.Post("/test", [&](const Request &, Response &res) {
  16540. res.set_content("ok", "text/plain");
  16541. });
  16542. thread t = thread([&] { svr.listen(HOST, PORT); });
  16543. auto se = detail::scope_exit([&] {
  16544. svr.stop();
  16545. t.join();
  16546. ASSERT_FALSE(svr.is_running());
  16547. });
  16548. svr.wait_until_ready();
  16549. // Exact "chunked"
  16550. {
  16551. auto req = "POST /test HTTP/1.1\r\n"
  16552. "Host: localhost\r\n"
  16553. "Content-Length: 5\r\n"
  16554. "Transfer-Encoding: chunked\r\n"
  16555. "Connection: close\r\n"
  16556. "\r\n"
  16557. "hello";
  16558. std::string response;
  16559. ASSERT_TRUE(send_request(1, req, &response));
  16560. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16561. response.substr(0, response.find("\r\n")));
  16562. }
  16563. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16564. {
  16565. auto req = "POST /test HTTP/1.1\r\n"
  16566. "Host: localhost\r\n"
  16567. "Content-Length: 5\r\n"
  16568. "Transfer-Encoding: gzip, chunked\r\n"
  16569. "Connection: close\r\n"
  16570. "\r\n"
  16571. "hello";
  16572. std::string response;
  16573. ASSERT_TRUE(send_request(1, req, &response));
  16574. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16575. response.substr(0, response.find("\r\n")));
  16576. }
  16577. }
  16578. // Regression for issue #2450: a DELETE without Content-Length on a
  16579. // keep-alive connection must not let the post-response drain consume the
  16580. // next request's bytes.
  16581. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16582. Server svr;
  16583. std::atomic<int> delete_count(0);
  16584. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16585. delete_count++;
  16586. res.status = StatusCode::NoContent_204;
  16587. });
  16588. auto port = svr.bind_to_any_port(HOST);
  16589. thread t = thread([&] { svr.listen_after_bind(); });
  16590. auto se = detail::scope_exit([&] {
  16591. svr.stop();
  16592. t.join();
  16593. });
  16594. svr.wait_until_ready();
  16595. auto error = Error::Success;
  16596. auto sock = detail::create_client_socket(
  16597. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16598. /*connection_timeout_sec=*/2, 0,
  16599. /*read_timeout_sec=*/2, 0,
  16600. /*write_timeout_sec=*/2, 0, std::string(), error);
  16601. ASSERT_NE(INVALID_SOCKET, sock);
  16602. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16603. auto send_request_and_read_response = [&](const std::string &req,
  16604. std::string &out) -> bool {
  16605. auto sent = send(sock, req.data(), req.size(), 0);
  16606. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16607. char buf[4096];
  16608. for (;;) {
  16609. auto n = recv(sock, buf, sizeof(buf), 0);
  16610. if (n <= 0) { return !out.empty(); }
  16611. out.append(buf, static_cast<size_t>(n));
  16612. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16613. }
  16614. };
  16615. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16616. "Host: localhost\r\n"
  16617. "\r\n";
  16618. std::string resp1;
  16619. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16620. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16621. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16622. "Host: localhost\r\n"
  16623. "Connection: close\r\n"
  16624. "\r\n";
  16625. std::string resp2;
  16626. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16627. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16628. EXPECT_EQ(2, delete_count.load());
  16629. }
  16630. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  16631. Server svr;
  16632. svr.Post("/ingest", [&](const Request &, Response &res,
  16633. const ContentReader &content_reader) {
  16634. auto consumed =
  16635. content_reader([](const char *, size_t) { return false; });
  16636. EXPECT_FALSE(consumed);
  16637. res.status = StatusCode::Conflict_409;
  16638. res.set_header("Connection", "close");
  16639. });
  16640. auto port = svr.bind_to_any_port(HOST);
  16641. thread t = thread([&] { svr.listen_after_bind(); });
  16642. auto se = detail::scope_exit([&] {
  16643. svr.stop();
  16644. t.join();
  16645. });
  16646. svr.wait_until_ready();
  16647. auto error = Error::Success;
  16648. auto sock = detail::create_client_socket(
  16649. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16650. /*connection_timeout_sec=*/2, 0,
  16651. /*read_timeout_sec=*/1, 0,
  16652. /*write_timeout_sec=*/2, 0, std::string(), error);
  16653. ASSERT_NE(INVALID_SOCKET, sock);
  16654. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16655. std::string request = "POST /ingest HTTP/1.1\r\n"
  16656. "Host: localhost\r\n"
  16657. "Transfer-Encoding: chunked\r\n"
  16658. "\r\n"
  16659. "4\r\n"
  16660. "data\r\n";
  16661. auto sent = send(sock, request.data(), request.size(), 0);
  16662. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  16663. std::string response;
  16664. ssize_t received = 0;
  16665. do {
  16666. char buf[4096];
  16667. received = recv(sock, buf, sizeof(buf), 0);
  16668. if (received > 0) {
  16669. response.append(buf, static_cast<size_t>(received));
  16670. }
  16671. } while (received > 0);
  16672. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  16673. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  16674. EXPECT_EQ(0, received);
  16675. }
  16676. namespace no_proxy_test {
  16677. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16678. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16679. // calling listen().
  16680. class ScopedServer {
  16681. public:
  16682. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16683. ~ScopedServer() {
  16684. svr_.stop();
  16685. if (th_.joinable()) { th_.join(); }
  16686. }
  16687. Server &svr() { return svr_; }
  16688. int port() const { return port_; }
  16689. void listen() {
  16690. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16691. svr_.wait_until_ready();
  16692. }
  16693. private:
  16694. Server svr_;
  16695. std::thread th_;
  16696. int port_ = 0;
  16697. };
  16698. class ProxyAndTargetServers {
  16699. public:
  16700. ProxyAndTargetServers() {
  16701. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16702. proxy_hits_++;
  16703. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16704. res.set_content("via-proxy", "text/plain");
  16705. });
  16706. target_.Get(".*", [this](const Request &req, Response &res) {
  16707. target_hits_++;
  16708. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16709. res.set_content("direct", "text/plain");
  16710. });
  16711. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16712. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16713. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16714. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16715. proxy_mock_.wait_until_ready();
  16716. target_.wait_until_ready();
  16717. }
  16718. ~ProxyAndTargetServers() {
  16719. proxy_mock_.stop();
  16720. target_.stop();
  16721. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16722. if (target_thread_.joinable()) { target_thread_.join(); }
  16723. }
  16724. Server &proxy_mock() { return proxy_mock_; }
  16725. Server &target() { return target_; }
  16726. int proxy_port() const { return proxy_port_; }
  16727. int target_port() const { return target_port_; }
  16728. int proxy_hits() const { return proxy_hits_.load(); }
  16729. int target_hits() const { return target_hits_.load(); }
  16730. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16731. void reset_counters() {
  16732. proxy_hits_ = 0;
  16733. target_hits_ = 0;
  16734. last_had_proxy_authz_ = false;
  16735. }
  16736. private:
  16737. Server proxy_mock_;
  16738. Server target_;
  16739. std::thread proxy_thread_;
  16740. std::thread target_thread_;
  16741. int proxy_port_ = 0;
  16742. int target_port_ = 0;
  16743. std::atomic<int> proxy_hits_{0};
  16744. std::atomic<int> target_hits_{0};
  16745. std::atomic<bool> last_had_proxy_authz_{false};
  16746. };
  16747. inline std::unique_ptr<Client> make_client(const std::string &host,
  16748. ProxyAndTargetServers &s) {
  16749. auto cli = detail::make_unique<Client>(host, s.target_port());
  16750. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16751. cli->set_proxy("127.0.0.1", s.proxy_port());
  16752. return cli;
  16753. }
  16754. } // namespace no_proxy_test
  16755. using no_proxy_test::make_client;
  16756. using no_proxy_test::ProxyAndTargetServers;
  16757. TEST(NoProxyTest, ExactHostnameBypasses) {
  16758. ProxyAndTargetServers s;
  16759. auto cli = make_client("example.com", s);
  16760. cli->set_no_proxy({"example.com"});
  16761. auto res = cli->Get("/");
  16762. ASSERT_TRUE(res);
  16763. EXPECT_EQ(0, s.proxy_hits());
  16764. EXPECT_EQ(1, s.target_hits());
  16765. }
  16766. TEST(NoProxyTest, SubdomainBypasses) {
  16767. ProxyAndTargetServers s;
  16768. auto cli = make_client("foo.example.com", s);
  16769. cli->set_no_proxy({"example.com"});
  16770. auto res = cli->Get("/");
  16771. ASSERT_TRUE(res);
  16772. EXPECT_EQ(0, s.proxy_hits());
  16773. EXPECT_EQ(1, s.target_hits());
  16774. }
  16775. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16776. // Regression guard: "evilexample.com" must not be considered a subdomain
  16777. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16778. // check would let traffic bypass the proxy and leak credentials direct
  16779. // to the attacker host.
  16780. ProxyAndTargetServers s;
  16781. auto cli = make_client("evilexample.com", s);
  16782. cli->set_no_proxy({"example.com"});
  16783. auto res = cli->Get("/");
  16784. ASSERT_TRUE(res);
  16785. EXPECT_GE(s.proxy_hits(), 1);
  16786. EXPECT_EQ(0, s.target_hits());
  16787. }
  16788. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16789. ProxyAndTargetServers s;
  16790. auto cli = make_client("example.com.evil.com", s);
  16791. cli->set_no_proxy({"example.com"});
  16792. auto res = cli->Get("/");
  16793. ASSERT_TRUE(res);
  16794. EXPECT_GE(s.proxy_hits(), 1);
  16795. EXPECT_EQ(0, s.target_hits());
  16796. }
  16797. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16798. ProxyAndTargetServers s;
  16799. auto cli = make_client("example.com", s);
  16800. cli->set_no_proxy({".example.com"});
  16801. auto res = cli->Get("/");
  16802. ASSERT_TRUE(res);
  16803. EXPECT_EQ(0, s.proxy_hits());
  16804. EXPECT_EQ(1, s.target_hits());
  16805. }
  16806. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16807. ProxyAndTargetServers s;
  16808. auto cli = make_client("Example.COM", s);
  16809. cli->set_no_proxy({"EXAMPLE.com"});
  16810. auto res = cli->Get("/");
  16811. ASSERT_TRUE(res);
  16812. EXPECT_EQ(0, s.proxy_hits());
  16813. EXPECT_EQ(1, s.target_hits());
  16814. }
  16815. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16816. ProxyAndTargetServers s;
  16817. auto cli = make_client("example.com.", s);
  16818. cli->set_no_proxy({"example.com"});
  16819. auto res = cli->Get("/");
  16820. ASSERT_TRUE(res);
  16821. EXPECT_EQ(0, s.proxy_hits());
  16822. EXPECT_EQ(1, s.target_hits());
  16823. }
  16824. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16825. // Trailing dots must be normalized on BOTH sides — host and entry.
  16826. // An implementation that only strips the host-side trailing dot would
  16827. // fail to match host "example.com" against entry "example.com." because
  16828. // a literal substring search would compare 11 chars against 12.
  16829. ProxyAndTargetServers s;
  16830. auto cli = make_client("example.com", s);
  16831. cli->set_no_proxy({"example.com."});
  16832. auto res = cli->Get("/");
  16833. ASSERT_TRUE(res);
  16834. EXPECT_EQ(0, s.proxy_hits());
  16835. EXPECT_EQ(1, s.target_hits());
  16836. }
  16837. TEST(NoProxyTest, WildcardBypassesEverything) {
  16838. ProxyAndTargetServers s;
  16839. auto cli = make_client("anything.invalid.test", s);
  16840. cli->set_no_proxy({"*"});
  16841. auto res = cli->Get("/");
  16842. ASSERT_TRUE(res);
  16843. EXPECT_EQ(0, s.proxy_hits());
  16844. EXPECT_EQ(1, s.target_hits());
  16845. }
  16846. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16847. ProxyAndTargetServers s;
  16848. Client cli("127.0.0.1", s.target_port());
  16849. cli.set_proxy("127.0.0.1", s.proxy_port());
  16850. cli.set_no_proxy({"127.0.0.1"});
  16851. auto res = cli.Get("/");
  16852. ASSERT_TRUE(res);
  16853. EXPECT_EQ(0, s.proxy_hits());
  16854. EXPECT_EQ(1, s.target_hits());
  16855. }
  16856. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16857. ProxyAndTargetServers s;
  16858. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16859. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16860. cli.set_proxy("127.0.0.1", s.proxy_port());
  16861. cli.set_no_proxy({"::1"});
  16862. auto res = cli.Get("/");
  16863. ASSERT_TRUE(res);
  16864. EXPECT_EQ(0, s.proxy_hits());
  16865. EXPECT_EQ(1, s.target_hits());
  16866. }
  16867. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16868. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16869. // must still be recognized as IPv6 for CIDR matching. Implementations
  16870. // that detect IPv6 only when the host begins with '[' would parse the
  16871. // host as a hostname and miss the match.
  16872. ProxyAndTargetServers s;
  16873. Client cli("fe80::1", s.target_port());
  16874. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16875. cli.set_proxy("127.0.0.1", s.proxy_port());
  16876. cli.set_no_proxy({"fe80::/10"});
  16877. auto res = cli.Get("/");
  16878. ASSERT_TRUE(res);
  16879. EXPECT_EQ(0, s.proxy_hits());
  16880. EXPECT_EQ(1, s.target_hits());
  16881. }
  16882. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16883. ProxyAndTargetServers s;
  16884. Client cli("::1", s.target_port());
  16885. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16886. cli.set_proxy("127.0.0.1", s.proxy_port());
  16887. cli.set_no_proxy({"[::1]"});
  16888. auto res = cli.Get("/");
  16889. ASSERT_TRUE(res);
  16890. EXPECT_EQ(0, s.proxy_hits());
  16891. EXPECT_EQ(1, s.target_hits());
  16892. }
  16893. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16894. ProxyAndTargetServers s;
  16895. Client cli("fe80::1", s.target_port());
  16896. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16897. cli.set_proxy("127.0.0.1", s.proxy_port());
  16898. cli.set_no_proxy({"[fe80::]/10"});
  16899. auto res = cli.Get("/");
  16900. ASSERT_TRUE(res);
  16901. EXPECT_EQ(0, s.proxy_hits());
  16902. EXPECT_EQ(1, s.target_hits());
  16903. }
  16904. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16905. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16906. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16907. // tricks via address-family conversion.
  16908. ProxyAndTargetServers s;
  16909. Client cli("::ffff:127.0.0.1", s.target_port());
  16910. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16911. cli.set_proxy("127.0.0.1", s.proxy_port());
  16912. cli.set_no_proxy({"127.0.0.1"});
  16913. auto res = cli.Get("/");
  16914. ASSERT_TRUE(res);
  16915. EXPECT_GE(s.proxy_hits(), 1);
  16916. EXPECT_EQ(0, s.target_hits());
  16917. }
  16918. TEST(NoProxyTest, IPv4CidrMatch) {
  16919. ProxyAndTargetServers s;
  16920. Client cli("127.0.0.1", s.target_port());
  16921. cli.set_proxy("127.0.0.1", s.proxy_port());
  16922. cli.set_no_proxy({"127.0.0.0/8"});
  16923. auto res = cli.Get("/");
  16924. ASSERT_TRUE(res);
  16925. EXPECT_EQ(0, s.proxy_hits());
  16926. EXPECT_EQ(1, s.target_hits());
  16927. }
  16928. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16929. ProxyAndTargetServers s;
  16930. Client cli("127.0.0.1", s.target_port());
  16931. cli.set_proxy("127.0.0.1", s.proxy_port());
  16932. cli.set_no_proxy({"10.0.0.0/8"});
  16933. auto res = cli.Get("/");
  16934. ASSERT_TRUE(res);
  16935. EXPECT_GE(s.proxy_hits(), 1);
  16936. EXPECT_EQ(0, s.target_hits());
  16937. }
  16938. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16939. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16940. // IPv4 target matches.
  16941. ProxyAndTargetServers s;
  16942. Client cli("127.0.0.1", s.target_port());
  16943. cli.set_proxy("127.0.0.1", s.proxy_port());
  16944. cli.set_no_proxy({"0.0.0.0/0"});
  16945. auto res = cli.Get("/");
  16946. ASSERT_TRUE(res);
  16947. EXPECT_EQ(0, s.proxy_hits());
  16948. EXPECT_EQ(1, s.target_hits());
  16949. }
  16950. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16951. ProxyAndTargetServers s;
  16952. Client cli("127.0.0.1", s.target_port());
  16953. cli.set_proxy("127.0.0.1", s.proxy_port());
  16954. cli.set_no_proxy({"127.0.0.1"});
  16955. auto res = cli.Get("/");
  16956. ASSERT_TRUE(res);
  16957. EXPECT_EQ(0, s.proxy_hits());
  16958. EXPECT_EQ(1, s.target_hits());
  16959. }
  16960. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16961. ProxyAndTargetServers s;
  16962. Client cli("127.0.0.1", s.target_port());
  16963. cli.set_proxy("127.0.0.1", s.proxy_port());
  16964. cli.set_no_proxy({"127.0.0.0/33"});
  16965. auto res = cli.Get("/");
  16966. ASSERT_TRUE(res);
  16967. EXPECT_GE(s.proxy_hits(), 1);
  16968. EXPECT_EQ(0, s.target_hits());
  16969. }
  16970. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16971. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16972. ProxyAndTargetServers s;
  16973. Client cli("127.0.0.1", s.target_port());
  16974. cli.set_proxy("127.0.0.1", s.proxy_port());
  16975. cli.set_no_proxy({"127.0.0.1/"});
  16976. auto res = cli.Get("/");
  16977. ASSERT_TRUE(res);
  16978. EXPECT_GE(s.proxy_hits(), 1);
  16979. EXPECT_EQ(0, s.target_hits());
  16980. }
  16981. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16982. ProxyAndTargetServers s;
  16983. auto cli = make_client("internal.corp", s);
  16984. cli->set_proxy_basic_auth("u", "p");
  16985. cli->set_no_proxy({"internal.corp"});
  16986. auto res = cli->Get("/");
  16987. ASSERT_TRUE(res);
  16988. EXPECT_EQ(1, s.target_hits());
  16989. EXPECT_EQ(0, s.proxy_hits());
  16990. EXPECT_FALSE(s.last_had_proxy_authz())
  16991. << "Proxy-Authorization must not be sent direct to the target";
  16992. }
  16993. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16994. ProxyAndTargetServers s;
  16995. auto cli = make_client("public.example", s);
  16996. cli->set_proxy_basic_auth("u", "p");
  16997. cli->set_no_proxy({"internal.corp"}); // does not match
  16998. auto res = cli->Get("/");
  16999. ASSERT_TRUE(res);
  17000. EXPECT_GE(s.proxy_hits(), 1);
  17001. EXPECT_TRUE(s.last_had_proxy_authz());
  17002. }
  17003. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17004. ProxyAndTargetServers s;
  17005. auto cli = make_client("anything.test", s);
  17006. auto res = cli->Get("/");
  17007. ASSERT_TRUE(res);
  17008. EXPECT_GE(s.proxy_hits(), 1);
  17009. EXPECT_EQ(0, s.target_hits());
  17010. }
  17011. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17012. ProxyAndTargetServers s;
  17013. auto cli = make_client("example.com", s);
  17014. cli->set_no_proxy({"example.com:8080"});
  17015. auto res = cli->Get("/");
  17016. ASSERT_TRUE(res);
  17017. EXPECT_GE(s.proxy_hits(), 1);
  17018. EXPECT_EQ(0, s.target_hits());
  17019. }
  17020. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17021. ProxyAndTargetServers s;
  17022. auto cli = make_client("anything.test", s);
  17023. cli->set_no_proxy({"", " ", "\t"});
  17024. auto res = cli->Get("/");
  17025. ASSERT_TRUE(res);
  17026. EXPECT_GE(s.proxy_hits(), 1);
  17027. EXPECT_EQ(0, s.target_hits());
  17028. }
  17029. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17030. // An entry with leading/trailing whitespace must still match — env-style
  17031. // values are commonly pasted with stray spaces and an implementation
  17032. // that feeds the raw token directly to inet_pton would fail to match
  17033. // valid CIDRs because of the spaces.
  17034. ProxyAndTargetServers s;
  17035. Client cli("127.0.0.1", s.target_port());
  17036. cli.set_proxy("127.0.0.1", s.proxy_port());
  17037. cli.set_no_proxy({" 127.0.0.0/8 "});
  17038. auto res = cli.Get("/");
  17039. ASSERT_TRUE(res);
  17040. EXPECT_EQ(0, s.proxy_hits());
  17041. EXPECT_EQ(1, s.target_hits());
  17042. }
  17043. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17044. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17045. // go direct and must NOT carry Proxy-Authorization.
  17046. std::atomic<int> proxy_hits{0};
  17047. std::atomic<int> target_hits{0};
  17048. std::atomic<bool> target_saw_authz{false};
  17049. no_proxy_test::ScopedServer proxy_mock, target;
  17050. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17051. proxy_hits++;
  17052. res.status = 302;
  17053. res.set_header("Location", "http://127.0.0.1:" +
  17054. std::to_string(target.port()) + "/landed");
  17055. });
  17056. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17057. target_hits++;
  17058. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17059. res.set_content("direct", "text/plain");
  17060. });
  17061. proxy_mock.listen();
  17062. target.listen();
  17063. Client cli("public.example", target.port());
  17064. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17065. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17066. cli.set_proxy_basic_auth("u", "p");
  17067. cli.set_no_proxy({"127.0.0.1"});
  17068. cli.set_follow_location(true);
  17069. auto res = cli.Get("/redir");
  17070. ASSERT_TRUE(res);
  17071. EXPECT_GE(proxy_hits.load(), 1);
  17072. EXPECT_GE(target_hits.load(), 1);
  17073. EXPECT_FALSE(target_saw_authz.load());
  17074. }
  17075. #ifdef CPPHTTPLIB_SSL_ENABLED
  17076. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17077. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17078. // proxy creds would be sent to the (possibly hostile) origin.
  17079. std::atomic<int> target_hits{0};
  17080. std::atomic<bool> target_saw_proxy_authz{false};
  17081. no_proxy_test::ScopedServer target;
  17082. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17083. target_hits++;
  17084. if (req.has_header("Proxy-Authorization")) {
  17085. target_saw_proxy_authz = true;
  17086. }
  17087. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17088. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17089. "nonce=\"abc\", algorithm=MD5");
  17090. });
  17091. target.listen();
  17092. // The proxy address is set to the target's port: the bypass MUST kick in;
  17093. // if it doesn't, the test still routes "via proxy" to the same server and
  17094. // the Proxy-Authorization assertion below catches the leak.
  17095. Client cli("evil.example", target.port());
  17096. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17097. cli.set_proxy("127.0.0.1", target.port());
  17098. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17099. cli.set_no_proxy({"evil.example"});
  17100. auto res = cli.Get("/x");
  17101. ASSERT_TRUE(res);
  17102. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17103. EXPECT_EQ(1, target_hits.load());
  17104. EXPECT_FALSE(target_saw_proxy_authz.load());
  17105. }
  17106. #endif
  17107. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17108. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17109. std::atomic<int> proxy_hits{0};
  17110. std::atomic<int> bypass_hits{0};
  17111. std::atomic<bool> proxy_saw_c_url{false};
  17112. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17113. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17114. proxy_hits++;
  17115. if (req.path.find("/start") != std::string::npos) {
  17116. res.status = 302;
  17117. res.set_header("Location", "http://127.0.0.1:" +
  17118. std::to_string(bypass_server.port()) +
  17119. "/middle");
  17120. return;
  17121. }
  17122. if (req.path.find("/end") != std::string::npos) {
  17123. proxy_saw_c_url = true;
  17124. res.set_content("c-via-proxy", "text/plain");
  17125. return;
  17126. }
  17127. res.set_content("unexpected", "text/plain");
  17128. });
  17129. // public.example's "advertised" port is arbitrary (the request never lands
  17130. // there — it goes through the proxy), but use a dynamic value to stay
  17131. // friendly with sharded parallel runs.
  17132. int public_port = bypass_server.port();
  17133. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17134. bypass_hits++;
  17135. res.status = 302;
  17136. res.set_header("Location", "http://public.example:" +
  17137. std::to_string(public_port) + "/end");
  17138. });
  17139. proxy_mock.listen();
  17140. bypass_server.listen();
  17141. Client cli("public.example", public_port);
  17142. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17143. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17144. cli.set_no_proxy({"127.0.0.1"});
  17145. cli.set_follow_location(true);
  17146. auto res = cli.Get("/start");
  17147. ASSERT_TRUE(res);
  17148. EXPECT_EQ(StatusCode::OK_200, res->status);
  17149. EXPECT_EQ("c-via-proxy", res->body);
  17150. EXPECT_GE(proxy_hits.load(), 2);
  17151. EXPECT_GE(bypass_hits.load(), 1);
  17152. EXPECT_TRUE(proxy_saw_c_url.load());
  17153. }
  17154. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17155. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17156. // request reconnects to the correct endpoint.
  17157. std::atomic<int> proxy_hits{0};
  17158. std::atomic<int> target_hits{0};
  17159. no_proxy_test::ScopedServer proxy_mock, target;
  17160. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17161. proxy_hits++;
  17162. res.set_content("via-proxy", "text/plain");
  17163. });
  17164. target.svr().Get(".*", [&](const Request &, Response &res) {
  17165. target_hits++;
  17166. res.set_content("direct", "text/plain");
  17167. });
  17168. proxy_mock.listen();
  17169. target.listen();
  17170. Client cli("public.example", target.port());
  17171. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17172. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17173. cli.set_keep_alive(true);
  17174. auto res1 = cli.Get("/a");
  17175. ASSERT_TRUE(res1);
  17176. EXPECT_EQ("via-proxy", res1->body);
  17177. EXPECT_EQ(1, proxy_hits.load());
  17178. EXPECT_EQ(0, target_hits.load());
  17179. cli.set_no_proxy({"public.example"});
  17180. auto res2 = cli.Get("/b");
  17181. ASSERT_TRUE(res2);
  17182. EXPECT_EQ("direct", res2->body);
  17183. EXPECT_EQ(1, proxy_hits.load());
  17184. EXPECT_EQ(1, target_hits.load());
  17185. }
  17186. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17187. namespace proxy_tunnel_test {
  17188. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17189. class ScopedSSLServer {
  17190. public:
  17191. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17192. port_ = svr_.bind_to_any_port("127.0.0.1");
  17193. }
  17194. ~ScopedSSLServer() {
  17195. svr_.stop();
  17196. if (th_.joinable()) { th_.join(); }
  17197. }
  17198. SSLServer &svr() { return svr_; }
  17199. int port() const { return port_; }
  17200. void listen() {
  17201. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17202. svr_.wait_until_ready();
  17203. }
  17204. private:
  17205. SSLServer svr_;
  17206. std::thread th_;
  17207. int port_ = 0;
  17208. };
  17209. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17210. class ScopedConnectProxy {
  17211. public:
  17212. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17213. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17214. if (listen_fd_ < 0) { return; }
  17215. int yes = 1;
  17216. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17217. sockaddr_in a{};
  17218. a.sin_family = AF_INET;
  17219. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17220. a.sin_port = 0;
  17221. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17222. return;
  17223. }
  17224. socklen_t alen = sizeof(a);
  17225. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17226. 0) {
  17227. return;
  17228. }
  17229. port_ = ntohs(a.sin_port);
  17230. if (::listen(listen_fd_, 1) != 0) { return; }
  17231. th_ = std::thread([this] { run(); });
  17232. }
  17233. ~ScopedConnectProxy() {
  17234. stop_ = true;
  17235. if (listen_fd_ >= 0) {
  17236. ::shutdown(listen_fd_, SHUT_RDWR);
  17237. ::close(listen_fd_);
  17238. }
  17239. if (th_.joinable()) { th_.join(); }
  17240. }
  17241. int port() const { return port_; }
  17242. int connect_hits() const { return connect_hits_.load(); }
  17243. private:
  17244. void run() {
  17245. while (!stop_.load()) {
  17246. fd_set rfds;
  17247. FD_ZERO(&rfds);
  17248. FD_SET(listen_fd_, &rfds);
  17249. timeval tv{0, 100 * 1000};
  17250. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17251. if (sel <= 0) { continue; }
  17252. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17253. if (client_fd < 0) { continue; }
  17254. std::string req;
  17255. char buf[2048];
  17256. while (req.find("\r\n\r\n") == std::string::npos) {
  17257. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17258. if (n <= 0) { break; }
  17259. req.append(buf, static_cast<size_t>(n));
  17260. }
  17261. if (req.compare(0, 7, "CONNECT") != 0) {
  17262. ::close(client_fd);
  17263. continue;
  17264. }
  17265. connect_hits_++;
  17266. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17267. ::send(client_fd, ok, std::strlen(ok), 0);
  17268. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17269. sockaddr_in o{};
  17270. o.sin_family = AF_INET;
  17271. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17272. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17273. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17274. 0) {
  17275. ::close(client_fd);
  17276. ::close(origin_fd);
  17277. continue;
  17278. }
  17279. auto forward = [](int from, int to) {
  17280. char b[8192];
  17281. for (;;) {
  17282. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17283. if (n <= 0) { break; }
  17284. ssize_t off = 0;
  17285. while (off < n) {
  17286. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17287. if (s <= 0) {
  17288. off = n;
  17289. break;
  17290. }
  17291. off += s;
  17292. }
  17293. }
  17294. ::shutdown(to, SHUT_WR);
  17295. };
  17296. std::thread t1([&] { forward(client_fd, origin_fd); });
  17297. std::thread t2([&] { forward(origin_fd, client_fd); });
  17298. t1.join();
  17299. t2.join();
  17300. ::close(client_fd);
  17301. ::close(origin_fd);
  17302. }
  17303. }
  17304. int forward_port_ = -1;
  17305. int listen_fd_ = -1;
  17306. int port_ = 0;
  17307. std::thread th_;
  17308. std::atomic<bool> stop_{false};
  17309. std::atomic<int> connect_hits_{0};
  17310. };
  17311. } // namespace proxy_tunnel_test
  17312. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17313. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17314. // retry; otherwise proxy creds would be sent to the origin.
  17315. std::atomic<int> origin_hits{0};
  17316. std::atomic<bool> origin_saw_proxy_authz{false};
  17317. proxy_tunnel_test::ScopedSSLServer origin;
  17318. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17319. origin_hits++;
  17320. if (req.has_header("Proxy-Authorization")) {
  17321. origin_saw_proxy_authz = true;
  17322. }
  17323. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17324. res.set_header("Proxy-Authenticate",
  17325. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17326. "algorithm=MD5");
  17327. });
  17328. origin.listen();
  17329. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17330. ASSERT_NE(0, proxy.port());
  17331. SSLClient cli(HOST, origin.port());
  17332. cli.enable_server_certificate_verification(false);
  17333. cli.set_proxy(HOST, proxy.port());
  17334. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17335. auto res = cli.Get("/x");
  17336. ASSERT_TRUE(res);
  17337. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17338. EXPECT_EQ(1, origin_hits.load());
  17339. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17340. EXPECT_EQ(1, proxy.connect_hits());
  17341. }
  17342. #endif