test.cc 630 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395
  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: in split builds split.py strips `inline` and moves the
  361. // definition into httplib.cc, so detail::base64_encode is not visible from the
  362. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  363. // in both header-only and split builds.
  364. namespace httplib {
  365. namespace detail {
  366. std::string base64_encode(const std::string &in);
  367. } // namespace detail
  368. } // namespace httplib
  369. TEST(Base64EncodeTest, KnownAnswers) {
  370. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  371. // where the accumulator's top bit is already set before the next shift.
  372. EXPECT_EQ("", detail::base64_encode(""));
  373. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  374. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  375. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  376. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  377. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  378. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  379. // High bytes keep the top bit set across several rounds.
  380. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  381. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  382. }
  383. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  384. string unescapedCharacters = "-_.!~*'()";
  385. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  386. }
  387. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  388. string reservedCharacters = ";,/?:@&=+$";
  389. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  390. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  391. }
  392. TEST(ClientQueryOrder, PreserveOrder) {
  393. // This test reproduces Issue #2259: client may reorder query parameters
  394. // when sending a GET request. The expected behavior is that the client
  395. // preserves the original query string order when the caller supplied it
  396. // as part of the path.
  397. Server svr;
  398. svr.Get("/", [&](const Request &req, Response &res) {
  399. // Echo back the raw target so the test can assert ordering
  400. res.set_content(req.target, "text/plain");
  401. });
  402. std::thread t{[&] { svr.listen(HOST, PORT); }};
  403. auto se = detail::scope_exit([&] {
  404. svr.stop();
  405. t.join();
  406. ASSERT_FALSE(svr.is_running());
  407. });
  408. svr.wait_until_ready();
  409. Client cli(HOST, PORT);
  410. ASSERT_TRUE(cli.is_valid());
  411. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  412. auto res = cli.Get(original);
  413. ASSERT_TRUE(res);
  414. // Expect the echoed target to exactly match the original path (order
  415. // preserved)
  416. EXPECT_EQ(res->body, original);
  417. }
  418. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  425. "%D0%B4%D0%BE%D0%BC");
  426. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  427. }
  428. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  429. string unescapedCharacters = "-_.!~*'()";
  430. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  431. }
  432. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  433. string reservedCharacters = ";,/?:@&=+$";
  434. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  435. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  436. }
  437. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  438. string chineseCharacters = U8("中国語");
  439. string russianCharacters = U8("дом");
  440. string brazilianCharacters = U8("óculos");
  441. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  442. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  443. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  444. "%D0%B4%D0%BE%D0%BC");
  445. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  446. }
  447. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  448. // Issue #2082 use case: encoding path component with ampersand
  449. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  450. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  451. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  452. }
  453. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  454. string unescapedCharacters = "-_.!~*'()";
  455. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  456. }
  457. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  458. string reservedCharacters = ";,/?:@&=+$#";
  459. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  460. }
  461. TEST(EncodeUriTest, TestUTF8Characters) {
  462. string chineseCharacters = U8("中国語");
  463. string russianCharacters = U8("дом");
  464. string brazilianCharacters = U8("óculos");
  465. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  466. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  467. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriTest, TestCompleteUri) {
  471. string uri =
  472. "https://example.com/path/to/resource?query=value&param=test#fragment";
  473. EXPECT_EQ(
  474. httplib::encode_uri(uri),
  475. "https://example.com/path/to/resource?query=value&param=test#fragment");
  476. }
  477. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  478. string uri =
  479. "https://example.com/path with spaces/file name.html?q=hello world";
  480. EXPECT_EQ(httplib::encode_uri(uri),
  481. "https://example.com/path%20with%20spaces/"
  482. "file%20name.html?q=hello%20world");
  483. }
  484. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  485. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  487. }
  488. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  489. string unescapedCharacters = "-_.!~*'()";
  490. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  491. }
  492. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  493. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  494. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  495. string encodedBrazilian = "%C3%B3culos";
  496. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  497. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  498. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  499. }
  500. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  501. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  502. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  503. "Piri Tommy Villiers - on & on");
  504. }
  505. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  506. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  507. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  508. }
  509. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  510. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  511. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  512. }
  513. TEST(DecodeUriTest, TestUTF8Characters) {
  514. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  515. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  516. string encodedBrazilian = "%C3%B3culos";
  517. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  518. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  519. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  520. }
  521. TEST(DecodeUriTest, TestCompleteUri) {
  522. string encodedUri = "https://example.com/path%20with%20spaces/"
  523. "file%20name.html?q=hello%20world";
  524. EXPECT_EQ(
  525. httplib::decode_uri(encodedUri),
  526. "https://example.com/path with spaces/file name.html?q=hello world");
  527. }
  528. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  529. string original =
  530. "https://example.com/path with spaces/file name.html?q=hello world";
  531. string encoded = httplib::encode_uri(original);
  532. string decoded = httplib::decode_uri(encoded);
  533. EXPECT_EQ(decoded, original);
  534. }
  535. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  536. string original = "Piri Tommy Villiers - on & on";
  537. string encoded = httplib::encode_uri_component(original);
  538. string decoded = httplib::decode_uri_component(encoded);
  539. EXPECT_EQ(decoded, original);
  540. }
  541. TEST(TrimTests, TrimStringTests) {
  542. EXPECT_EQ("abc", detail::trim_copy("abc"));
  543. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  544. EXPECT_TRUE(detail::trim_copy("").empty());
  545. }
  546. TEST(AsciiTest, LocaleIndependentClassification) {
  547. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  548. // which consult the global C locale: std::isalnum(0xC5) can return true
  549. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  550. // helpers must classify every byte by the ASCII grammar alone.
  551. for (int i = 0; i < 256; i++) {
  552. auto c = static_cast<char>(i);
  553. auto is_digit = i >= '0' && i <= '9';
  554. auto is_upper = i >= 'A' && i <= 'Z';
  555. auto is_lower = i >= 'a' && i <= 'z';
  556. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  557. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  558. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  559. << "byte " << i;
  560. }
  561. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  562. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  563. // Non-ASCII bytes must be percent-encoded, never passed through as
  564. // alphanumeric.
  565. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  566. }
  567. TEST(FromCharsTest, Double) {
  568. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  569. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  570. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  571. auto parse = [](const std::string &s, double &v) {
  572. return detail::from_chars(s.data(), s.data() + s.size(), v);
  573. };
  574. double v = -1.0;
  575. // Representative quality values.
  576. EXPECT_EQ(parse("0", v).ec, std::errc{});
  577. EXPECT_DOUBLE_EQ(v, 0.0);
  578. EXPECT_EQ(parse("1", v).ec, std::errc{});
  579. EXPECT_DOUBLE_EQ(v, 1.0);
  580. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  581. EXPECT_DOUBLE_EQ(v, 0.8);
  582. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  583. EXPECT_DOUBLE_EQ(v, 0.001);
  584. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  585. EXPECT_DOUBLE_EQ(v, 1.0);
  586. // A missing integer or fractional part is tolerated.
  587. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  588. EXPECT_DOUBLE_EQ(v, 0.5);
  589. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  590. EXPECT_DOUBLE_EQ(v, 5.0);
  591. // Values outside [0, 1] still parse; the caller range-checks them.
  592. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  593. EXPECT_DOUBLE_EQ(v, 123.456);
  594. // Stops at the first byte that is not part of the number and reports where.
  595. std::string trailing = "0.9, text/html";
  596. auto r = parse(trailing, v);
  597. EXPECT_EQ(r.ec, std::errc{});
  598. EXPECT_DOUBLE_EQ(v, 0.9);
  599. EXPECT_EQ(*r.ptr, ',');
  600. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  601. // outright, and an 'e'/'E' simply ends the number.
  602. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  603. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  604. std::string exp_input = "1.5e3";
  605. r = parse(exp_input, v);
  606. EXPECT_EQ(r.ec, std::errc{});
  607. EXPECT_DOUBLE_EQ(v, 1.5);
  608. EXPECT_EQ(*r.ptr, 'e');
  609. // Invalid inputs.
  610. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  611. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  612. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  613. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  614. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  615. // Pathological but well-formed inputs must stay bounded (no overflow, no
  616. // out-of-bounds table access) and stay within [0, 1] for the caller.
  617. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  618. std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.0);
  620. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  621. std::errc{});
  622. EXPECT_GE(v, 0.0);
  623. EXPECT_LE(v, 1.0);
  624. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  625. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  626. }
  627. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  628. // Simple case without quality values
  629. std::vector<std::string> result1;
  630. EXPECT_TRUE(detail::parse_accept_header(
  631. "text/html,application/json,text/plain", result1));
  632. EXPECT_EQ(result1.size(), 3U);
  633. EXPECT_EQ(result1[0], "text/html");
  634. EXPECT_EQ(result1[1], "application/json");
  635. EXPECT_EQ(result1[2], "text/plain");
  636. // With quality values
  637. std::vector<std::string> result2;
  638. EXPECT_TRUE(detail::parse_accept_header(
  639. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  640. EXPECT_EQ(result2.size(), 3U);
  641. EXPECT_EQ(result2[0], "application/json"); // highest q value
  642. EXPECT_EQ(result2[1], "text/html");
  643. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  644. }
  645. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  646. // Mixed with and without quality values
  647. std::vector<std::string> result;
  648. EXPECT_TRUE(detail::parse_accept_header(
  649. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  650. EXPECT_EQ(result.size(), 3U);
  651. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  652. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  653. EXPECT_EQ(result[2], "application/json"); // q=0.5
  654. }
  655. TEST(ParseAcceptHeaderTest, EdgeCases) {
  656. // Empty header
  657. std::vector<std::string> empty_result;
  658. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  659. EXPECT_TRUE(empty_result.empty());
  660. // Single type
  661. std::vector<std::string> single_result;
  662. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  663. EXPECT_EQ(single_result.size(), 1U);
  664. EXPECT_EQ(single_result[0], "application/json");
  665. // Wildcard types
  666. std::vector<std::string> wildcard_result;
  667. EXPECT_TRUE(detail::parse_accept_header(
  668. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  669. EXPECT_EQ(wildcard_result.size(), 3U);
  670. EXPECT_EQ(wildcard_result[0], "application/json");
  671. EXPECT_EQ(wildcard_result[1], "text/*");
  672. EXPECT_EQ(wildcard_result[2], "*/*");
  673. }
  674. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  675. // Common browser Accept header
  676. std::vector<std::string> browser_result;
  677. EXPECT_TRUE(
  678. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  679. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  680. browser_result));
  681. EXPECT_EQ(browser_result.size(), 6U);
  682. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  683. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  684. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  685. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  686. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  687. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  688. // API client header
  689. std::vector<std::string> api_result;
  690. EXPECT_TRUE(detail::parse_accept_header(
  691. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  692. api_result));
  693. EXPECT_EQ(api_result.size(), 3U);
  694. EXPECT_EQ(api_result[0], "application/json");
  695. EXPECT_EQ(api_result[1], "application/xml");
  696. EXPECT_EQ(api_result[2], "text/plain");
  697. }
  698. TEST(ParseAcceptHeaderTest, SpecialCases) {
  699. // Quality value with 3 decimal places
  700. std::vector<std::string> decimal_result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  703. EXPECT_EQ(decimal_result.size(), 2U);
  704. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  705. EXPECT_EQ(decimal_result[1], "text/html");
  706. // Zero quality (should still be included but with lowest priority)
  707. std::vector<std::string> zero_q_result;
  708. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  709. zero_q_result));
  710. EXPECT_EQ(zero_q_result.size(), 2U);
  711. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  712. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  713. // No spaces around commas
  714. std::vector<std::string> no_space_result;
  715. EXPECT_TRUE(detail::parse_accept_header(
  716. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  717. no_space_result));
  718. EXPECT_EQ(no_space_result.size(), 3U);
  719. EXPECT_EQ(no_space_result[0], "text/html");
  720. EXPECT_EQ(no_space_result[1], "application/json");
  721. EXPECT_EQ(no_space_result[2], "text/plain");
  722. }
  723. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  724. // Quality values always use '.' as the decimal separator, so parsing must
  725. // not depend on the process locale. An embedding application may have
  726. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  727. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  728. std::string saved = cur ? cur : "C";
  729. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  730. "fr_FR.UTF-8"};
  731. bool switched = false;
  732. for (const auto loc : comma_locales) {
  733. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  734. std::localeconv()->decimal_point[0] == ',') {
  735. switched = true;
  736. break;
  737. }
  738. }
  739. if (!switched) {
  740. std::setlocale(LC_NUMERIC, saved.c_str());
  741. GTEST_SKIP() << "no comma-decimal locale available on this host";
  742. }
  743. // The higher-weighted type appears later in the list, so a correct parse
  744. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  745. // sensitive parse reads both weights as 0 and leaves the original order.
  746. std::vector<std::string> result;
  747. EXPECT_TRUE(detail::parse_accept_header(
  748. "application/json;q=0.1,text/html;q=0.9", result));
  749. ASSERT_EQ(result.size(), 2U);
  750. EXPECT_EQ(result[0], "text/html");
  751. EXPECT_EQ(result[1], "application/json");
  752. std::setlocale(LC_NUMERIC, saved.c_str());
  753. }
  754. TEST(ParseAcceptHeaderTest, InvalidCases) {
  755. std::vector<std::string> result;
  756. // Invalid quality value (> 1.0)
  757. EXPECT_FALSE(
  758. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  759. // Invalid quality value (< 0.0)
  760. EXPECT_FALSE(
  761. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  762. // Invalid quality value (not a number)
  763. EXPECT_FALSE(detail::parse_accept_header(
  764. "text/html;q=invalid,application/json", result));
  765. // Empty quality value
  766. EXPECT_FALSE(
  767. detail::parse_accept_header("text/html;q=,application/json", result));
  768. // Invalid media type format (no slash and not wildcard)
  769. EXPECT_FALSE(
  770. detail::parse_accept_header("invalidtype,application/json", result));
  771. // Empty media type
  772. result.clear();
  773. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  774. // Only commas
  775. result.clear();
  776. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  777. // Valid cases should still work
  778. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  779. EXPECT_EQ(result.size(), 1U);
  780. EXPECT_EQ(result[0], "*/*");
  781. EXPECT_TRUE(detail::parse_accept_header("*", result));
  782. EXPECT_EQ(result.size(), 1U);
  783. EXPECT_EQ(result[0], "*");
  784. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  785. EXPECT_EQ(result.size(), 1U);
  786. EXPECT_EQ(result[0], "text/*");
  787. }
  788. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  789. Server svr;
  790. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  791. EXPECT_EQ(req.accept_content_types.size(), 3U);
  792. EXPECT_EQ(req.accept_content_types[0], "application/json");
  793. EXPECT_EQ(req.accept_content_types[1], "text/html");
  794. EXPECT_EQ(req.accept_content_types[2], "*/*");
  795. res.set_content("ok", "text/plain");
  796. });
  797. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  798. EXPECT_TRUE(false);
  799. res.set_content("bad request", "text/plain");
  800. });
  801. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  802. auto se = detail::scope_exit([&] {
  803. svr.stop();
  804. listen_thread.join();
  805. ASSERT_FALSE(svr.is_running());
  806. });
  807. svr.wait_until_ready();
  808. Client cli("localhost", PORT);
  809. {
  810. auto res = cli.Get(
  811. "/accept_ok",
  812. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  813. ASSERT_TRUE(res);
  814. EXPECT_EQ(StatusCode::OK_200, res->status);
  815. }
  816. {
  817. auto res = cli.Get("/accept_bad_request",
  818. Headers{{"Accept", "text/html;q=abc,application/json"}});
  819. ASSERT_TRUE(res);
  820. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  821. }
  822. }
  823. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  824. Server svr;
  825. svr.Get("/", [](const Request & /*req*/, Response &res) {
  826. res.set_content("ok", "text/plain");
  827. });
  828. std::atomic<int> start_count{0};
  829. std::atomic<bool> running_when_called{false};
  830. svr.set_start_handler([&]() {
  831. running_when_called = svr.is_running();
  832. start_count++;
  833. });
  834. auto port = svr.bind_to_any_port(HOST);
  835. std::thread t([&]() { svr.listen_after_bind(); });
  836. auto se = detail::scope_exit([&] {
  837. svr.stop();
  838. t.join();
  839. ASSERT_FALSE(svr.is_running());
  840. });
  841. svr.wait_until_ready();
  842. // A successful request proves the accept loop is running, which the start
  843. // handler precedes; so by now the handler must have run exactly once.
  844. Client cli(HOST, port);
  845. cli.set_connection_timeout(std::chrono::seconds(5));
  846. auto res = cli.Get("/");
  847. ASSERT_TRUE(res);
  848. EXPECT_EQ(StatusCode::OK_200, res->status);
  849. EXPECT_EQ(1, start_count.load());
  850. EXPECT_TRUE(running_when_called.load());
  851. }
  852. TEST(DivideTest, DivideStringTests) {
  853. auto divide = [](const std::string &str, char d) {
  854. std::string lhs;
  855. std::string rhs;
  856. detail::divide(str, d,
  857. [&](const char *lhs_data, std::size_t lhs_size,
  858. const char *rhs_data, std::size_t rhs_size) {
  859. lhs.assign(lhs_data, lhs_size);
  860. rhs.assign(rhs_data, rhs_size);
  861. });
  862. return std::make_pair(std::move(lhs), std::move(rhs));
  863. };
  864. {
  865. const auto res = divide("", '=');
  866. EXPECT_EQ(res.first, "");
  867. EXPECT_EQ(res.second, "");
  868. }
  869. {
  870. const auto res = divide("=", '=');
  871. EXPECT_EQ(res.first, "");
  872. EXPECT_EQ(res.second, "");
  873. }
  874. {
  875. const auto res = divide(" ", '=');
  876. EXPECT_EQ(res.first, " ");
  877. EXPECT_EQ(res.second, "");
  878. }
  879. {
  880. const auto res = divide("a", '=');
  881. EXPECT_EQ(res.first, "a");
  882. EXPECT_EQ(res.second, "");
  883. }
  884. {
  885. const auto res = divide("a=", '=');
  886. EXPECT_EQ(res.first, "a");
  887. EXPECT_EQ(res.second, "");
  888. }
  889. {
  890. const auto res = divide("=b", '=');
  891. EXPECT_EQ(res.first, "");
  892. EXPECT_EQ(res.second, "b");
  893. }
  894. {
  895. const auto res = divide("a=b", '=');
  896. EXPECT_EQ(res.first, "a");
  897. EXPECT_EQ(res.second, "b");
  898. }
  899. {
  900. const auto res = divide("a=b=", '=');
  901. EXPECT_EQ(res.first, "a");
  902. EXPECT_EQ(res.second, "b=");
  903. }
  904. {
  905. const auto res = divide("a=b=c", '=');
  906. EXPECT_EQ(res.first, "a");
  907. EXPECT_EQ(res.second, "b=c");
  908. }
  909. }
  910. TEST(SplitTest, ParseQueryString) {
  911. string s = "key1=val1&key2=val2&key3=val3";
  912. Params dic;
  913. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  914. [&](const char *b, const char *e) {
  915. string key, val;
  916. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  917. if (key.empty()) {
  918. key.assign(b2, e2);
  919. } else {
  920. val.assign(b2, e2);
  921. }
  922. });
  923. dic.emplace(key, val);
  924. });
  925. EXPECT_EQ("val1", dic.find("key1")->second);
  926. EXPECT_EQ("val2", dic.find("key2")->second);
  927. EXPECT_EQ("val3", dic.find("key3")->second);
  928. }
  929. TEST(SplitTest, ParseInvalidQueryTests) {
  930. {
  931. string s = " ";
  932. Params dict;
  933. detail::parse_query_text(s, dict);
  934. EXPECT_TRUE(dict.empty());
  935. }
  936. {
  937. string s = " = =";
  938. Params dict;
  939. detail::parse_query_text(s, dict);
  940. EXPECT_TRUE(dict.empty());
  941. }
  942. }
  943. TEST(ParseQueryTest, ParseQueryString) {
  944. {
  945. std::string s = "key1=val1&key2=val2&key3=val3";
  946. Params dic;
  947. detail::parse_query_text(s, dic);
  948. EXPECT_EQ("val1", dic.find("key1")->second);
  949. EXPECT_EQ("val2", dic.find("key2")->second);
  950. EXPECT_EQ("val3", dic.find("key3")->second);
  951. }
  952. {
  953. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  954. Params dic;
  955. detail::parse_query_text(s, dic);
  956. EXPECT_EQ("", dic.find("key1")->second);
  957. EXPECT_EQ("val1", dic.find("key2")->second);
  958. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  959. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  960. }
  961. }
  962. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  963. Params dic;
  964. EXPECT_EQ(detail::params_to_query_str(dic), "");
  965. dic.emplace("key1", "val1");
  966. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  967. dic.emplace("key2", "val2");
  968. dic.emplace("key3", "val3");
  969. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  970. }
  971. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  972. string content_type = "multipart/form-data; boundary=something";
  973. string boundary;
  974. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  975. EXPECT_TRUE(ret);
  976. EXPECT_EQ(boundary, "something");
  977. }
  978. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  979. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  980. string boundary;
  981. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  982. EXPECT_TRUE(ret);
  983. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  984. }
  985. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  986. string content_type =
  987. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  988. string boundary;
  989. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  990. EXPECT_TRUE(ret);
  991. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  992. }
  993. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  994. string content_type =
  995. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  996. string boundary;
  997. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  998. EXPECT_TRUE(ret);
  999. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1000. }
  1001. TEST(GetHeaderValueTest, DefaultValue) {
  1002. Headers headers = {{"Dummy", "Dummy"}};
  1003. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1004. EXPECT_STREQ("text/plain", val);
  1005. }
  1006. TEST(GetHeaderValueTest, DefaultValueInt) {
  1007. Headers headers = {{"Dummy", "Dummy"}};
  1008. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1009. EXPECT_EQ(100ull, val);
  1010. }
  1011. TEST(GetHeaderValueTest, RegularValue) {
  1012. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1013. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1014. EXPECT_STREQ("text/html", val);
  1015. }
  1016. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1017. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1018. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1019. EXPECT_STREQ("text/html", val);
  1020. }
  1021. TEST(GetHeaderValueTest, SetContent) {
  1022. Response res;
  1023. res.set_content("html", "text/html");
  1024. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1025. res.set_content("text", "text/plain");
  1026. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1027. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1028. }
  1029. TEST(GetHeaderValueTest, RegularValueInt) {
  1030. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1031. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1032. EXPECT_EQ(100ull, val);
  1033. }
  1034. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1035. Headers headers = {{"Content-Length", "x"}};
  1036. auto is_invalid_value = false;
  1037. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1038. is_invalid_value);
  1039. EXPECT_EQ(0ull, val);
  1040. EXPECT_TRUE(is_invalid_value);
  1041. }
  1042. TEST(GetHeaderValueTest, Range) {
  1043. {
  1044. Headers headers = {make_range_header({{1, -1}})};
  1045. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1046. EXPECT_STREQ("bytes=1-", val);
  1047. }
  1048. {
  1049. Headers headers = {make_range_header({{-1, 1}})};
  1050. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1051. EXPECT_STREQ("bytes=-1", val);
  1052. }
  1053. {
  1054. Headers headers = {make_range_header({{1, 10}})};
  1055. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1056. EXPECT_STREQ("bytes=1-10", val);
  1057. }
  1058. {
  1059. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1060. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1061. EXPECT_STREQ("bytes=1-10, 100-", val);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1065. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1066. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1067. }
  1068. {
  1069. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1070. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1071. EXPECT_STREQ("bytes=0-0, -1", val);
  1072. }
  1073. }
  1074. TEST(ParseHeaderValueTest, Range) {
  1075. {
  1076. Ranges ranges;
  1077. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1078. EXPECT_TRUE(ret);
  1079. EXPECT_EQ(1u, ranges.size());
  1080. EXPECT_EQ(1u, ranges[0].first);
  1081. EXPECT_EQ(-1, ranges[0].second);
  1082. }
  1083. {
  1084. Ranges ranges;
  1085. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1086. EXPECT_TRUE(ret);
  1087. EXPECT_EQ(1u, ranges.size());
  1088. EXPECT_EQ(-1, ranges[0].first);
  1089. EXPECT_EQ(1u, ranges[0].second);
  1090. }
  1091. {
  1092. Ranges ranges;
  1093. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1094. EXPECT_TRUE(ret);
  1095. EXPECT_EQ(1u, ranges.size());
  1096. EXPECT_EQ(1u, ranges[0].first);
  1097. EXPECT_EQ(10u, ranges[0].second);
  1098. }
  1099. {
  1100. Ranges ranges;
  1101. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1102. EXPECT_FALSE(ret);
  1103. }
  1104. {
  1105. Ranges ranges;
  1106. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1107. EXPECT_TRUE(ret);
  1108. EXPECT_EQ(2u, ranges.size());
  1109. EXPECT_EQ(1u, ranges[0].first);
  1110. EXPECT_EQ(10u, ranges[0].second);
  1111. EXPECT_EQ(100u, ranges[1].first);
  1112. EXPECT_EQ(-1, ranges[1].second);
  1113. }
  1114. {
  1115. Ranges ranges;
  1116. auto ret =
  1117. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1118. EXPECT_TRUE(ret);
  1119. EXPECT_EQ(3u, ranges.size());
  1120. EXPECT_EQ(1u, ranges[0].first);
  1121. EXPECT_EQ(10u, ranges[0].second);
  1122. EXPECT_EQ(100u, ranges[1].first);
  1123. EXPECT_EQ(200u, ranges[1].second);
  1124. EXPECT_EQ(300u, ranges[2].first);
  1125. EXPECT_EQ(400u, ranges[2].second);
  1126. }
  1127. {
  1128. Ranges ranges;
  1129. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1130. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1131. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1132. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1133. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1134. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1135. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1136. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1137. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1138. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1139. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1140. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1141. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1142. EXPECT_TRUE(ranges.empty());
  1143. }
  1144. }
  1145. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1146. Request req;
  1147. req.set_header("Accept-Encoding", "gzip");
  1148. Response res;
  1149. res.set_header("Content-Type", "text/plain");
  1150. auto ret = detail::encoding_type(req, res);
  1151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1152. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1153. #else
  1154. EXPECT_TRUE(ret == detail::EncodingType::None);
  1155. #endif
  1156. }
  1157. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1158. Request req;
  1159. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1160. Response res;
  1161. res.set_header("Content-Type", "text/plain");
  1162. auto ret = detail::encoding_type(req, res);
  1163. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1164. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1165. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1166. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1167. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1168. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1169. #else
  1170. EXPECT_TRUE(ret == detail::EncodingType::None);
  1171. #endif
  1172. }
  1173. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1174. Request req;
  1175. req.set_header("Accept-Encoding",
  1176. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1177. Response res;
  1178. res.set_header("Content-Type", "text/plain");
  1179. auto ret = detail::encoding_type(req, res);
  1180. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1181. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1182. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1183. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1184. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1185. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1186. #else
  1187. EXPECT_TRUE(ret == detail::EncodingType::None);
  1188. #endif
  1189. }
  1190. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1191. // All supported encodings rejected with q=0 should return None
  1192. Request req;
  1193. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1194. Response res;
  1195. res.set_header("Content-Type", "text/plain");
  1196. auto ret = detail::encoding_type(req, res);
  1197. EXPECT_TRUE(ret == detail::EncodingType::None);
  1198. }
  1199. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1200. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1201. Request req;
  1202. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1203. Response res;
  1204. res.set_header("Content-Type", "text/plain");
  1205. auto ret = detail::encoding_type(req, res);
  1206. EXPECT_TRUE(ret == detail::EncodingType::None);
  1207. }
  1208. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1209. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1210. Request req;
  1211. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1212. Response res;
  1213. res.set_header("Content-Type", "text/plain");
  1214. auto ret = detail::encoding_type(req, res);
  1215. EXPECT_TRUE(ret == detail::EncodingType::None);
  1216. }
  1217. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1218. // RFC 7231: Accept-Encoding values are case-insensitive
  1219. Request req;
  1220. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1221. Response res;
  1222. res.set_header("Content-Type", "text/plain");
  1223. auto ret = detail::encoding_type(req, res);
  1224. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1225. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1226. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1227. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1228. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1229. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1230. #else
  1231. EXPECT_TRUE(ret == detail::EncodingType::None);
  1232. #endif
  1233. }
  1234. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1235. // q value should determine priority, not hardcoded order
  1236. Request req;
  1237. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1238. Response res;
  1239. res.set_header("Content-Type", "text/plain");
  1240. auto ret = detail::encoding_type(req, res);
  1241. // gzip has highest q=1.0, so it should be selected even though
  1242. // br and zstd are also supported
  1243. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1244. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1245. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1246. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1247. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1248. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1249. #else
  1250. EXPECT_TRUE(ret == detail::EncodingType::None);
  1251. #endif
  1252. }
  1253. TEST(BufferStreamTest, read) {
  1254. detail::BufferStream strm1;
  1255. Stream &strm = strm1;
  1256. EXPECT_EQ(5, strm.write("hello"));
  1257. char buf[512];
  1258. EXPECT_EQ(2, strm.read(buf, 2));
  1259. EXPECT_EQ('h', buf[0]);
  1260. EXPECT_EQ('e', buf[1]);
  1261. EXPECT_EQ(2, strm.read(buf, 2));
  1262. EXPECT_EQ('l', buf[0]);
  1263. EXPECT_EQ('l', buf[1]);
  1264. EXPECT_EQ(1, strm.read(buf, 1));
  1265. EXPECT_EQ('o', buf[0]);
  1266. EXPECT_EQ(0, strm.read(buf, 1));
  1267. }
  1268. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1269. auto host = "www.httpwatch.com";
  1270. auto ip = hosted_at(host);
  1271. EXPECT_EQ("23.96.13.243", ip);
  1272. std::vector<std::string> addrs;
  1273. hosted_at(host, addrs);
  1274. EXPECT_EQ(1u, addrs.size());
  1275. }
  1276. #if 0 // It depends on each test environment...
  1277. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1278. auto host = "www.youtube.com";
  1279. std::vector<std::string> addrs;
  1280. hosted_at(host, addrs);
  1281. EXPECT_EQ(20u, addrs.size());
  1282. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1283. EXPECT_TRUE(it != addrs.end());
  1284. }
  1285. #endif
  1286. class ChunkedEncodingTest : public ::testing::Test {
  1287. protected:
  1288. ChunkedEncodingTest()
  1289. : cli_(HOST, PORT)
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. ,
  1292. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1293. #endif
  1294. {
  1295. cli_.set_connection_timeout(2);
  1296. #ifdef CPPHTTPLIB_SSL_ENABLED
  1297. cli_.enable_server_certificate_verification(false);
  1298. #endif
  1299. }
  1300. virtual void SetUp() {
  1301. read_file("./image.jpg", image_data_);
  1302. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1303. res.set_content("Hello World!", "text/plain");
  1304. });
  1305. svr_.Get(
  1306. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1307. res.set_chunked_content_provider(
  1308. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1309. size_t remaining = image_data_.size() - offset;
  1310. if (remaining == 0) {
  1311. sink.done();
  1312. } else {
  1313. constexpr size_t CHUNK_SIZE = 1024;
  1314. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1315. sink.write(&image_data_[offset], send_size);
  1316. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1317. }
  1318. return true;
  1319. });
  1320. });
  1321. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1322. svr_.wait_until_ready();
  1323. }
  1324. virtual void TearDown() {
  1325. svr_.stop();
  1326. if (!request_threads_.empty()) {
  1327. std::this_thread::sleep_for(std::chrono::seconds(1));
  1328. for (auto &t : request_threads_) {
  1329. t.join();
  1330. }
  1331. }
  1332. t_.join();
  1333. }
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. SSLClient cli_;
  1336. SSLServer svr_;
  1337. #else
  1338. Client cli_;
  1339. Server svr_;
  1340. #endif
  1341. thread t_;
  1342. std::vector<thread> request_threads_;
  1343. std::string image_data_;
  1344. };
  1345. TEST_F(ChunkedEncodingTest, NormalGet) {
  1346. auto res = cli_.Get("/chunked");
  1347. ASSERT_TRUE(res);
  1348. std::string out;
  1349. read_file("./image.jpg", out);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. EXPECT_EQ(out, res->body);
  1352. }
  1353. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1354. std::string body;
  1355. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1356. body.append(data, data_length);
  1357. return true;
  1358. });
  1359. ASSERT_TRUE(res);
  1360. std::string out;
  1361. read_file("./image.jpg", out);
  1362. EXPECT_EQ(StatusCode::OK_200, res->status);
  1363. EXPECT_EQ(out, body);
  1364. }
  1365. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1366. std::string body;
  1367. auto res = cli_.Get(
  1368. "/chunked",
  1369. [&](const Response &response) {
  1370. EXPECT_EQ(StatusCode::OK_200, response.status);
  1371. return true;
  1372. },
  1373. [&](const char *data, size_t data_length) {
  1374. body.append(data, data_length);
  1375. return true;
  1376. });
  1377. ASSERT_TRUE(res);
  1378. std::string out;
  1379. read_file("./image.jpg", out);
  1380. EXPECT_EQ(StatusCode::OK_200, res->status);
  1381. EXPECT_EQ(out, body);
  1382. }
  1383. TEST(RangeTest, FromHTTPBin_Online) {
  1384. auto host = "httpbingo.org";
  1385. auto path = std::string{"/range/32"};
  1386. #ifdef CPPHTTPLIB_SSL_ENABLED
  1387. auto port = 443;
  1388. SSLClient cli(host, port);
  1389. #else
  1390. auto port = 80;
  1391. Client cli(host, port);
  1392. #endif
  1393. cli.set_connection_timeout(5);
  1394. {
  1395. auto res = cli.Get(path);
  1396. ASSERT_TRUE(res);
  1397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1398. EXPECT_EQ(StatusCode::OK_200, res->status);
  1399. }
  1400. {
  1401. Headers headers = {make_range_header({{1, -1}})};
  1402. auto res = cli.Get(path, headers);
  1403. ASSERT_TRUE(res);
  1404. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1406. }
  1407. {
  1408. Headers headers = {make_range_header({{1, 10}})};
  1409. auto res = cli.Get(path, headers);
  1410. ASSERT_TRUE(res);
  1411. EXPECT_EQ("bcdefghijk", res->body);
  1412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1413. }
  1414. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1415. // entire resource, while the original httpbin returned 200. Both are
  1416. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1417. {
  1418. Headers headers = {make_range_header({{0, 31}})};
  1419. auto res = cli.Get(path, headers);
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1422. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1423. res->status == StatusCode::PartialContent_206);
  1424. }
  1425. {
  1426. Headers headers = {make_range_header({{0, -1}})};
  1427. auto res = cli.Get(path, headers);
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1430. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1431. res->status == StatusCode::PartialContent_206);
  1432. }
  1433. // go-httpbin returns 206 with clamped range for over-range requests,
  1434. // while the original httpbin returned 416. Both behaviors are observed
  1435. // in real servers, so we only verify the request succeeds.
  1436. {
  1437. Headers headers = {make_range_header({{0, 32}})};
  1438. auto res = cli.Get(path, headers);
  1439. ASSERT_TRUE(res);
  1440. }
  1441. }
  1442. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1443. auto host = "unresolvableaddress.local";
  1444. auto path = std::string{"/"};
  1445. #ifdef CPPHTTPLIB_SSL_ENABLED
  1446. auto port = 443;
  1447. SSLClient cli(host, port);
  1448. #else
  1449. auto port = 80;
  1450. Client cli(host, port);
  1451. #endif
  1452. cli.set_connection_timeout(1);
  1453. {
  1454. auto res = cli.Get(path);
  1455. ASSERT_FALSE(res);
  1456. }
  1457. std::this_thread::sleep_for(std::chrono::seconds(8));
  1458. }
  1459. #if defined(__linux__) && defined(__GLIBC__) && \
  1460. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1461. // Forward declaration: in split builds split.py strips `inline` and moves the
  1462. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1463. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1464. // against the symbol in both header-only and split builds.
  1465. namespace httplib {
  1466. namespace detail {
  1467. int getaddrinfo_with_timeout(const char *node, const char *service,
  1468. const struct addrinfo *hints,
  1469. struct addrinfo **res, time_t timeout_sec);
  1470. } // namespace detail
  1471. } // namespace httplib
  1472. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1473. //
  1474. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1475. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1476. // gai_suspend() call hits the connection timeout the function calls
  1477. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1478. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1479. // still alive and still references the now-destroyed stack frame.
  1480. //
  1481. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1482. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1483. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1484. // and runs them in a container.
  1485. namespace {
  1486. bool should_run_issue_2431_tests() {
  1487. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1488. return v && *v && std::string(v) != "0";
  1489. }
  1490. std::string unique_unresolvable_host(int n) {
  1491. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1492. // glibc still asks the configured nameserver — which is exactly the path
  1493. // we want to exercise. A unique label per call avoids the resolver cache.
  1494. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1495. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1496. std::to_string(n) + ".invalid";
  1497. }
  1498. } // namespace
  1499. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1500. if (!should_run_issue_2431_tests()) {
  1501. GTEST_SKIP()
  1502. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1503. }
  1504. for (int i = 0; i < 8; ++i) {
  1505. struct addrinfo hints;
  1506. memset(&hints, 0, sizeof(hints));
  1507. hints.ai_family = AF_UNSPEC;
  1508. hints.ai_socktype = SOCK_STREAM;
  1509. auto host = unique_unresolvable_host(i);
  1510. struct addrinfo *result = nullptr;
  1511. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1512. &result, /*timeout_sec=*/1);
  1513. if (rc == 0 && result) { freeaddrinfo(result); }
  1514. }
  1515. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1516. // stack region they still believe holds their gaicb.
  1517. std::this_thread::sleep_for(std::chrono::seconds(3));
  1518. }
  1519. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1520. if (!should_run_issue_2431_tests()) {
  1521. GTEST_SKIP()
  1522. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1523. }
  1524. std::atomic<bool> stop{false};
  1525. std::vector<std::thread> threads;
  1526. for (int t = 0; t < 8; ++t) {
  1527. threads.emplace_back([t, &stop] {
  1528. int i = 0;
  1529. while (!stop.load(std::memory_order_relaxed)) {
  1530. struct addrinfo hints;
  1531. memset(&hints, 0, sizeof(hints));
  1532. hints.ai_family = AF_UNSPEC;
  1533. hints.ai_socktype = SOCK_STREAM;
  1534. auto host = unique_unresolvable_host(t * 100000 + i++);
  1535. struct addrinfo *result = nullptr;
  1536. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1537. &result, /*timeout_sec=*/1);
  1538. if (rc == 0 && result) { freeaddrinfo(result); }
  1539. }
  1540. });
  1541. }
  1542. std::this_thread::sleep_for(std::chrono::seconds(8));
  1543. stop.store(true, std::memory_order_relaxed);
  1544. for (auto &th : threads) {
  1545. th.join();
  1546. }
  1547. std::this_thread::sleep_for(std::chrono::seconds(3));
  1548. }
  1549. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1550. if (!should_run_issue_2431_tests()) {
  1551. GTEST_SKIP()
  1552. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1553. }
  1554. std::atomic<bool> stop{false};
  1555. std::vector<std::thread> threads;
  1556. for (int t = 0; t < 8; ++t) {
  1557. threads.emplace_back([t, &stop] {
  1558. int i = 0;
  1559. while (!stop.load(std::memory_order_relaxed)) {
  1560. auto host = unique_unresolvable_host(t * 100000 + i++);
  1561. Client cli(host, 80);
  1562. cli.set_connection_timeout(1, 0);
  1563. cli.set_read_timeout(1, 0);
  1564. cli.set_write_timeout(1, 0);
  1565. (void)cli.Get("/");
  1566. }
  1567. });
  1568. }
  1569. std::this_thread::sleep_for(std::chrono::seconds(8));
  1570. stop.store(true, std::memory_order_relaxed);
  1571. for (auto &th : threads) {
  1572. th.join();
  1573. }
  1574. std::this_thread::sleep_for(std::chrono::seconds(3));
  1575. }
  1576. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1577. TEST(ConnectionErrorTest, InvalidHost) {
  1578. auto host = "-abcde.com";
  1579. #ifdef CPPHTTPLIB_SSL_ENABLED
  1580. auto port = 443;
  1581. SSLClient cli(host, port);
  1582. #else
  1583. auto port = 80;
  1584. Client cli(host, port);
  1585. #endif
  1586. cli.set_connection_timeout(std::chrono::seconds(2));
  1587. auto res = cli.Get("/");
  1588. ASSERT_TRUE(!res);
  1589. EXPECT_EQ(Error::Connection, res.error());
  1590. }
  1591. TEST(ConnectionErrorTest, InvalidHost2) {
  1592. auto host = "httpcan.org/";
  1593. #ifdef CPPHTTPLIB_SSL_ENABLED
  1594. SSLClient cli(host);
  1595. #else
  1596. Client cli(host);
  1597. #endif
  1598. cli.set_connection_timeout(std::chrono::seconds(2));
  1599. auto res = cli.Get("/");
  1600. ASSERT_TRUE(!res);
  1601. EXPECT_EQ(Error::Connection, res.error());
  1602. }
  1603. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1604. auto host = "httpcan.org/";
  1605. #ifdef CPPHTTPLIB_SSL_ENABLED
  1606. SSLClient cli(host);
  1607. #else
  1608. Client cli(host);
  1609. #endif
  1610. cli.set_connection_timeout(std::chrono::seconds(2));
  1611. auto res = cli.Get("/");
  1612. ASSERT_TRUE(!res);
  1613. stringstream s;
  1614. s << "error code: " << res.error();
  1615. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1616. }
  1617. TEST(ConnectionErrorTest, InvalidPort) {
  1618. auto host = "localhost";
  1619. auto port = 44380;
  1620. #ifdef CPPHTTPLIB_SSL_ENABLED
  1621. SSLClient cli(host, port);
  1622. #else
  1623. Client cli(host, port);
  1624. #endif
  1625. cli.set_connection_timeout(std::chrono::seconds(2));
  1626. auto res = cli.Get("/");
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_TRUE(Error::Connection == res.error() ||
  1629. Error::ConnectionTimeout == res.error());
  1630. }
  1631. TEST(ConnectionErrorTest, Timeout_Online) {
  1632. auto host = "google.com";
  1633. #ifdef CPPHTTPLIB_SSL_ENABLED
  1634. auto port = 44380;
  1635. SSLClient cli(host, port);
  1636. #else
  1637. auto port = 8080;
  1638. Client cli(host, port);
  1639. #endif
  1640. cli.set_connection_timeout(std::chrono::seconds(2));
  1641. // only probe one address type so that the error reason
  1642. // correlates to the timed-out IPv4, not the unsupported
  1643. // IPv6 connection attempt
  1644. cli.set_address_family(AF_INET);
  1645. auto res = cli.Get("/");
  1646. ASSERT_TRUE(!res);
  1647. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1648. }
  1649. TEST(CancelTest, NoCancel_Online) {
  1650. auto host = "httpbingo.org";
  1651. auto path = std::string{"/range/32"};
  1652. #ifdef CPPHTTPLIB_SSL_ENABLED
  1653. auto port = 443;
  1654. SSLClient cli(host, port);
  1655. #else
  1656. auto port = 80;
  1657. Client cli(host, port);
  1658. #endif
  1659. cli.set_connection_timeout(std::chrono::seconds(5));
  1660. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1661. ASSERT_TRUE(res);
  1662. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1663. EXPECT_EQ(StatusCode::OK_200, res->status);
  1664. }
  1665. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1666. // Use /bytes with a large payload so that the DownloadProgress callback
  1667. // (which only fires for Content-Length responses) is invoked before the
  1668. // entire body is received, giving cancellation a chance to fire.
  1669. auto host = "httpbingo.org";
  1670. auto path = std::string{"/bytes/524288"};
  1671. #ifdef CPPHTTPLIB_SSL_ENABLED
  1672. auto port = 443;
  1673. SSLClient cli(host, port);
  1674. #else
  1675. auto port = 80;
  1676. Client cli(host, port);
  1677. #endif
  1678. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1679. cli.set_connection_timeout(std::chrono::seconds(5));
  1680. ASSERT_TRUE(!res);
  1681. EXPECT_EQ(Error::Canceled, res.error());
  1682. }
  1683. TEST(CancelTest, WithCancelLargePayload_Online) {
  1684. auto host = "httpbingo.org";
  1685. auto path = std::string{"/bytes/524288"};
  1686. #ifdef CPPHTTPLIB_SSL_ENABLED
  1687. auto port = 443;
  1688. SSLClient cli(host, port);
  1689. #else
  1690. auto port = 80;
  1691. Client cli(host, port);
  1692. #endif
  1693. cli.set_connection_timeout(std::chrono::seconds(5));
  1694. uint32_t count = 0;
  1695. auto res =
  1696. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1697. ASSERT_TRUE(!res);
  1698. EXPECT_EQ(Error::Canceled, res.error());
  1699. }
  1700. TEST(CancelTest, NoCancelPost) {
  1701. Server svr;
  1702. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1703. res.set_content("Hello World!", "text/plain");
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. Client cli(HOST, PORT);
  1713. cli.set_connection_timeout(std::chrono::seconds(5));
  1714. auto res =
  1715. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1716. "application/json", [](uint64_t, uint64_t) { return true; });
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ("Hello World!", res->body);
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. }
  1721. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1722. Server svr;
  1723. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1724. res.set_content("Hello World!", "text/plain");
  1725. });
  1726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. Client cli(HOST, PORT);
  1734. cli.set_connection_timeout(std::chrono::seconds(5));
  1735. auto res =
  1736. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1737. "application/json", [](uint64_t, uint64_t) { return false; });
  1738. ASSERT_TRUE(!res);
  1739. EXPECT_EQ(Error::Canceled, res.error());
  1740. }
  1741. TEST(CancelTest, WithCancelLargePayloadPost) {
  1742. Server svr;
  1743. svr.set_payload_max_length(200 * 1024 * 1024);
  1744. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content(LARGE_DATA, "text/plain");
  1746. });
  1747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1748. auto se = detail::scope_exit([&] {
  1749. svr.stop();
  1750. thread.join();
  1751. ASSERT_FALSE(svr.is_running());
  1752. });
  1753. svr.wait_until_ready();
  1754. Client cli(HOST, PORT);
  1755. cli.set_payload_max_length(200 * 1024 * 1024);
  1756. cli.set_connection_timeout(std::chrono::seconds(5));
  1757. auto res =
  1758. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1759. "application/json", [](uint64_t, uint64_t) { return false; });
  1760. ASSERT_TRUE(!res);
  1761. EXPECT_EQ(Error::Canceled, res.error());
  1762. }
  1763. TEST(CancelTest, NoCancelPut) {
  1764. Server svr;
  1765. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1766. res.set_content("Hello World!", "text/plain");
  1767. });
  1768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1769. auto se = detail::scope_exit([&] {
  1770. svr.stop();
  1771. thread.join();
  1772. ASSERT_FALSE(svr.is_running());
  1773. });
  1774. svr.wait_until_ready();
  1775. Client cli(HOST, PORT);
  1776. cli.set_connection_timeout(std::chrono::seconds(5));
  1777. auto res =
  1778. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1779. "application/json", [](uint64_t, uint64_t) { return true; });
  1780. ASSERT_TRUE(res);
  1781. EXPECT_EQ("Hello World!", res->body);
  1782. EXPECT_EQ(StatusCode::OK_200, res->status);
  1783. }
  1784. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1785. Server svr;
  1786. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1787. res.set_content("Hello World!", "text/plain");
  1788. });
  1789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1790. auto se = detail::scope_exit([&] {
  1791. svr.stop();
  1792. thread.join();
  1793. ASSERT_FALSE(svr.is_running());
  1794. });
  1795. svr.wait_until_ready();
  1796. Client cli(HOST, PORT);
  1797. cli.set_connection_timeout(std::chrono::seconds(5));
  1798. auto res =
  1799. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1800. "application/json", [](uint64_t, uint64_t) { return false; });
  1801. ASSERT_TRUE(!res);
  1802. EXPECT_EQ(Error::Canceled, res.error());
  1803. }
  1804. TEST(CancelTest, WithCancelLargePayloadPut) {
  1805. Server svr;
  1806. svr.set_payload_max_length(200 * 1024 * 1024);
  1807. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1808. res.set_content(LARGE_DATA, "text/plain");
  1809. });
  1810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1811. auto se = detail::scope_exit([&] {
  1812. svr.stop();
  1813. thread.join();
  1814. ASSERT_FALSE(svr.is_running());
  1815. });
  1816. svr.wait_until_ready();
  1817. Client cli(HOST, PORT);
  1818. cli.set_payload_max_length(200 * 1024 * 1024);
  1819. cli.set_connection_timeout(std::chrono::seconds(5));
  1820. auto res =
  1821. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1822. "application/json", [](uint64_t, uint64_t) { return false; });
  1823. ASSERT_TRUE(!res);
  1824. EXPECT_EQ(Error::Canceled, res.error());
  1825. }
  1826. TEST(CancelTest, NoCancelPatch) {
  1827. Server svr;
  1828. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1829. res.set_content("Hello World!", "text/plain");
  1830. });
  1831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. Client cli(HOST, PORT);
  1839. cli.set_connection_timeout(std::chrono::seconds(5));
  1840. auto res =
  1841. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1842. "application/json", [](uint64_t, uint64_t) { return true; });
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ("Hello World!", res->body);
  1845. EXPECT_EQ(StatusCode::OK_200, res->status);
  1846. }
  1847. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1848. Server svr;
  1849. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1850. res.set_content("Hello World!", "text/plain");
  1851. });
  1852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1853. auto se = detail::scope_exit([&] {
  1854. svr.stop();
  1855. thread.join();
  1856. ASSERT_FALSE(svr.is_running());
  1857. });
  1858. svr.wait_until_ready();
  1859. Client cli(HOST, PORT);
  1860. cli.set_connection_timeout(std::chrono::seconds(5));
  1861. auto res =
  1862. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1863. "application/json", [](uint64_t, uint64_t) { return false; });
  1864. ASSERT_TRUE(!res);
  1865. EXPECT_EQ(Error::Canceled, res.error());
  1866. }
  1867. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1868. Server svr;
  1869. svr.set_payload_max_length(200 * 1024 * 1024);
  1870. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1871. res.set_content(LARGE_DATA, "text/plain");
  1872. });
  1873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1874. auto se = detail::scope_exit([&] {
  1875. svr.stop();
  1876. thread.join();
  1877. ASSERT_FALSE(svr.is_running());
  1878. });
  1879. svr.wait_until_ready();
  1880. Client cli(HOST, PORT);
  1881. cli.set_payload_max_length(200 * 1024 * 1024);
  1882. cli.set_connection_timeout(std::chrono::seconds(5));
  1883. auto res =
  1884. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1885. "application/json", [](uint64_t, uint64_t) { return false; });
  1886. ASSERT_TRUE(!res);
  1887. EXPECT_EQ(Error::Canceled, res.error());
  1888. }
  1889. TEST(CancelTest, NoCancelDelete) {
  1890. Server svr;
  1891. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1892. res.set_content("Hello World!", "text/plain");
  1893. });
  1894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1895. auto se = detail::scope_exit([&] {
  1896. svr.stop();
  1897. thread.join();
  1898. ASSERT_FALSE(svr.is_running());
  1899. });
  1900. svr.wait_until_ready();
  1901. Client cli(HOST, PORT);
  1902. cli.set_connection_timeout(std::chrono::seconds(5));
  1903. auto res =
  1904. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1905. "application/json", [](uint64_t, uint64_t) { return true; });
  1906. ASSERT_TRUE(res);
  1907. EXPECT_EQ("Hello World!", res->body);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. }
  1910. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1911. Server svr;
  1912. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content("Hello World!", "text/plain");
  1914. });
  1915. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. thread.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. Client cli(HOST, PORT);
  1923. cli.set_connection_timeout(std::chrono::seconds(5));
  1924. auto res =
  1925. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1926. "application/json", [](uint64_t, uint64_t) { return false; });
  1927. ASSERT_TRUE(!res);
  1928. EXPECT_EQ(Error::Canceled, res.error());
  1929. }
  1930. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1931. Server svr;
  1932. svr.set_payload_max_length(200 * 1024 * 1024);
  1933. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1934. res.set_content(LARGE_DATA, "text/plain");
  1935. });
  1936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1937. auto se = detail::scope_exit([&] {
  1938. svr.stop();
  1939. thread.join();
  1940. ASSERT_FALSE(svr.is_running());
  1941. });
  1942. svr.wait_until_ready();
  1943. Client cli(HOST, PORT);
  1944. cli.set_payload_max_length(200 * 1024 * 1024);
  1945. cli.set_connection_timeout(std::chrono::seconds(5));
  1946. auto res =
  1947. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1948. "application/json", [](uint64_t, uint64_t) { return false; });
  1949. ASSERT_TRUE(!res);
  1950. EXPECT_EQ(Error::Canceled, res.error());
  1951. }
  1952. static std::string remove_whitespace(const std::string &input) {
  1953. std::string output;
  1954. output.reserve(input.size());
  1955. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1956. [](unsigned char c) { return !std::isspace(c); });
  1957. return output;
  1958. }
  1959. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1960. auto host = "httpbingo.org";
  1961. auto path = std::string{"/basic-auth/hello/world"};
  1962. #ifdef CPPHTTPLIB_SSL_ENABLED
  1963. auto port = 443;
  1964. SSLClient cli(host, port);
  1965. #else
  1966. auto port = 80;
  1967. Client cli(host, port);
  1968. #endif
  1969. {
  1970. auto res = cli.Get(path);
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1973. }
  1974. {
  1975. auto res = cli.Get(
  1976. path, Headers{make_basic_authentication_header("hello", "world")});
  1977. ASSERT_TRUE(res);
  1978. auto body = remove_whitespace(res->body);
  1979. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1980. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. {
  1984. cli.set_basic_auth("hello", "world");
  1985. auto res = cli.Get(path);
  1986. ASSERT_TRUE(res);
  1987. auto body = remove_whitespace(res->body);
  1988. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1989. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1990. EXPECT_EQ(StatusCode::OK_200, res->status);
  1991. }
  1992. {
  1993. cli.set_basic_auth("hello", "bad");
  1994. auto res = cli.Get(path);
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1997. }
  1998. {
  1999. cli.set_basic_auth("bad", "world");
  2000. auto res = cli.Get(path);
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2003. }
  2004. }
  2005. #ifdef CPPHTTPLIB_SSL_ENABLED
  2006. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2007. auto host = "httpbingo.org";
  2008. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2009. auto paths = std::vector<std::string>{
  2010. "/digest-auth/auth/hello/world/MD5",
  2011. "/digest-auth/auth/hello/world/SHA-256",
  2012. };
  2013. auto port = 443;
  2014. SSLClient cli(host, port);
  2015. {
  2016. auto res = cli.Get(unauth_path);
  2017. ASSERT_TRUE(res);
  2018. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2019. }
  2020. {
  2021. cli.set_digest_auth("hello", "world");
  2022. for (const auto &path : paths) {
  2023. auto res = cli.Get(path.c_str());
  2024. ASSERT_TRUE(res);
  2025. auto body = remove_whitespace(res->body);
  2026. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2027. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. }
  2030. cli.set_digest_auth("hello", "bad");
  2031. for (const auto &path : paths) {
  2032. auto res = cli.Get(path.c_str());
  2033. ASSERT_TRUE(res);
  2034. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2035. }
  2036. }
  2037. }
  2038. #endif
  2039. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2040. auto host = "google.com";
  2041. auto another_host = "example.com";
  2042. auto wrong_ip = "0.0.0.0";
  2043. #ifdef CPPHTTPLIB_SSL_ENABLED
  2044. SSLClient cli(host);
  2045. #else
  2046. Client cli(host);
  2047. #endif
  2048. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2049. auto res = cli.Get("/");
  2050. ASSERT_TRUE(res);
  2051. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2052. }
  2053. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2054. auto host = "google.com";
  2055. auto wrong_ip = "0.0.0.0";
  2056. #ifdef CPPHTTPLIB_SSL_ENABLED
  2057. SSLClient cli(host);
  2058. #else
  2059. Client cli(host);
  2060. #endif
  2061. cli.set_hostname_addr_map({{host, wrong_ip}});
  2062. auto res = cli.Get("/");
  2063. ASSERT_TRUE(!res);
  2064. EXPECT_EQ(Error::Connection, res.error());
  2065. }
  2066. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2067. auto host = "httpbingo.org";
  2068. auto path = std::string{"/absolute-redirect/3"};
  2069. #ifdef CPPHTTPLIB_SSL_ENABLED
  2070. SSLClient cli(host);
  2071. #else
  2072. Client cli(host);
  2073. #endif
  2074. cli.set_follow_location(true);
  2075. auto res = cli.Get(path);
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(StatusCode::OK_200, res->status);
  2078. }
  2079. TEST(RedirectTest, Redirect_Online) {
  2080. auto host = "httpbingo.org";
  2081. auto path = std::string{"/redirect/3"};
  2082. #ifdef CPPHTTPLIB_SSL_ENABLED
  2083. SSLClient cli(host);
  2084. #else
  2085. Client cli(host);
  2086. #endif
  2087. cli.set_follow_location(true);
  2088. auto res = cli.Get(path);
  2089. ASSERT_TRUE(res);
  2090. EXPECT_EQ(StatusCode::OK_200, res->status);
  2091. }
  2092. TEST(RelativeRedirectTest, Redirect_Online) {
  2093. auto host = "httpbingo.org";
  2094. auto path = std::string{"/relative-redirect/3"};
  2095. #ifdef CPPHTTPLIB_SSL_ENABLED
  2096. SSLClient cli(host);
  2097. #else
  2098. Client cli(host);
  2099. #endif
  2100. cli.set_follow_location(true);
  2101. auto res = cli.Get(path);
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(StatusCode::OK_200, res->status);
  2104. }
  2105. TEST(TooManyRedirectTest, Redirect_Online) {
  2106. auto host = "httpbingo.org";
  2107. auto path = std::string{"/redirect/21"};
  2108. #ifdef CPPHTTPLIB_SSL_ENABLED
  2109. SSLClient cli(host);
  2110. #else
  2111. Client cli(host);
  2112. #endif
  2113. cli.set_follow_location(true);
  2114. auto res = cli.Get(path);
  2115. ASSERT_TRUE(!res);
  2116. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2117. }
  2118. #ifdef CPPHTTPLIB_SSL_ENABLED
  2119. TEST(YahooRedirectTest, Redirect_Online) {
  2120. Client cli("yahoo.com");
  2121. auto res = cli.Get("/");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2124. cli.set_follow_location(true);
  2125. res = cli.Get("/");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2129. }
  2130. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2131. #define REDIR_HOST "httpbingo.org"
  2132. #define REDIR_PATH "/redirect-to"
  2133. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2134. SSLClient cli(REDIR_HOST);
  2135. cli.set_follow_location(true);
  2136. auto res =
  2137. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::OK_200, res->status);
  2140. }
  2141. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2142. SSLClient cli(REDIR_HOST);
  2143. cli.set_follow_location(true);
  2144. Params params;
  2145. params.emplace("url", "http://example.com");
  2146. params.emplace("status_code", "302");
  2147. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2148. ASSERT_TRUE(res);
  2149. EXPECT_EQ(StatusCode::OK_200, res->status);
  2150. }
  2151. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2152. SSLClient cli(REDIR_HOST);
  2153. cli.set_follow_location(true);
  2154. Params params;
  2155. params.emplace("url", "http://example.com");
  2156. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2157. ASSERT_TRUE(res);
  2158. EXPECT_EQ(StatusCode::OK_200, res->status);
  2159. }
  2160. TEST(UrlWithSpace, Redirect_Online) {
  2161. SSLClient cli("edge.forgecdn.net");
  2162. cli.set_follow_location(true);
  2163. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2167. }
  2168. #endif
  2169. #if !defined(_WIN32) && !defined(_WIN64)
  2170. TEST(ReceiveSignals, Signal) {
  2171. auto setupSignalHandlers = []() {
  2172. struct sigaction act;
  2173. sigemptyset(&act.sa_mask);
  2174. act.sa_flags = SA_SIGINFO;
  2175. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2176. switch (sig) {
  2177. case SIGINT:
  2178. default: break;
  2179. }
  2180. };
  2181. ::sigaction(SIGINT, &act, nullptr);
  2182. };
  2183. Server svr;
  2184. int port = 0;
  2185. auto thread = std::thread([&]() {
  2186. setupSignalHandlers();
  2187. port = svr.bind_to_any_port(HOST);
  2188. svr.listen_after_bind();
  2189. });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. ASSERT_TRUE(svr.is_running());
  2197. pthread_kill(thread.native_handle(), SIGINT);
  2198. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2199. ASSERT_TRUE(svr.is_running());
  2200. }
  2201. #endif
  2202. TEST(RedirectToDifferentPort, Redirect) {
  2203. Server svr1;
  2204. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2205. res.set_content("Hello World!", "text/plain");
  2206. });
  2207. int svr1_port = 0;
  2208. auto thread1 = std::thread([&]() {
  2209. svr1_port = svr1.bind_to_any_port(HOST);
  2210. svr1.listen_after_bind();
  2211. });
  2212. Server svr2;
  2213. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2214. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2215. });
  2216. int svr2_port = 0;
  2217. auto thread2 = std::thread([&]() {
  2218. svr2_port = svr2.bind_to_any_port(HOST);
  2219. svr2.listen_after_bind();
  2220. });
  2221. auto se = detail::scope_exit([&] {
  2222. svr2.stop();
  2223. thread2.join();
  2224. svr1.stop();
  2225. thread1.join();
  2226. ASSERT_FALSE(svr2.is_running());
  2227. ASSERT_FALSE(svr1.is_running());
  2228. });
  2229. svr1.wait_until_ready();
  2230. svr2.wait_until_ready();
  2231. Client cli("localhost", svr2_port);
  2232. cli.set_follow_location(true);
  2233. auto res = cli.Get("/2");
  2234. ASSERT_TRUE(res);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. EXPECT_EQ("Hello World!", res->body);
  2237. }
  2238. static void
  2239. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2240. Server svr1;
  2241. std::string captured_authorization;
  2242. svr1.Get("/target", [&](const Request &req, Response &res) {
  2243. captured_authorization = req.get_header_value("Authorization");
  2244. res.set_content("OK", "text/plain");
  2245. });
  2246. int svr1_port = 0;
  2247. auto thread1 = std::thread([&]() {
  2248. svr1_port = svr1.bind_to_any_port(HOST);
  2249. svr1.listen_after_bind();
  2250. });
  2251. Server svr2;
  2252. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2253. res.set_redirect(
  2254. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2255. });
  2256. int svr2_port = 0;
  2257. auto thread2 = std::thread([&]() {
  2258. svr2_port = svr2.bind_to_any_port(HOST);
  2259. svr2.listen_after_bind();
  2260. });
  2261. auto se = detail::scope_exit([&] {
  2262. svr2.stop();
  2263. thread2.join();
  2264. svr1.stop();
  2265. thread1.join();
  2266. ASSERT_FALSE(svr2.is_running());
  2267. ASSERT_FALSE(svr1.is_running());
  2268. });
  2269. svr1.wait_until_ready();
  2270. svr2.wait_until_ready();
  2271. Client cli("localhost", svr2_port);
  2272. cli.set_follow_location(true);
  2273. set_auth(cli);
  2274. auto res = cli.Get("/redir");
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2278. EXPECT_TRUE(captured_authorization.empty());
  2279. }
  2280. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2281. TestDoNotForwardCredentialsOnRedirect(
  2282. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2283. }
  2284. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2285. TestDoNotForwardCredentialsOnRedirect(
  2286. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2287. }
  2288. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2289. Server svr;
  2290. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2291. // Port number that overflows int — should not crash
  2292. res.set_redirect("http://localhost:99999999999999999999/target");
  2293. });
  2294. auto port = svr.bind_to_any_port(HOST);
  2295. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2296. auto se = detail::scope_exit([&] {
  2297. svr.stop();
  2298. thread.join();
  2299. ASSERT_FALSE(svr.is_running());
  2300. });
  2301. svr.wait_until_ready();
  2302. Client cli(HOST, port);
  2303. cli.set_follow_location(true);
  2304. auto res = cli.Get("/redir");
  2305. // Should fail gracefully, not crash (no valid response due to bad port)
  2306. EXPECT_FALSE(res);
  2307. }
  2308. TEST(RedirectFromPageWithContent, Redirect) {
  2309. Server svr;
  2310. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2311. res.set_content("___", "text/plain");
  2312. res.set_redirect("/2");
  2313. });
  2314. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2315. res.set_content("Hello World!", "text/plain");
  2316. });
  2317. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2318. auto se = detail::scope_exit([&] {
  2319. svr.stop();
  2320. th.join();
  2321. ASSERT_FALSE(svr.is_running());
  2322. });
  2323. svr.wait_until_ready();
  2324. {
  2325. Client cli("localhost", PORT);
  2326. cli.set_follow_location(true);
  2327. std::string body;
  2328. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2329. body.append(data, data_length);
  2330. return true;
  2331. });
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::OK_200, res->status);
  2334. EXPECT_EQ("Hello World!", body);
  2335. }
  2336. {
  2337. Client cli("localhost", PORT);
  2338. std::string body;
  2339. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2340. body.append(data, data_length);
  2341. return true;
  2342. });
  2343. ASSERT_TRUE(res);
  2344. EXPECT_EQ(StatusCode::Found_302, res->status);
  2345. EXPECT_EQ("___", body);
  2346. }
  2347. }
  2348. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2349. Server svr;
  2350. auto port_str = std::to_string(PORT);
  2351. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2352. auto expected_host = "[::1]:" + port_str;
  2353. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2354. res.set_content("___", "text/plain");
  2355. // res.set_redirect("/2");
  2356. res.set_redirect(redirect_url);
  2357. });
  2358. svr.Get("/2", [&](const Request &req, Response &res) {
  2359. auto host_header = req.headers.find("Host");
  2360. ASSERT_TRUE(host_header != req.headers.end());
  2361. EXPECT_EQ(expected_host, host_header->second);
  2362. res.set_content("Hello World!", "text/plain");
  2363. });
  2364. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2365. auto se = detail::scope_exit([&] {
  2366. svr.stop();
  2367. th.join();
  2368. ASSERT_FALSE(svr.is_running());
  2369. });
  2370. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2371. // actually starts anything, so the condition !svr.is_running() will
  2372. // always remain true, and the loop never stops.
  2373. // This basically counts how many milliseconds have passed since the
  2374. // call to svr.listen(), and if after 5 seconds nothing started yet
  2375. // aborts the test.
  2376. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2377. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2378. ASSERT_LT(milliseconds, 5000U);
  2379. }
  2380. {
  2381. Client cli("::1", PORT);
  2382. cli.set_follow_location(true);
  2383. std::string body;
  2384. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2385. body.append(data, data_length);
  2386. return true;
  2387. });
  2388. ASSERT_TRUE(res);
  2389. EXPECT_EQ(StatusCode::OK_200, res->status);
  2390. EXPECT_EQ("Hello World!", body);
  2391. }
  2392. {
  2393. Client cli("::1", PORT);
  2394. std::string body;
  2395. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2396. body.append(data, data_length);
  2397. return true;
  2398. });
  2399. ASSERT_TRUE(res);
  2400. EXPECT_EQ(StatusCode::Found_302, res->status);
  2401. EXPECT_EQ("___", body);
  2402. }
  2403. }
  2404. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2405. Server svr;
  2406. svr.Get("/foo", [](const Request &req, Response &res) {
  2407. auto a = req.params.find("a");
  2408. if (a != req.params.end()) {
  2409. res.set_content((*a).second, "text/plain");
  2410. res.status = StatusCode::OK_200;
  2411. } else {
  2412. res.status = StatusCode::BadRequest_400;
  2413. }
  2414. });
  2415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2416. auto se = detail::scope_exit([&] {
  2417. svr.stop();
  2418. thread.join();
  2419. ASSERT_FALSE(svr.is_running());
  2420. });
  2421. svr.wait_until_ready();
  2422. {
  2423. Client cli(HOST, PORT);
  2424. cli.set_path_encode(false);
  2425. auto res = cli.Get("/foo?a=explicitly+encoded");
  2426. ASSERT_TRUE(res);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. // This expects it back with a space, as the `+` won't have been
  2429. // url-encoded, and server-side the params get decoded turning `+`
  2430. // into spaces.
  2431. EXPECT_EQ("explicitly encoded", res->body);
  2432. }
  2433. }
  2434. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2435. // When path encoding is disabled the client must transmit the supplied
  2436. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2437. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2438. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2439. // than a space (0x20). Assert on the raw wire target to catch this.
  2440. Server svr;
  2441. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2442. svr.Get("/foo", [&](const Request &req, Response &res) {
  2443. EXPECT_EQ(expected_target, req.target);
  2444. res.status = StatusCode::OK_200;
  2445. });
  2446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. {
  2454. Client cli(HOST, PORT);
  2455. cli.set_path_encode(false);
  2456. auto res = cli.Get(expected_target.c_str());
  2457. ASSERT_TRUE(res);
  2458. EXPECT_EQ(StatusCode::OK_200, res->status);
  2459. }
  2460. }
  2461. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2462. Server svr;
  2463. svr.Get("/", [](const Request &req, Response &) {
  2464. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2465. });
  2466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2467. auto se = detail::scope_exit([&] {
  2468. svr.stop();
  2469. thread.join();
  2470. ASSERT_FALSE(svr.is_running());
  2471. });
  2472. svr.wait_until_ready();
  2473. {
  2474. Client cli(HOST, PORT);
  2475. cli.set_path_encode(false);
  2476. auto res = cli.Get("/?something=%0A");
  2477. ASSERT_TRUE(res);
  2478. EXPECT_EQ(StatusCode::OK_200, res->status);
  2479. }
  2480. }
  2481. TEST(BindServerTest, BindDualStack) {
  2482. Server svr;
  2483. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2484. res.set_content("Hello World!", "text/plain");
  2485. });
  2486. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2487. auto se = detail::scope_exit([&] {
  2488. svr.stop();
  2489. thread.join();
  2490. ASSERT_FALSE(svr.is_running());
  2491. });
  2492. svr.wait_until_ready();
  2493. {
  2494. Client cli("127.0.0.1", PORT);
  2495. auto res = cli.Get("/1");
  2496. ASSERT_TRUE(res);
  2497. EXPECT_EQ(StatusCode::OK_200, res->status);
  2498. EXPECT_EQ("Hello World!", res->body);
  2499. }
  2500. {
  2501. Client cli("::1", PORT);
  2502. auto res = cli.Get("/1");
  2503. ASSERT_TRUE(res);
  2504. EXPECT_EQ(StatusCode::OK_200, res->status);
  2505. EXPECT_EQ("Hello World!", res->body);
  2506. }
  2507. }
  2508. TEST(BindServerTest, BindAndListenSeparately) {
  2509. Server svr;
  2510. int port = svr.bind_to_any_port("0.0.0.0");
  2511. ASSERT_TRUE(svr.is_valid());
  2512. ASSERT_TRUE(port > 0);
  2513. svr.stop();
  2514. }
  2515. #ifdef CPPHTTPLIB_SSL_ENABLED
  2516. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2518. CLIENT_CA_CERT_DIR);
  2519. int port = svr.bind_to_any_port("0.0.0.0");
  2520. ASSERT_TRUE(svr.is_valid());
  2521. ASSERT_TRUE(port > 0);
  2522. svr.stop();
  2523. }
  2524. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2525. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2526. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2527. int port = svr.bind_to_any_port("0.0.0.0");
  2528. ASSERT_TRUE(svr.is_valid());
  2529. ASSERT_TRUE(port > 0);
  2530. svr.stop();
  2531. }
  2532. TEST(BindServerTest, UpdateCertsPem) {
  2533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2534. int port = svr.bind_to_any_port("0.0.0.0");
  2535. ASSERT_TRUE(svr.is_valid());
  2536. ASSERT_TRUE(port > 0);
  2537. // Read PEM files
  2538. std::string cert_pem, key_pem, ca_pem;
  2539. read_file(SERVER_CERT_FILE, cert_pem);
  2540. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2541. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2542. // Update server certificates using PEM API
  2543. ASSERT_TRUE(
  2544. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2545. ASSERT_TRUE(svr.is_valid());
  2546. svr.stop();
  2547. }
  2548. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2549. // Start server with client CA (enables client auth)
  2550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2551. ASSERT_TRUE(svr.is_valid());
  2552. bool handler_called = false;
  2553. svr.Get("/test", [&](const Request &req, Response &res) {
  2554. handler_called = true;
  2555. // Verify client certificate is present
  2556. auto cert = req.peer_cert();
  2557. EXPECT_TRUE(static_cast<bool>(cert));
  2558. res.set_content("ok", "text/plain");
  2559. });
  2560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2561. auto se = detail::scope_exit([&] {
  2562. svr.stop();
  2563. t.join();
  2564. ASSERT_FALSE(svr.is_running());
  2565. });
  2566. svr.wait_until_ready();
  2567. // Read PEM files
  2568. std::string cert_pem, key_pem, ca_pem;
  2569. read_file(SERVER_CERT_FILE, cert_pem);
  2570. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2571. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2572. // Update server certificates and client CA using PEM API while server running
  2573. ASSERT_TRUE(
  2574. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2575. // Connect with client certificate
  2576. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2577. cli.enable_server_certificate_verification(false);
  2578. cli.set_connection_timeout(30);
  2579. auto res = cli.Get("/test");
  2580. ASSERT_TRUE(res);
  2581. ASSERT_EQ(StatusCode::OK_200, res->status);
  2582. ASSERT_TRUE(handler_called);
  2583. EXPECT_EQ("ok", res->body);
  2584. }
  2585. #endif
  2586. TEST(ErrorHandlerTest, ContentLength) {
  2587. Server svr;
  2588. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2589. res.status = StatusCode::OK_200;
  2590. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2591. "text/html"); // <= Content-Length still 13
  2592. });
  2593. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2594. res.set_content("Hello World!\n", "text/plain");
  2595. res.status = 524;
  2596. });
  2597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2598. auto se = detail::scope_exit([&] {
  2599. svr.stop();
  2600. thread.join();
  2601. ASSERT_FALSE(svr.is_running());
  2602. });
  2603. svr.wait_until_ready();
  2604. {
  2605. Client cli(HOST, PORT);
  2606. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2607. ASSERT_TRUE(res);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2610. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2611. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2612. }
  2613. }
  2614. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2615. TEST(ExceptionTest, WithoutExceptionHandler) {
  2616. Server svr;
  2617. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2618. throw std::runtime_error("exception...");
  2619. });
  2620. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2621. throw std::runtime_error("exception\r\n...");
  2622. });
  2623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. listen_thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli("localhost", PORT);
  2631. {
  2632. auto res = cli.Get("/exception");
  2633. ASSERT_TRUE(res);
  2634. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2635. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2636. }
  2637. {
  2638. auto res = cli.Get("/unknown");
  2639. ASSERT_TRUE(res);
  2640. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2641. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2642. }
  2643. }
  2644. TEST(ExceptionTest, WithExceptionHandler) {
  2645. Server svr;
  2646. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2647. std::exception_ptr ep) {
  2648. EXPECT_FALSE(ep == nullptr);
  2649. try {
  2650. std::rethrow_exception(ep);
  2651. } catch (std::exception &e) {
  2652. EXPECT_EQ("abc", std::string(e.what()));
  2653. } catch (...) {}
  2654. res.status = StatusCode::InternalServerError_500;
  2655. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2656. "text/html"); // <= Content-Length still 13 at this point
  2657. });
  2658. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2659. res.set_content("Hello World!\n", "text/plain");
  2660. throw std::runtime_error("abc");
  2661. });
  2662. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2663. auto se = detail::scope_exit([&] {
  2664. svr.stop();
  2665. thread.join();
  2666. ASSERT_FALSE(svr.is_running());
  2667. });
  2668. svr.wait_until_ready();
  2669. for (size_t i = 0; i < 10; i++) {
  2670. Client cli(HOST, PORT);
  2671. for (size_t j = 0; j < 100; j++) {
  2672. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2673. ASSERT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2675. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2676. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2677. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2678. }
  2679. cli.set_keep_alive(true);
  2680. for (size_t j = 0; j < 100; j++) {
  2681. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2684. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2685. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2686. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2687. }
  2688. }
  2689. }
  2690. TEST(ExceptionTest, AndErrorHandler) {
  2691. Server svr;
  2692. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2693. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2694. });
  2695. svr.set_exception_handler(
  2696. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2697. EXPECT_FALSE(ep == nullptr);
  2698. try {
  2699. std::rethrow_exception(ep);
  2700. } catch (std::exception &e) {
  2701. res.set_content(e.what(), "text/html");
  2702. } catch (...) {}
  2703. res.status = StatusCode::InternalServerError_500;
  2704. });
  2705. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2706. throw std::runtime_error("EXCEPTION");
  2707. });
  2708. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2709. res.set_content("ERROR", "text/html");
  2710. res.status = StatusCode::InternalServerError_500;
  2711. });
  2712. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2713. auto se = detail::scope_exit([&] {
  2714. svr.stop();
  2715. thread.join();
  2716. ASSERT_FALSE(svr.is_running());
  2717. });
  2718. svr.wait_until_ready();
  2719. Client cli(HOST, PORT);
  2720. {
  2721. auto res = cli.Get("/exception");
  2722. ASSERT_TRUE(res);
  2723. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2724. EXPECT_EQ("EXCEPTION", res->body);
  2725. }
  2726. {
  2727. auto res = cli.Get("/error");
  2728. ASSERT_TRUE(res);
  2729. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2730. EXPECT_EQ("ERROR", res->body);
  2731. }
  2732. {
  2733. auto res = cli.Get("/invalid");
  2734. ASSERT_TRUE(res);
  2735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2736. EXPECT_EQ("NOT_FOUND", res->body);
  2737. }
  2738. }
  2739. #endif
  2740. TEST(NoContentTest, ContentLength) {
  2741. Server svr;
  2742. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2743. res.status = StatusCode::NoContent_204;
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. {
  2753. Client cli(HOST, PORT);
  2754. auto res = cli.Get("/hi");
  2755. ASSERT_TRUE(res);
  2756. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2757. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2758. }
  2759. }
  2760. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2763. ASSERT_TRUE(svr.is_valid());
  2764. #else
  2765. Server svr;
  2766. #endif
  2767. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2768. if (req.path == "/routing_handler") {
  2769. res.set_header("PRE_ROUTING", "on");
  2770. res.set_content("Routing Handler", "text/plain");
  2771. return httplib::Server::HandlerResponse::Handled;
  2772. }
  2773. return httplib::Server::HandlerResponse::Unhandled;
  2774. });
  2775. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2776. res.set_content("Error", "text/html");
  2777. });
  2778. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2779. if (req.path == "/routing_handler") {
  2780. res.set_header("POST_ROUTING", "on");
  2781. }
  2782. });
  2783. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!\n", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. {
  2794. #ifdef CPPHTTPLIB_SSL_ENABLED
  2795. SSLClient cli(HOST, PORT);
  2796. cli.enable_server_certificate_verification(false);
  2797. #else
  2798. Client cli(HOST, PORT);
  2799. #endif
  2800. auto res = cli.Get("/routing_handler");
  2801. ASSERT_TRUE(res);
  2802. EXPECT_EQ(StatusCode::OK_200, res->status);
  2803. EXPECT_EQ("Routing Handler", res->body);
  2804. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2805. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2806. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2807. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2808. }
  2809. {
  2810. #ifdef CPPHTTPLIB_SSL_ENABLED
  2811. SSLClient cli(HOST, PORT);
  2812. cli.enable_server_certificate_verification(false);
  2813. #else
  2814. Client cli(HOST, PORT);
  2815. #endif
  2816. auto res = cli.Get("/hi");
  2817. ASSERT_TRUE(res);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. EXPECT_EQ("Hello World!\n", res->body);
  2820. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2821. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2822. }
  2823. {
  2824. #ifdef CPPHTTPLIB_SSL_ENABLED
  2825. SSLClient cli(HOST, PORT);
  2826. cli.enable_server_certificate_verification(false);
  2827. #else
  2828. Client cli(HOST, PORT);
  2829. #endif
  2830. auto res = cli.Get("/aaa");
  2831. ASSERT_TRUE(res);
  2832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2833. EXPECT_EQ("Error", res->body);
  2834. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2835. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2836. }
  2837. }
  2838. TEST(RequestHandlerTest, PreRequestHandler) {
  2839. auto route_path = "/user/:user";
  2840. Server svr;
  2841. svr.Get("/hi", [](const Request &, Response &res) {
  2842. res.set_content("hi", "text/plain");
  2843. });
  2844. svr.Get(route_path, [](const Request &req, Response &res) {
  2845. res.set_content(req.path_params.at("user"), "text/plain");
  2846. });
  2847. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2848. if (req.matched_route == route_path) {
  2849. auto user = req.path_params.at("user");
  2850. if (user != "john") {
  2851. res.status = StatusCode::Forbidden_403;
  2852. res.set_content("error", "text/html");
  2853. return Server::HandlerResponse::Handled;
  2854. }
  2855. }
  2856. return Server::HandlerResponse::Unhandled;
  2857. });
  2858. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2859. auto se = detail::scope_exit([&] {
  2860. svr.stop();
  2861. thread.join();
  2862. ASSERT_FALSE(svr.is_running());
  2863. });
  2864. svr.wait_until_ready();
  2865. Client cli(HOST, PORT);
  2866. {
  2867. auto res = cli.Get("/hi");
  2868. ASSERT_TRUE(res);
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. EXPECT_EQ("hi", res->body);
  2871. }
  2872. {
  2873. auto res = cli.Get("/user/john");
  2874. ASSERT_TRUE(res);
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. EXPECT_EQ("john", res->body);
  2877. }
  2878. {
  2879. auto res = cli.Get("/user/invalid-user");
  2880. ASSERT_TRUE(res);
  2881. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2882. EXPECT_EQ("error", res->body);
  2883. }
  2884. }
  2885. // The pre-request handler must run before the request body is read, so a
  2886. // rejected request never forces the server to buffer a (potentially large)
  2887. // body. Here the posted body is larger than the payload limit: if the body
  2888. // were read first the server would answer 413, but because the pre-request
  2889. // handler runs first it answers 403 and the body is never read.
  2890. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2891. Server svr;
  2892. svr.set_payload_max_length(8);
  2893. auto handler_ran = false;
  2894. svr.Post("/reject", [&](const Request &req, Response &res) {
  2895. handler_ran = true;
  2896. res.set_content(req.body, "text/plain");
  2897. });
  2898. svr.Post("/accept", [](const Request &req, Response &res) {
  2899. res.set_content(req.body, "text/plain");
  2900. });
  2901. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2902. if (req.matched_route == "/reject") {
  2903. res.status = StatusCode::Forbidden_403;
  2904. res.set_content("denied", "text/plain");
  2905. return Server::HandlerResponse::Handled;
  2906. }
  2907. return Server::HandlerResponse::Unhandled;
  2908. });
  2909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2910. auto se = detail::scope_exit([&] {
  2911. svr.stop();
  2912. thread.join();
  2913. ASSERT_FALSE(svr.is_running());
  2914. });
  2915. svr.wait_until_ready();
  2916. Client cli(HOST, PORT);
  2917. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2918. // rejects with 403 before the body is read, so 413 is never reached.
  2919. {
  2920. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2921. ASSERT_TRUE(res);
  2922. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2923. EXPECT_EQ("denied", res->body);
  2924. EXPECT_FALSE(handler_ran);
  2925. }
  2926. // An approved route still reads the body and enforces the payload limit.
  2927. {
  2928. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2929. ASSERT_TRUE(res);
  2930. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2931. }
  2932. }
  2933. TEST(UserDataTest, BasicOperations) {
  2934. httplib::UserData ud;
  2935. // Initially empty
  2936. EXPECT_FALSE(ud.has("key"));
  2937. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2938. // set and get
  2939. ud.set("key", 42);
  2940. EXPECT_TRUE(ud.has("key"));
  2941. auto *p = ud.get<int>("key");
  2942. ASSERT_NE(nullptr, p);
  2943. EXPECT_EQ(42, *p);
  2944. // Type mismatch → nullptr
  2945. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2946. // Overwrite with different type
  2947. ud.set("key", std::string("hello"));
  2948. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2949. auto *s = ud.get<std::string>("key");
  2950. ASSERT_NE(nullptr, s);
  2951. EXPECT_EQ("hello", *s);
  2952. // erase
  2953. ud.erase("key");
  2954. EXPECT_FALSE(ud.has("key"));
  2955. // clear
  2956. ud.set("a", 1);
  2957. ud.set("b", 2);
  2958. ud.clear();
  2959. EXPECT_FALSE(ud.has("a"));
  2960. EXPECT_FALSE(ud.has("b"));
  2961. }
  2962. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2963. struct AuthCtx {
  2964. std::string user_id;
  2965. };
  2966. Server svr;
  2967. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2968. res.user_data.set("auth", AuthCtx{"alice"});
  2969. return Server::HandlerResponse::Unhandled;
  2970. });
  2971. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2972. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2973. ASSERT_NE(nullptr, ctx);
  2974. res.set_content("Hello " + ctx->user_id, "text/plain");
  2975. });
  2976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. thread.join();
  2980. ASSERT_FALSE(svr.is_running());
  2981. });
  2982. svr.wait_until_ready();
  2983. Client cli(HOST, PORT);
  2984. auto res = cli.Get("/me");
  2985. ASSERT_TRUE(res);
  2986. EXPECT_EQ(StatusCode::OK_200, res->status);
  2987. EXPECT_EQ("Hello alice", res->body);
  2988. }
  2989. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2990. struct RoleCtx {
  2991. std::string role;
  2992. };
  2993. Server svr;
  2994. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2995. res.user_data.set("role", RoleCtx{"admin"});
  2996. return Server::HandlerResponse::Unhandled;
  2997. });
  2998. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2999. auto *ctx = res.user_data.get<RoleCtx>("role");
  3000. ASSERT_NE(nullptr, ctx);
  3001. res.set_content(ctx->role, "text/plain");
  3002. });
  3003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3004. auto se = detail::scope_exit([&] {
  3005. svr.stop();
  3006. thread.join();
  3007. ASSERT_FALSE(svr.is_running());
  3008. });
  3009. svr.wait_until_ready();
  3010. Client cli(HOST, PORT);
  3011. auto res = cli.Get("/role");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. EXPECT_EQ("admin", res->body);
  3015. }
  3016. TEST(InvalidFormatTest, StatusCode) {
  3017. Server svr;
  3018. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3019. res.set_content("Hello World!\n", "text/plain");
  3020. res.status = 9999; // Status should be a three-digit code...
  3021. });
  3022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3023. auto se = detail::scope_exit([&] {
  3024. svr.stop();
  3025. thread.join();
  3026. ASSERT_FALSE(svr.is_running());
  3027. });
  3028. svr.wait_until_ready();
  3029. {
  3030. Client cli(HOST, PORT);
  3031. auto res = cli.Get("/hi");
  3032. ASSERT_FALSE(res);
  3033. }
  3034. }
  3035. TEST(URLFragmentTest, WithFragment) {
  3036. Server svr;
  3037. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3038. EXPECT_TRUE(req.target == "/hi");
  3039. });
  3040. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3041. auto se = detail::scope_exit([&] {
  3042. svr.stop();
  3043. thread.join();
  3044. ASSERT_FALSE(svr.is_running());
  3045. });
  3046. svr.wait_until_ready();
  3047. {
  3048. Client cli(HOST, PORT);
  3049. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3050. EXPECT_TRUE(res);
  3051. EXPECT_EQ(StatusCode::OK_200, res->status);
  3052. res = cli.Get("/hi%23key1=val1=key2=val2");
  3053. EXPECT_TRUE(res);
  3054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3055. }
  3056. }
  3057. TEST(HeaderWriter, SetHeaderWriter) {
  3058. Server svr;
  3059. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3060. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3061. return detail::write_headers(strm, hdrs);
  3062. });
  3063. svr.Get("/hi", [](const Request &req, Response &res) {
  3064. auto it = req.headers.find("CustomClientHeader");
  3065. EXPECT_TRUE(it != req.headers.end());
  3066. EXPECT_EQ(it->second, "CustomClientValue");
  3067. res.set_content("Hello World!\n", "text/plain");
  3068. });
  3069. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3070. auto se = detail::scope_exit([&] {
  3071. svr.stop();
  3072. thread.join();
  3073. ASSERT_FALSE(svr.is_running());
  3074. });
  3075. svr.wait_until_ready();
  3076. {
  3077. Client cli(HOST, PORT);
  3078. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3079. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3080. return detail::write_headers(strm, hdrs);
  3081. });
  3082. auto res = cli.Get("/hi");
  3083. EXPECT_TRUE(res);
  3084. EXPECT_EQ(StatusCode::OK_200, res->status);
  3085. auto it = res->headers.find("CustomServerHeader");
  3086. EXPECT_TRUE(it != res->headers.end());
  3087. EXPECT_EQ(it->second, "CustomServerValue");
  3088. }
  3089. }
  3090. class ServerTest : public ::testing::Test {
  3091. protected:
  3092. ServerTest()
  3093. : cli_(HOST, PORT)
  3094. #ifdef CPPHTTPLIB_SSL_ENABLED
  3095. ,
  3096. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3097. #endif
  3098. {
  3099. #ifdef CPPHTTPLIB_SSL_ENABLED
  3100. cli_.enable_server_certificate_verification(false);
  3101. #endif
  3102. // Allow LARGE_DATA (100MB) responses
  3103. cli_.set_payload_max_length(200 * 1024 * 1024);
  3104. }
  3105. virtual void SetUp() {
  3106. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3107. svr_.set_payload_max_length(200 * 1024 * 1024);
  3108. svr_.set_mount_point("/", "./www");
  3109. svr_.set_mount_point("/mount", "./www2");
  3110. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3111. svr_.Get("/hi",
  3112. [&](const Request & /*req*/, Response &res) {
  3113. res.set_content("Hello World!", "text/plain");
  3114. })
  3115. .Get("/file_content",
  3116. [&](const Request & /*req*/, Response &res) {
  3117. res.set_file_content("./www/dir/test.html");
  3118. })
  3119. .Get("/file_content_with_content_type",
  3120. [&](const Request & /*req*/, Response &res) {
  3121. res.set_file_content("./www/file", "text/plain");
  3122. })
  3123. .Get("/invalid_file_content",
  3124. [&](const Request & /*req*/, Response &res) {
  3125. res.set_file_content("./www/dir/invalid_file_path");
  3126. })
  3127. .Get("/http_response_splitting",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3130. EXPECT_EQ(0U, res.headers.size());
  3131. EXPECT_FALSE(res.has_header("a"));
  3132. res.set_header("a", "1\nSet-Cookie: a=1");
  3133. EXPECT_EQ(0U, res.headers.size());
  3134. EXPECT_FALSE(res.has_header("a"));
  3135. res.set_header("a", "1\rSet-Cookie: a=1");
  3136. EXPECT_EQ(0U, res.headers.size());
  3137. EXPECT_FALSE(res.has_header("a"));
  3138. res.set_header("a\r\nb", "0");
  3139. EXPECT_EQ(0U, res.headers.size());
  3140. EXPECT_FALSE(res.has_header("a"));
  3141. res.set_header("a\rb", "0");
  3142. EXPECT_EQ(0U, res.headers.size());
  3143. EXPECT_FALSE(res.has_header("a"));
  3144. res.set_header("a\nb", "0");
  3145. EXPECT_EQ(0U, res.headers.size());
  3146. EXPECT_FALSE(res.has_header("a"));
  3147. res.set_redirect("1\r\nSet-Cookie: a=1");
  3148. EXPECT_EQ(0U, res.headers.size());
  3149. EXPECT_FALSE(res.has_header("Location"));
  3150. })
  3151. .Get("/slow",
  3152. [&](const Request & /*req*/, Response &res) {
  3153. std::this_thread::sleep_for(std::chrono::seconds(4));
  3154. res.set_content("slow", "text/plain");
  3155. })
  3156. #if 0
  3157. .Post("/slowpost",
  3158. [&](const Request & /*req*/, Response &res) {
  3159. std::this_thread::sleep_for(std::chrono::seconds(2));
  3160. res.set_content("slow", "text/plain");
  3161. })
  3162. #endif
  3163. .Get("/remote_addr",
  3164. [&](const Request &req, Response &res) {
  3165. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3166. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3167. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3168. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3169. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3170. #endif
  3171. res.set_content(req.remote_addr, "text/plain");
  3172. })
  3173. .Get("/local_addr",
  3174. [&](const Request &req, Response &res) {
  3175. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3176. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3177. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3178. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3179. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3180. #endif
  3181. auto local_addr = req.local_addr;
  3182. auto local_port = std::to_string(req.local_port);
  3183. res.set_content(local_addr.append(":").append(local_port),
  3184. "text/plain");
  3185. })
  3186. .Get("/endwith%",
  3187. [&](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. })
  3190. .Get("/a\\+\\+b",
  3191. [&](const Request &req, Response &res) {
  3192. ASSERT_TRUE(req.has_param("a +b"));
  3193. auto val = req.get_param_value("a +b");
  3194. res.set_content(val, "text/plain");
  3195. })
  3196. .Get("/", [&](const Request & /*req*/,
  3197. Response &res) { res.set_redirect("/hi"); })
  3198. .Post("/1",
  3199. [](const Request & /*req*/, Response &res) {
  3200. res.set_redirect("/2", StatusCode::SeeOther_303);
  3201. })
  3202. .Get("/2",
  3203. [](const Request & /*req*/, Response &res) {
  3204. res.set_content("redirected.", "text/plain");
  3205. res.status = StatusCode::OK_200;
  3206. })
  3207. .Post("/person",
  3208. [&](const Request &req, Response &res) {
  3209. if (req.has_param("name") && req.has_param("note")) {
  3210. persons_[req.get_param_value("name")] =
  3211. req.get_param_value("note");
  3212. } else {
  3213. res.status = StatusCode::BadRequest_400;
  3214. }
  3215. })
  3216. .Put("/person",
  3217. [&](const Request &req, Response &res) {
  3218. if (req.has_param("name") && req.has_param("note")) {
  3219. persons_[req.get_param_value("name")] =
  3220. req.get_param_value("note");
  3221. } else {
  3222. res.status = StatusCode::BadRequest_400;
  3223. }
  3224. })
  3225. .Get("/person/(.*)",
  3226. [&](const Request &req, Response &res) {
  3227. string name = req.matches[1];
  3228. if (persons_.find(name) != persons_.end()) {
  3229. auto note = persons_[name];
  3230. res.set_content(note, "text/plain");
  3231. } else {
  3232. res.status = StatusCode::NotFound_404;
  3233. }
  3234. })
  3235. .Delete("/person",
  3236. [&](const Request &req, Response &res) {
  3237. if (req.has_param("name")) {
  3238. string name = req.get_param_value("name");
  3239. if (persons_.find(name) != persons_.end()) {
  3240. persons_.erase(name);
  3241. res.set_content("DELETED", "text/plain");
  3242. } else {
  3243. res.status = StatusCode::NotFound_404;
  3244. }
  3245. } else {
  3246. res.status = StatusCode::BadRequest_400;
  3247. }
  3248. })
  3249. .Post("/x-www-form-urlencoded-json",
  3250. [&](const Request &req, Response &res) {
  3251. auto json = req.get_param_value("json");
  3252. ASSERT_EQ(JSON_DATA, json);
  3253. res.set_content(json, "appliation/json");
  3254. res.status = StatusCode::OK_200;
  3255. })
  3256. .Get("/streamed-chunked",
  3257. [&](const Request & /*req*/, Response &res) {
  3258. res.set_chunked_content_provider(
  3259. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3260. sink.os << "123";
  3261. sink.os << "456";
  3262. sink.os << "789";
  3263. sink.done();
  3264. return true;
  3265. });
  3266. })
  3267. .Get("/streamed-chunked-with-prohibited-trailer",
  3268. [&](const Request & /*req*/, Response &res) {
  3269. auto i = new int(0);
  3270. // Declare both a prohibited trailer (Content-Length) and an
  3271. // allowed one
  3272. res.set_header("Trailer", "Content-Length, X-Allowed");
  3273. res.set_chunked_content_provider(
  3274. "text/plain",
  3275. [i](size_t /*offset*/, DataSink &sink) {
  3276. switch (*i) {
  3277. case 0: sink.os << "123"; break;
  3278. case 1: sink.os << "456"; break;
  3279. case 2: sink.os << "789"; break;
  3280. case 3: {
  3281. sink.done_with_trailer(
  3282. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3283. } break;
  3284. }
  3285. (*i)++;
  3286. return true;
  3287. },
  3288. [i](bool success) {
  3289. EXPECT_TRUE(success);
  3290. delete i;
  3291. });
  3292. })
  3293. .Get("/streamed-chunked2",
  3294. [&](const Request & /*req*/, Response &res) {
  3295. auto i = new int(0);
  3296. res.set_chunked_content_provider(
  3297. "text/plain",
  3298. [i](size_t /*offset*/, DataSink &sink) {
  3299. switch (*i) {
  3300. case 0: sink.os << "123"; break;
  3301. case 1: sink.os << "456"; break;
  3302. case 2: sink.os << "789"; break;
  3303. case 3: sink.done(); break;
  3304. }
  3305. (*i)++;
  3306. return true;
  3307. },
  3308. [i](bool success) {
  3309. EXPECT_TRUE(success);
  3310. delete i;
  3311. });
  3312. })
  3313. .Get("/streamed-chunked-with-trailer",
  3314. [&](const Request & /*req*/, Response &res) {
  3315. auto i = new int(0);
  3316. res.set_header("Trailer", "Dummy1, Dummy2");
  3317. res.set_chunked_content_provider(
  3318. "text/plain",
  3319. [i](size_t /*offset*/, DataSink &sink) {
  3320. switch (*i) {
  3321. case 0: sink.os << "123"; break;
  3322. case 1: sink.os << "456"; break;
  3323. case 2: sink.os << "789"; break;
  3324. case 3: {
  3325. sink.done_with_trailer(
  3326. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3327. } break;
  3328. }
  3329. (*i)++;
  3330. return true;
  3331. },
  3332. [i](bool success) {
  3333. EXPECT_TRUE(success);
  3334. delete i;
  3335. });
  3336. })
  3337. .Get("/streamed",
  3338. [&](const Request & /*req*/, Response &res) {
  3339. res.set_content_provider(
  3340. 6, "text/plain",
  3341. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3342. sink.os << (offset < 3 ? "a" : "b");
  3343. return true;
  3344. });
  3345. })
  3346. .Get("/streamed-without-length",
  3347. [&](const Request & /*req*/, Response &res) {
  3348. auto data = new std::string("abcdefg");
  3349. res.set_content_provider(
  3350. "text/plain",
  3351. [data](size_t offset, DataSink &sink) {
  3352. if (offset < data->size()) {
  3353. sink.os << data->substr(offset);
  3354. }
  3355. sink.done();
  3356. return true;
  3357. },
  3358. [data](bool success) {
  3359. EXPECT_TRUE(success);
  3360. delete data;
  3361. });
  3362. })
  3363. .Get("/streamed-with-range",
  3364. [&](const Request &req, Response &res) {
  3365. auto data = new std::string("abcdefg");
  3366. res.set_content_provider(
  3367. data->size(), "text/plain",
  3368. [data](size_t offset, size_t length, DataSink &sink) {
  3369. size_t DATA_CHUNK_SIZE = 4;
  3370. const auto &d = *data;
  3371. auto out_len =
  3372. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3373. auto ret =
  3374. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3375. EXPECT_TRUE(ret);
  3376. return true;
  3377. },
  3378. [data, &req](bool success) {
  3379. EXPECT_EQ(success, !req.has_param("error"));
  3380. delete data;
  3381. });
  3382. })
  3383. .Get("/streamed-cancel",
  3384. [&](const Request & /*req*/, Response &res) {
  3385. res.set_content_provider(
  3386. size_t(-1), "text/plain",
  3387. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3388. sink.os << "data_chunk";
  3389. return true;
  3390. });
  3391. })
  3392. .Get("/regex-with-delimiter",
  3393. [&](const Request &req, Response & /*res*/) {
  3394. ASSERT_TRUE(req.has_param("key"));
  3395. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3396. })
  3397. .Get("/with-range",
  3398. [&](const Request & /*req*/, Response &res) {
  3399. res.set_content("abcdefg", "text/plain");
  3400. })
  3401. .Get("/test-start-time",
  3402. [&](const Request &req, Response & /*res*/) {
  3403. EXPECT_NE(req.start_time_,
  3404. std::chrono::steady_clock::time_point::min());
  3405. })
  3406. .Get("/with-range-customized-response",
  3407. [&](const Request & /*req*/, Response &res) {
  3408. res.status = StatusCode::BadRequest_400;
  3409. res.set_content(JSON_DATA, "application/json");
  3410. })
  3411. .Post("/chunked",
  3412. [&](const Request &req, Response & /*res*/) {
  3413. EXPECT_EQ(req.body, "dechunked post body");
  3414. })
  3415. .Post("/large-chunked",
  3416. [&](const Request &req, Response & /*res*/) {
  3417. std::string expected(6 * 30 * 1024u, 'a');
  3418. EXPECT_EQ(req.body, expected);
  3419. })
  3420. .Post("/multipart",
  3421. [&](const Request &req, Response & /*res*/) {
  3422. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3423. req.form.get_field_count("text2") +
  3424. req.form.get_field_count("file3") +
  3425. req.form.get_field_count("file4"));
  3426. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3427. req.form.get_file_count("file2"));
  3428. ASSERT_TRUE(!req.form.has_file("???"));
  3429. ASSERT_TRUE(!req.form.has_field("???"));
  3430. ASSERT_TRUE(req.body.empty());
  3431. {
  3432. const auto &text = req.form.get_field("text1");
  3433. EXPECT_EQ("text default", text);
  3434. }
  3435. {
  3436. const auto &text = req.form.get_field("text2");
  3437. EXPECT_EQ("aωb", text);
  3438. }
  3439. {
  3440. const auto &file = req.form.get_file("file1");
  3441. EXPECT_EQ("hello.txt", file.filename);
  3442. EXPECT_EQ("text/plain", file.content_type);
  3443. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3444. }
  3445. {
  3446. const auto &file = req.form.get_file("file2");
  3447. EXPECT_EQ("world.json", file.filename);
  3448. EXPECT_EQ("application/json", file.content_type);
  3449. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3450. }
  3451. {
  3452. const auto &text = req.form.get_field("file3");
  3453. EXPECT_EQ(0u, text.size());
  3454. }
  3455. {
  3456. const auto &text = req.form.get_field("file4");
  3457. EXPECT_EQ(0u, text.size());
  3458. }
  3459. })
  3460. .Post("/multipart/multi_file_values",
  3461. [&](const Request &req, Response & /*res*/) {
  3462. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3463. req.form.get_field_count("multi_text1"));
  3464. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3465. ASSERT_TRUE(!req.form.has_file("???"));
  3466. ASSERT_TRUE(!req.form.has_field("???"));
  3467. ASSERT_TRUE(req.body.empty());
  3468. {
  3469. const auto &text = req.form.get_field("text");
  3470. EXPECT_EQ("default text", text);
  3471. }
  3472. {
  3473. const auto &text1_values = req.form.get_fields("multi_text1");
  3474. EXPECT_EQ(2u, text1_values.size());
  3475. EXPECT_EQ("aaaaa", text1_values[0]);
  3476. EXPECT_EQ("bbbbb", text1_values[1]);
  3477. }
  3478. {
  3479. const auto &file1_values = req.form.get_files("multi_file1");
  3480. EXPECT_EQ(2u, file1_values.size());
  3481. auto file1 = file1_values[0];
  3482. EXPECT_EQ(file1.filename, "hello.txt");
  3483. EXPECT_EQ(file1.content_type, "text/plain");
  3484. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3485. auto file2 = file1_values[1];
  3486. EXPECT_EQ(file2.filename, "world.json");
  3487. EXPECT_EQ(file2.content_type, "application/json");
  3488. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3489. }
  3490. })
  3491. .Post("/empty",
  3492. [&](const Request &req, Response &res) {
  3493. EXPECT_EQ(req.body, "");
  3494. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3495. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3496. res.set_content("empty", "text/plain");
  3497. })
  3498. .Post("/empty-no-content-type",
  3499. [&](const Request &req, Response &res) {
  3500. EXPECT_EQ(req.body, "");
  3501. EXPECT_FALSE(req.has_header("Content-Type"));
  3502. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3503. res.set_content("empty-no-content-type", "text/plain");
  3504. })
  3505. .Post("/path-only",
  3506. [&](const Request &req, Response &res) {
  3507. EXPECT_EQ(req.body, "");
  3508. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3509. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3510. res.set_content("path-only", "text/plain");
  3511. })
  3512. .Post("/path-headers-only",
  3513. [&](const Request &req, Response &res) {
  3514. EXPECT_EQ(req.body, "");
  3515. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3516. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3517. EXPECT_EQ("world", req.get_header_value("hello"));
  3518. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3519. res.set_content("path-headers-only", "text/plain");
  3520. })
  3521. .Post("/post-large",
  3522. [&](const Request &req, Response &res) {
  3523. EXPECT_EQ(req.body, LARGE_DATA);
  3524. res.set_content(req.body, "text/plain");
  3525. })
  3526. .Post("/post-loopback",
  3527. [&](const Request &, Response &res,
  3528. ContentReader const &content_reader) {
  3529. std::string body;
  3530. content_reader([&](const char *data, size_t data_length) {
  3531. body.append(data, data_length);
  3532. return true;
  3533. });
  3534. res.set_content(body, "text/plain");
  3535. })
  3536. .Put("/put-loopback",
  3537. [&](const Request &, Response &res,
  3538. ContentReader const &content_reader) {
  3539. std::string body;
  3540. content_reader([&](const char *data, size_t data_length) {
  3541. body.append(data, data_length);
  3542. return true;
  3543. });
  3544. res.set_content(body, "text/plain");
  3545. })
  3546. .Patch("/patch-loopback",
  3547. [&](const Request &, Response &res,
  3548. ContentReader const &content_reader) {
  3549. std::string body;
  3550. content_reader([&](const char *data, size_t data_length) {
  3551. body.append(data, data_length);
  3552. return true;
  3553. });
  3554. res.set_content(body, "text/plain");
  3555. })
  3556. .Put("/empty-no-content-type",
  3557. [&](const Request &req, Response &res) {
  3558. EXPECT_EQ(req.body, "");
  3559. EXPECT_FALSE(req.has_header("Content-Type"));
  3560. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3561. res.set_content("empty-no-content-type", "text/plain");
  3562. })
  3563. .Put("/put",
  3564. [&](const Request &req, Response &res) {
  3565. EXPECT_EQ(req.body, "PUT");
  3566. res.set_content(req.body, "text/plain");
  3567. })
  3568. .Put("/put-large",
  3569. [&](const Request &req, Response &res) {
  3570. EXPECT_EQ(req.body, LARGE_DATA);
  3571. res.set_content(req.body, "text/plain");
  3572. })
  3573. .Patch("/patch",
  3574. [&](const Request &req, Response &res) {
  3575. EXPECT_EQ(req.body, "PATCH");
  3576. res.set_content(req.body, "text/plain");
  3577. })
  3578. .Delete("/delete",
  3579. [&](const Request & /*req*/, Response &res) {
  3580. res.set_content("DELETE", "text/plain");
  3581. })
  3582. .Delete("/delete-body",
  3583. [&](const Request &req, Response &res) {
  3584. EXPECT_EQ(req.body, "content");
  3585. res.set_content(req.body, "text/plain");
  3586. })
  3587. .Options(R"(\*)",
  3588. [&](const Request & /*req*/, Response &res) {
  3589. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3590. })
  3591. .Get("/request-target",
  3592. [&](const Request &req, Response & /*res*/) {
  3593. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3594. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3595. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3596. })
  3597. .Get("/long-query-value",
  3598. [&](const Request &req, Response & /*res*/) {
  3599. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3600. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3601. })
  3602. .Get("/too-long-query-value",
  3603. [&](const Request &req, Response & /*res*/) {
  3604. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3605. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3606. })
  3607. .Get("/array-param",
  3608. [&](const Request &req, Response & /*res*/) {
  3609. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3610. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3611. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3612. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3613. })
  3614. .Get("/array-param-values",
  3615. [&](const Request &req, Response & /*res*/) {
  3616. auto values = req.get_param_values("array");
  3617. EXPECT_EQ(3u, values.size());
  3618. EXPECT_EQ("value1", values[0]);
  3619. EXPECT_EQ("value2", values[1]);
  3620. EXPECT_EQ("value3", values[2]);
  3621. auto empty = req.get_param_values("nonexistent");
  3622. EXPECT_TRUE(empty.empty());
  3623. })
  3624. .Post("/validate-no-multiple-headers",
  3625. [&](const Request &req, Response & /*res*/) {
  3626. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3627. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3628. })
  3629. .Post("/content_receiver",
  3630. [&](const Request &req, Response &res,
  3631. const ContentReader &content_reader) {
  3632. if (req.is_multipart_form_data()) {
  3633. std::vector<FormData> items;
  3634. content_reader(
  3635. [&](const FormData &file) {
  3636. items.push_back(file);
  3637. return true;
  3638. },
  3639. [&](const char *data, size_t data_length) {
  3640. items.back().content.append(data, data_length);
  3641. return true;
  3642. });
  3643. EXPECT_EQ(5u, items.size());
  3644. {
  3645. const auto &file = get_file_value(items, "text1");
  3646. EXPECT_TRUE(file.filename.empty());
  3647. EXPECT_EQ("text default", file.content);
  3648. }
  3649. {
  3650. const auto &file = get_file_value(items, "text2");
  3651. EXPECT_TRUE(file.filename.empty());
  3652. EXPECT_EQ("aωb", file.content);
  3653. }
  3654. {
  3655. const auto &file = get_file_value(items, "file1");
  3656. EXPECT_EQ("hello.txt", file.filename);
  3657. EXPECT_EQ("text/plain", file.content_type);
  3658. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3659. }
  3660. {
  3661. const auto &file = get_file_value(items, "file2");
  3662. EXPECT_EQ("world.json", file.filename);
  3663. EXPECT_EQ("application/json", file.content_type);
  3664. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3665. }
  3666. {
  3667. const auto &file = get_file_value(items, "file3");
  3668. EXPECT_TRUE(file.filename.empty());
  3669. EXPECT_EQ("application/octet-stream", file.content_type);
  3670. EXPECT_EQ(0u, file.content.size());
  3671. }
  3672. } else {
  3673. std::string body;
  3674. content_reader([&](const char *data, size_t data_length) {
  3675. EXPECT_EQ(7U, data_length);
  3676. body.append(data, data_length);
  3677. return true;
  3678. });
  3679. EXPECT_EQ(body, "content");
  3680. res.set_content(body, "text/plain");
  3681. }
  3682. })
  3683. .Put("/content_receiver",
  3684. [&](const Request & /*req*/, Response &res,
  3685. const ContentReader &content_reader) {
  3686. std::string body;
  3687. content_reader([&](const char *data, size_t data_length) {
  3688. body.append(data, data_length);
  3689. return true;
  3690. });
  3691. EXPECT_EQ(body, "content");
  3692. res.set_content(body, "text/plain");
  3693. })
  3694. .Patch("/content_receiver",
  3695. [&](const Request & /*req*/, Response &res,
  3696. const ContentReader &content_reader) {
  3697. std::string body;
  3698. content_reader([&](const char *data, size_t data_length) {
  3699. body.append(data, data_length);
  3700. return true;
  3701. });
  3702. EXPECT_EQ(body, "content");
  3703. res.set_content(body, "text/plain");
  3704. })
  3705. .Post("/query-string-and-body",
  3706. [&](const Request &req, Response & /*res*/) {
  3707. ASSERT_TRUE(req.has_param("key"));
  3708. EXPECT_EQ(req.get_param_value("key"), "value");
  3709. EXPECT_EQ(req.body, "content");
  3710. })
  3711. .Get("/last-request",
  3712. [&](const Request &req, Response & /*res*/) {
  3713. EXPECT_EQ("close", req.get_header_value("Connection"));
  3714. })
  3715. .Get(R"(/redirect/(\d+))",
  3716. [&](const Request &req, Response &res) {
  3717. auto num = std::stoi(req.matches[1]) + 1;
  3718. std::string url = "/redirect/" + std::to_string(num);
  3719. res.set_redirect(url);
  3720. })
  3721. .Post("/binary",
  3722. [&](const Request &req, Response &res) {
  3723. EXPECT_EQ(4U, req.body.size());
  3724. EXPECT_EQ("application/octet-stream",
  3725. req.get_header_value("Content-Type"));
  3726. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3727. res.set_content(req.body, "application/octet-stream");
  3728. })
  3729. .Put("/binary",
  3730. [&](const Request &req, Response &res) {
  3731. EXPECT_EQ(4U, req.body.size());
  3732. EXPECT_EQ("application/octet-stream",
  3733. req.get_header_value("Content-Type"));
  3734. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3735. res.set_content(req.body, "application/octet-stream");
  3736. })
  3737. .Patch("/binary",
  3738. [&](const Request &req, Response &res) {
  3739. EXPECT_EQ(4U, req.body.size());
  3740. EXPECT_EQ("application/octet-stream",
  3741. req.get_header_value("Content-Type"));
  3742. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3743. res.set_content(req.body, "application/octet-stream");
  3744. })
  3745. .Delete("/binary",
  3746. [&](const Request &req, Response &res) {
  3747. EXPECT_EQ(4U, req.body.size());
  3748. EXPECT_EQ("application/octet-stream",
  3749. req.get_header_value("Content-Type"));
  3750. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3751. res.set_content(req.body, "application/octet-stream");
  3752. })
  3753. .Get("/issue1772",
  3754. [&](const Request & /*req*/, Response &res) {
  3755. res.status = 401;
  3756. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3757. })
  3758. .Delete("/issue609",
  3759. [](const httplib::Request &, httplib::Response &res,
  3760. const httplib::ContentReader &) {
  3761. res.set_content("ok", "text/plain");
  3762. })
  3763. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3764. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3765. .Get("/compress",
  3766. [&](const Request & /*req*/, Response &res) {
  3767. res.set_content(
  3768. "12345678901234567890123456789012345678901234567890123456789"
  3769. "01234567890123456789012345678901234567890",
  3770. "text/plain");
  3771. })
  3772. .Get("/compress-with-charset",
  3773. [&](const Request & /*req*/, Response &res) {
  3774. res.set_content(
  3775. "12345678901234567890123456789012345678901234567890123456789"
  3776. "01234567890123456789012345678901234567890",
  3777. "application/json; charset=utf-8");
  3778. })
  3779. .Get("/nocompress",
  3780. [&](const Request & /*req*/, Response &res) {
  3781. res.set_content(
  3782. "12345678901234567890123456789012345678901234567890123456789"
  3783. "01234567890123456789012345678901234567890",
  3784. "application/octet-stream");
  3785. })
  3786. .Post("/compress-multipart",
  3787. [&](const Request &req, Response & /*res*/) {
  3788. EXPECT_EQ(2u, req.form.fields.size());
  3789. ASSERT_TRUE(!req.form.has_field("???"));
  3790. {
  3791. const auto &text = req.form.get_field("key1");
  3792. EXPECT_EQ("test", text);
  3793. }
  3794. {
  3795. const auto &text = req.form.get_field("key2");
  3796. EXPECT_EQ("--abcdefg123", text);
  3797. }
  3798. })
  3799. #endif
  3800. ;
  3801. persons_["john"] = "programmer";
  3802. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3803. svr_.wait_until_ready();
  3804. }
  3805. virtual void TearDown() {
  3806. svr_.stop();
  3807. if (!request_threads_.empty()) {
  3808. std::this_thread::sleep_for(std::chrono::seconds(1));
  3809. for (auto &t : request_threads_) {
  3810. t.join();
  3811. }
  3812. }
  3813. t_.join();
  3814. }
  3815. map<string, string> persons_;
  3816. #ifdef CPPHTTPLIB_SSL_ENABLED
  3817. SSLClient cli_;
  3818. SSLServer svr_;
  3819. #else
  3820. Client cli_;
  3821. Server svr_;
  3822. #endif
  3823. thread t_;
  3824. std::vector<thread> request_threads_;
  3825. };
  3826. TEST_F(ServerTest, GetMethod200) {
  3827. auto res = cli_.Get("/hi");
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ("HTTP/1.1", res->version);
  3830. EXPECT_EQ(StatusCode::OK_200, res->status);
  3831. EXPECT_EQ("OK", res->reason);
  3832. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3833. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3834. EXPECT_EQ("Hello World!", res->body);
  3835. }
  3836. TEST_F(ServerTest, GetEmptyFile) {
  3837. auto res = cli_.Get("/empty_file");
  3838. ASSERT_TRUE(res);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3841. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3842. EXPECT_EQ("", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetFileContent) {
  3845. auto res = cli_.Get("/file_content");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3850. EXPECT_EQ("test.html", res->body);
  3851. }
  3852. TEST_F(ServerTest, GetFileContentWithRange) {
  3853. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3854. ASSERT_TRUE(res);
  3855. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3856. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3857. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3858. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3859. EXPECT_EQ("est", res->body);
  3860. }
  3861. TEST_F(ServerTest, GetFileContentWithContentType) {
  3862. auto res = cli_.Get("/file_content_with_content_type");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3866. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3867. EXPECT_EQ("file\n", res->body);
  3868. }
  3869. TEST_F(ServerTest, GetInvalidFileContent) {
  3870. auto res = cli_.Get("/invalid_file_content");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3873. }
  3874. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3875. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ("HTTP/1.1", res->version);
  3878. EXPECT_EQ(StatusCode::OK_200, res->status);
  3879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3880. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3881. EXPECT_EQ("Hello World!", res->body);
  3882. }
  3883. TEST_F(ServerTest, GetMethod302) {
  3884. auto res = cli_.Get("/");
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::Found_302, res->status);
  3887. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3888. }
  3889. TEST_F(ServerTest, GetMethod302Redirect) {
  3890. cli_.set_follow_location(true);
  3891. auto res = cli_.Get("/");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. EXPECT_EQ("Hello World!", res->body);
  3895. EXPECT_EQ("/hi", res->location);
  3896. }
  3897. TEST_F(ServerTest, GetMethod404) {
  3898. auto res = cli_.Get("/invalid");
  3899. ASSERT_TRUE(res);
  3900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3901. }
  3902. TEST_F(ServerTest, HeadMethod200) {
  3903. auto res = cli_.Head("/hi");
  3904. ASSERT_TRUE(res);
  3905. EXPECT_EQ(StatusCode::OK_200, res->status);
  3906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3907. EXPECT_TRUE(res->body.empty());
  3908. }
  3909. TEST_F(ServerTest, HeadMethod200Static) {
  3910. auto res = cli_.Head("/mount/dir/index.html");
  3911. ASSERT_TRUE(res);
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3914. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3915. EXPECT_TRUE(res->body.empty());
  3916. }
  3917. TEST_F(ServerTest, HeadMethod404) {
  3918. auto res = cli_.Head("/invalid");
  3919. ASSERT_TRUE(res);
  3920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3921. EXPECT_TRUE(res->body.empty());
  3922. }
  3923. TEST_F(ServerTest, GetMethodPersonJohn) {
  3924. auto res = cli_.Get("/person/john");
  3925. ASSERT_TRUE(res);
  3926. EXPECT_EQ(StatusCode::OK_200, res->status);
  3927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3928. EXPECT_EQ("programmer", res->body);
  3929. }
  3930. TEST_F(ServerTest, PostMethod1) {
  3931. auto res = cli_.Get("/person/john1");
  3932. ASSERT_TRUE(res);
  3933. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3934. res = cli_.Post("/person", "name=john1&note=coder",
  3935. "application/x-www-form-urlencoded");
  3936. ASSERT_TRUE(res);
  3937. ASSERT_EQ(StatusCode::OK_200, res->status);
  3938. res = cli_.Get("/person/john1");
  3939. ASSERT_TRUE(res);
  3940. ASSERT_EQ(StatusCode::OK_200, res->status);
  3941. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3942. ASSERT_EQ("coder", res->body);
  3943. }
  3944. TEST_F(ServerTest, PostMethod2) {
  3945. auto res = cli_.Get("/person/john2");
  3946. ASSERT_TRUE(res);
  3947. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3948. Params params;
  3949. params.emplace("name", "john2");
  3950. params.emplace("note", "coder");
  3951. res = cli_.Post("/person", params);
  3952. ASSERT_TRUE(res);
  3953. ASSERT_EQ(StatusCode::OK_200, res->status);
  3954. res = cli_.Get("/person/john2");
  3955. ASSERT_TRUE(res);
  3956. ASSERT_EQ(StatusCode::OK_200, res->status);
  3957. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3958. ASSERT_EQ("coder", res->body);
  3959. }
  3960. TEST_F(ServerTest, PutMethod3) {
  3961. auto res = cli_.Get("/person/john3");
  3962. ASSERT_TRUE(res);
  3963. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3964. Params params;
  3965. params.emplace("name", "john3");
  3966. params.emplace("note", "coder");
  3967. res = cli_.Put("/person", params);
  3968. ASSERT_TRUE(res);
  3969. ASSERT_EQ(StatusCode::OK_200, res->status);
  3970. res = cli_.Get("/person/john3");
  3971. ASSERT_TRUE(res);
  3972. ASSERT_EQ(StatusCode::OK_200, res->status);
  3973. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3974. ASSERT_EQ("coder", res->body);
  3975. }
  3976. TEST_F(ServerTest, DeleteMethod1) {
  3977. auto res = cli_.Get("/person/john4");
  3978. ASSERT_TRUE(res);
  3979. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3980. Params params;
  3981. params.emplace("name", "john4");
  3982. params.emplace("note", "coder");
  3983. res = cli_.Post("/person", params);
  3984. ASSERT_TRUE(res);
  3985. ASSERT_EQ(StatusCode::OK_200, res->status);
  3986. res = cli_.Get("/person/john4");
  3987. ASSERT_TRUE(res);
  3988. ASSERT_EQ(StatusCode::OK_200, res->status);
  3989. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3990. ASSERT_EQ("coder", res->body);
  3991. Params delete_params;
  3992. delete_params.emplace("name", "john4");
  3993. res = cli_.Delete("/person", delete_params);
  3994. ASSERT_TRUE(res);
  3995. ASSERT_EQ(StatusCode::OK_200, res->status);
  3996. ASSERT_EQ("DELETED", res->body);
  3997. res = cli_.Get("/person/john4");
  3998. ASSERT_TRUE(res);
  3999. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4000. }
  4001. TEST_F(ServerTest, DeleteMethod2) {
  4002. auto res = cli_.Get("/person/john5");
  4003. ASSERT_TRUE(res);
  4004. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4005. Params params;
  4006. params.emplace("name", "john5");
  4007. params.emplace("note", "developer");
  4008. res = cli_.Post("/person", params);
  4009. ASSERT_TRUE(res);
  4010. ASSERT_EQ(StatusCode::OK_200, res->status);
  4011. res = cli_.Get("/person/john5");
  4012. ASSERT_TRUE(res);
  4013. ASSERT_EQ(StatusCode::OK_200, res->status);
  4014. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4015. ASSERT_EQ("developer", res->body);
  4016. Params delete_params;
  4017. delete_params.emplace("name", "john5");
  4018. Headers headers;
  4019. headers.emplace("Custom-Header", "test-value");
  4020. res = cli_.Delete("/person", headers, delete_params);
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ("DELETED", res->body);
  4024. res = cli_.Get("/person/john5");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4027. }
  4028. TEST_F(ServerTest, DeleteMethod3) {
  4029. auto res = cli_.Get("/person/john6");
  4030. ASSERT_TRUE(res);
  4031. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4032. Params params;
  4033. params.emplace("name", "john6");
  4034. params.emplace("note", "tester");
  4035. res = cli_.Post("/person", params);
  4036. ASSERT_TRUE(res);
  4037. ASSERT_EQ(StatusCode::OK_200, res->status);
  4038. res = cli_.Get("/person/john6");
  4039. ASSERT_TRUE(res);
  4040. ASSERT_EQ(StatusCode::OK_200, res->status);
  4041. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4042. ASSERT_EQ("tester", res->body);
  4043. Params delete_params;
  4044. delete_params.emplace("name", "john6");
  4045. Headers headers;
  4046. headers.emplace("Custom-Header", "test-value");
  4047. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4048. ASSERT_TRUE(res);
  4049. ASSERT_EQ(StatusCode::OK_200, res->status);
  4050. ASSERT_EQ("DELETED", res->body);
  4051. res = cli_.Get("/person/john6");
  4052. ASSERT_TRUE(res);
  4053. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4054. }
  4055. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4056. Params params;
  4057. params.emplace("json", JSON_DATA);
  4058. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4059. ASSERT_TRUE(res);
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_EQ(JSON_DATA, res->body);
  4062. }
  4063. TEST_F(ServerTest, PostEmptyContent) {
  4064. auto res = cli_.Post("/empty", "", "text/plain");
  4065. ASSERT_TRUE(res);
  4066. ASSERT_EQ(StatusCode::OK_200, res->status);
  4067. ASSERT_EQ("empty", res->body);
  4068. }
  4069. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4070. auto res = cli_.Post("/empty-no-content-type");
  4071. ASSERT_TRUE(res);
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_EQ("empty-no-content-type", res->body);
  4074. }
  4075. TEST_F(ServerTest, PostPathOnly) {
  4076. auto res = cli_.Post("/path-only");
  4077. ASSERT_TRUE(res);
  4078. ASSERT_EQ(StatusCode::OK_200, res->status);
  4079. ASSERT_EQ("path-only", res->body);
  4080. }
  4081. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4082. auto res = cli_.Post("/path-headers-only",
  4083. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4084. ASSERT_TRUE(res);
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. ASSERT_EQ("path-headers-only", res->body);
  4087. }
  4088. TEST_F(ServerTest, PostLarge) {
  4089. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4090. ASSERT_TRUE(res);
  4091. ASSERT_EQ(StatusCode::OK_200, res->status);
  4092. EXPECT_EQ(LARGE_DATA, res->body);
  4093. }
  4094. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4095. auto res = cli_.Put("/empty-no-content-type");
  4096. ASSERT_TRUE(res);
  4097. ASSERT_EQ(StatusCode::OK_200, res->status);
  4098. ASSERT_EQ("empty-no-content-type", res->body);
  4099. }
  4100. TEST_F(ServerTest, GetMethodDir) {
  4101. auto res = cli_.Get("/dir/");
  4102. ASSERT_TRUE(res);
  4103. EXPECT_EQ(StatusCode::OK_200, res->status);
  4104. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4105. auto body = R"(<html>
  4106. <head>
  4107. </head>
  4108. <body>
  4109. <a href="/dir/test.html">Test</a>
  4110. <a href="/hi">hi</a>
  4111. </body>
  4112. </html>
  4113. )";
  4114. EXPECT_EQ(body, res->body);
  4115. }
  4116. TEST_F(ServerTest, GetMethodDirTest) {
  4117. auto res = cli_.Get("/dir/test.html");
  4118. ASSERT_TRUE(res);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4121. EXPECT_EQ("test.html", res->body);
  4122. }
  4123. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4124. auto res = cli_.Get("/dir/../dir/test.html");
  4125. ASSERT_TRUE(res);
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4128. EXPECT_EQ("test.html", res->body);
  4129. }
  4130. TEST_F(ServerTest, GetMethodInvalidPath) {
  4131. auto res = cli_.Get("/dir/../test.html");
  4132. ASSERT_TRUE(res);
  4133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4134. }
  4135. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4136. auto res = cli_.Get("/../www/dir/test.html");
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4139. }
  4140. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4141. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4142. ASSERT_TRUE(res);
  4143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4144. }
  4145. TEST_F(ServerTest, GetMethodDirMountTest) {
  4146. auto res = cli_.Get("/mount/dir/test.html");
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::OK_200, res->status);
  4149. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4150. EXPECT_EQ("test.html", res->body);
  4151. }
  4152. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4153. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4154. ASSERT_TRUE(res);
  4155. EXPECT_EQ(StatusCode::OK_200, res->status);
  4156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4157. EXPECT_EQ("test.html", res->body);
  4158. }
  4159. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4160. auto res = cli_.Get("/mount/dir/../test.html");
  4161. ASSERT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4163. }
  4164. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4165. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4166. ASSERT_TRUE(res);
  4167. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4168. }
  4169. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4170. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4171. ASSERT_TRUE(res);
  4172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4175. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4178. }
  4179. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4180. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4183. }
  4184. TEST_F(ServerTest, PostMethod303) {
  4185. auto res = cli_.Post("/1", "body", "text/plain");
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4188. EXPECT_EQ("/2", res->get_header_value("Location"));
  4189. }
  4190. TEST_F(ServerTest, PostMethod303Redirect) {
  4191. cli_.set_follow_location(true);
  4192. auto res = cli_.Post("/1", "body", "text/plain");
  4193. ASSERT_TRUE(res);
  4194. EXPECT_EQ(StatusCode::OK_200, res->status);
  4195. EXPECT_EQ("redirected.", res->body);
  4196. EXPECT_EQ("/2", res->location);
  4197. }
  4198. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4199. auto res = cli_.Get("/dir/test.abcde");
  4200. ASSERT_TRUE(res);
  4201. EXPECT_EQ(StatusCode::OK_200, res->status);
  4202. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4203. EXPECT_EQ("abcde", res->body);
  4204. }
  4205. TEST_F(ServerTest, StaticFileRange) {
  4206. auto res =
  4207. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4211. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4212. EXPECT_EQ(true, res->has_header("Content-Range"));
  4213. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4214. EXPECT_EQ(std::string("cd"), res->body);
  4215. }
  4216. TEST_F(ServerTest, StaticFileRanges) {
  4217. auto res = cli_.Get("/dir/test.abcde",
  4218. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_TRUE(
  4222. res->get_header_value("Content-Type")
  4223. .find(
  4224. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4225. 0);
  4226. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4227. }
  4228. TEST_F(ServerTest, StaticFileRangeHead) {
  4229. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4233. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ(true, res->has_header("Content-Range"));
  4235. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4236. }
  4237. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4238. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4242. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4243. EXPECT_EQ(true, res->has_header("Content-Range"));
  4244. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4245. res->get_header_value("Content-Range"));
  4246. EXPECT_EQ("LAST\n", res->body);
  4247. }
  4248. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4249. auto res =
  4250. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4254. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4255. EXPECT_EQ(true, res->has_header("Content-Range"));
  4256. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4257. }
  4258. TEST_F(ServerTest, StaticFileBigFile) {
  4259. auto res = cli_.Get("/dir/1MB.txt");
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::OK_200, res->status);
  4262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4263. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4264. }
  4265. TEST_F(ServerTest, InvalidBaseDirMount) {
  4266. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4267. }
  4268. TEST_F(ServerTest, Binary) {
  4269. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4270. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4271. "application/octet-stream");
  4272. ASSERT_TRUE(res);
  4273. ASSERT_EQ(StatusCode::OK_200, res->status);
  4274. ASSERT_EQ(4U, res->body.size());
  4275. res = cli_.Put("/binary", binary.data(), binary.size(),
  4276. "application/octet-stream");
  4277. ASSERT_TRUE(res);
  4278. ASSERT_EQ(StatusCode::OK_200, res->status);
  4279. ASSERT_EQ(4U, res->body.size());
  4280. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4281. "application/octet-stream");
  4282. ASSERT_TRUE(res);
  4283. ASSERT_EQ(StatusCode::OK_200, res->status);
  4284. ASSERT_EQ(4U, res->body.size());
  4285. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4286. "application/octet-stream");
  4287. ASSERT_TRUE(res);
  4288. ASSERT_EQ(StatusCode::OK_200, res->status);
  4289. ASSERT_EQ(4U, res->body.size());
  4290. }
  4291. TEST_F(ServerTest, BinaryString) {
  4292. auto binary = std::string("\x00\x01\x02\x03", 4);
  4293. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4294. ASSERT_TRUE(res);
  4295. ASSERT_EQ(StatusCode::OK_200, res->status);
  4296. ASSERT_EQ(4U, res->body.size());
  4297. res = cli_.Put("/binary", binary, "application/octet-stream");
  4298. ASSERT_TRUE(res);
  4299. ASSERT_EQ(StatusCode::OK_200, res->status);
  4300. ASSERT_EQ(4U, res->body.size());
  4301. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4302. ASSERT_TRUE(res);
  4303. ASSERT_EQ(StatusCode::OK_200, res->status);
  4304. ASSERT_EQ(4U, res->body.size());
  4305. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4306. ASSERT_TRUE(res);
  4307. ASSERT_EQ(StatusCode::OK_200, res->status);
  4308. ASSERT_EQ(4U, res->body.size());
  4309. }
  4310. TEST_F(ServerTest, EmptyRequest) {
  4311. auto res = cli_.Get("");
  4312. ASSERT_TRUE(!res);
  4313. EXPECT_EQ(Error::Connection, res.error());
  4314. }
  4315. TEST_F(ServerTest, LongRequest) {
  4316. std::string request;
  4317. for (size_t i = 0; i < 545; i++) {
  4318. request += "/TooLongRequest";
  4319. }
  4320. request += "OK";
  4321. auto res = cli_.Get(request.c_str());
  4322. ASSERT_TRUE(res);
  4323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4324. }
  4325. TEST_F(ServerTest, TooLongRequest) {
  4326. std::string request;
  4327. for (size_t i = 0; i < 546; i++) {
  4328. request += "/TooLongRequest";
  4329. }
  4330. request += "_NG";
  4331. auto start = std::chrono::high_resolution_clock::now();
  4332. cli_.set_keep_alive(true);
  4333. auto res = cli_.Get(request.c_str());
  4334. auto end = std::chrono::high_resolution_clock::now();
  4335. auto elapsed =
  4336. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4337. .count();
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4340. EXPECT_LE(elapsed, 1000);
  4341. EXPECT_EQ("close", res->get_header_value("Connection"));
  4342. EXPECT_FALSE(cli_.is_socket_open());
  4343. }
  4344. TEST_F(ServerTest, AlmostTooLongRequest) {
  4345. // test for #2046 - URI length check shouldn't include other content on req
  4346. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4347. // leading /, space, HTTP/1.1)
  4348. std::string request =
  4349. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4350. auto res = cli_.Get(request.c_str());
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4353. }
  4354. TEST_F(ServerTest, LongHeader) {
  4355. Request req;
  4356. req.method = "GET";
  4357. req.path = "/hi";
  4358. std::string host_and_port;
  4359. host_and_port += HOST;
  4360. host_and_port += ":";
  4361. host_and_port += std::to_string(PORT);
  4362. req.headers.emplace("Host", host_and_port.c_str());
  4363. req.headers.emplace("Accept", "*/*");
  4364. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4365. req.headers.emplace(
  4366. "Header-Name",
  4367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4389. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4390. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4395. "@@@@@@@@@@@@@@@@");
  4396. auto res = std::make_shared<Response>();
  4397. auto error = Error::Success;
  4398. auto ret = cli_.send(req, *res, error);
  4399. ASSERT_TRUE(ret);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. }
  4402. TEST_F(ServerTest, LongQueryValue) {
  4403. auto start = std::chrono::high_resolution_clock::now();
  4404. cli_.set_keep_alive(true);
  4405. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4406. auto end = std::chrono::high_resolution_clock::now();
  4407. auto elapsed =
  4408. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4409. .count();
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4412. EXPECT_LE(elapsed, 1000);
  4413. EXPECT_EQ("close", res->get_header_value("Connection"));
  4414. EXPECT_FALSE(cli_.is_socket_open());
  4415. }
  4416. TEST_F(ServerTest, TooLongQueryValue) {
  4417. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4418. ASSERT_FALSE(res);
  4419. EXPECT_EQ(Error::Read, res.error());
  4420. }
  4421. TEST_F(ServerTest, TooLongHeader) {
  4422. Request req;
  4423. req.method = "GET";
  4424. req.path = "/hi";
  4425. std::string host_and_port;
  4426. host_and_port += HOST;
  4427. host_and_port += ":";
  4428. host_and_port += std::to_string(PORT);
  4429. req.headers.emplace("Host", host_and_port.c_str());
  4430. req.headers.emplace("Accept", "*/*");
  4431. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4432. req.headers.emplace(
  4433. "Header-Name",
  4434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4455. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4456. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4457. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4458. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4459. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4462. "@@@@@@@@@@@@@@@@@");
  4463. auto res = std::make_shared<Response>();
  4464. auto error = Error::Success;
  4465. auto ret = cli_.send(req, *res, error);
  4466. ASSERT_TRUE(ret);
  4467. EXPECT_EQ(StatusCode::OK_200, res->status);
  4468. }
  4469. TEST_F(ServerTest, HeaderCountAtLimit) {
  4470. // Test with headers just under the 100 limit
  4471. httplib::Headers headers;
  4472. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4473. // This should keep us just under the 100 header limit
  4474. for (int i = 0; i < 95; i++) {
  4475. std::string name = "X-Test-Header-" + std::to_string(i);
  4476. std::string value = "value" + std::to_string(i);
  4477. headers.emplace(name, value);
  4478. }
  4479. // This should work fine as we're under the limit
  4480. auto res = cli_.Get("/hi", headers);
  4481. EXPECT_TRUE(res);
  4482. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4483. }
  4484. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4485. // Test with many headers to exceed the 100 limit
  4486. httplib::Headers headers;
  4487. // Add 150 headers to definitely exceed the 100 limit
  4488. for (int i = 0; i < 150; i++) {
  4489. std::string name = "X-Test-Header-" + std::to_string(i);
  4490. std::string value = "value" + std::to_string(i);
  4491. headers.emplace(name, value);
  4492. }
  4493. // This should fail due to exceeding header count limit
  4494. cli_.set_keep_alive(true);
  4495. auto res = cli_.Get("/hi", headers);
  4496. // The server should respond with 400 Bad Request
  4497. ASSERT_TRUE(res);
  4498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4499. EXPECT_EQ("close", res->get_header_value("Connection"));
  4500. EXPECT_FALSE(cli_.is_socket_open());
  4501. }
  4502. TEST_F(ServerTest, PercentEncoding) {
  4503. auto res = cli_.Get("/e%6edwith%");
  4504. ASSERT_TRUE(res);
  4505. EXPECT_EQ(StatusCode::OK_200, res->status);
  4506. }
  4507. TEST_F(ServerTest, PercentEncodingUnicode) {
  4508. auto res = cli_.Get("/e%u006edwith%");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. }
  4512. TEST_F(ServerTest, InvalidPercentEncoding) {
  4513. auto res = cli_.Get("/%endwith%");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4516. }
  4517. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4518. auto res = cli_.Get("/%uendwith%");
  4519. ASSERT_TRUE(res);
  4520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4521. }
  4522. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4523. auto res = cli_.Get("/hello?aaa=bbb%");
  4524. ASSERT_TRUE(res);
  4525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4526. }
  4527. TEST_F(ServerTest, PlusSignEncoding) {
  4528. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("a +b", res->body);
  4532. }
  4533. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4534. // This test simulates a potential DoS attack using many headers
  4535. // to verify our security fix prevents memory exhaustion
  4536. httplib::Headers attack_headers;
  4537. // Attempt to add many headers like an attacker would (200 headers to far
  4538. // exceed limit)
  4539. for (int i = 0; i < 200; i++) {
  4540. std::string name = "X-Attack-Header-" + std::to_string(i);
  4541. std::string value = "attack_payload_" + std::to_string(i);
  4542. attack_headers.emplace(name, value);
  4543. }
  4544. // Try to POST with excessive headers
  4545. cli_.set_keep_alive(true);
  4546. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4547. // Should either fail or return 400 Bad Request due to security limit
  4548. if (res) {
  4549. // If we get a response, it should be 400 Bad Request
  4550. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4551. EXPECT_EQ("close", res->get_header_value("Connection"));
  4552. }
  4553. EXPECT_FALSE(cli_.is_socket_open());
  4554. }
  4555. TEST_F(ServerTest, MultipartFormData) {
  4556. UploadFormDataItems items = {
  4557. {"text1", "text default", "", ""},
  4558. {"text2", "aωb", "", ""},
  4559. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4560. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4561. {"file3", "", "", "application/octet-stream"},
  4562. {"file4", "", "", " application/json tmp-string "}};
  4563. auto res = cli_.Post("/multipart", items);
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. }
  4567. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4568. UploadFormDataItems items = {
  4569. {"text", "default text", "", ""},
  4570. {"multi_text1", "aaaaa", "", ""},
  4571. {"multi_text1", "bbbbb", "", ""},
  4572. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4573. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4574. "application/json"},
  4575. };
  4576. auto res = cli_.Post("/multipart/multi_file_values", items);
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(StatusCode::OK_200, res->status);
  4579. }
  4580. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4581. auto res = cli_.Get("/hi");
  4582. ASSERT_TRUE(res);
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4585. EXPECT_EQ("Hello World!", res->body);
  4586. }
  4587. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4588. Request req;
  4589. req.method = "POST";
  4590. req.path = "/chunked";
  4591. std::string host_and_port;
  4592. host_and_port += HOST;
  4593. host_and_port += ":";
  4594. host_and_port += std::to_string(PORT);
  4595. req.headers.emplace("Host", host_and_port.c_str());
  4596. req.headers.emplace("Accept", "*/*");
  4597. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4598. req.headers.emplace("Content-Type", "text/plain");
  4599. req.headers.emplace("Content-Length", "0");
  4600. req.headers.emplace(
  4601. "Transfer-Encoding",
  4602. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4603. // Client does not chunk, so make a chunked body manually.
  4604. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4605. auto res = std::make_shared<Response>();
  4606. auto error = Error::Success;
  4607. auto ret = cli_.send(req, *res, error);
  4608. ASSERT_TRUE(ret);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4612. // rather than treat them as valid lengths.
  4613. template <typename ClientT>
  4614. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4615. Request req;
  4616. req.method = "POST";
  4617. req.path = "/chunked";
  4618. std::string host_and_port;
  4619. host_and_port += HOST;
  4620. host_and_port += ":";
  4621. host_and_port += std::to_string(PORT);
  4622. req.headers.emplace("Host", host_and_port.c_str());
  4623. req.headers.emplace("Content-Length", "0");
  4624. req.headers.emplace("Transfer-Encoding", "chunked");
  4625. req.body = body;
  4626. auto res = std::make_shared<Response>();
  4627. auto error = Error::Success;
  4628. ASSERT_TRUE(cli.send(req, *res, error));
  4629. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4630. }
  4631. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4632. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4633. }
  4634. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4635. expect_chunked_body_rejected(
  4636. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4637. }
  4638. TEST_F(ServerTest, GetStreamed2) {
  4639. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4642. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4643. EXPECT_EQ(true, res->has_header("Content-Range"));
  4644. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4645. EXPECT_EQ(std::string("ab"), res->body);
  4646. }
  4647. TEST_F(ServerTest, GetStreamed) {
  4648. auto res = cli_.Get("/streamed");
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4652. EXPECT_EQ(std::string("aaabbb"), res->body);
  4653. }
  4654. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4655. auto res = cli_.Get("/streamed-without-length",
  4656. Headers{make_range_header({{0, -1}})});
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(StatusCode::OK_200, res->status);
  4659. EXPECT_EQ(false, res->has_header("Content-Length"));
  4660. EXPECT_EQ(false, res->has_header("Content-Range"));
  4661. EXPECT_EQ(std::string("abcdefg"), res->body);
  4662. }
  4663. TEST_F(ServerTest, GetStreamedWithRange1) {
  4664. auto res =
  4665. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4668. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4669. EXPECT_EQ(true, res->has_header("Content-Range"));
  4670. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4671. EXPECT_EQ(std::string("def"), res->body);
  4672. }
  4673. TEST_F(ServerTest, GetStreamedWithRange2) {
  4674. auto res =
  4675. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4676. ASSERT_TRUE(res);
  4677. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4678. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4679. EXPECT_EQ(true, res->has_header("Content-Range"));
  4680. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4681. EXPECT_EQ(std::string("bcdefg"), res->body);
  4682. }
  4683. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4684. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4685. ASSERT_TRUE(res);
  4686. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4687. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4688. EXPECT_EQ(true, res->has_header("Content-Range"));
  4689. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4690. EXPECT_EQ(std::string("efg"), res->body);
  4691. }
  4692. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4693. auto res =
  4694. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4695. ASSERT_TRUE(res);
  4696. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4697. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4698. EXPECT_EQ(false, res->has_header("Content-Range"));
  4699. EXPECT_EQ(0U, res->body.size());
  4700. }
  4701. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4702. auto res =
  4703. cli_.Get("/streamed-with-range",
  4704. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4705. "92233720368547758079223372036854775807"}});
  4706. ASSERT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4708. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4709. EXPECT_EQ(false, res->has_header("Content-Range"));
  4710. EXPECT_EQ(0U, res->body.size());
  4711. }
  4712. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4713. auto res = cli_.Get(
  4714. "/with-range",
  4715. Headers{{"Range",
  4716. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4717. {"Accept-Encoding", ""}});
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4720. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4721. EXPECT_EQ(true, res->has_header("Content-Range"));
  4722. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4723. EXPECT_EQ(std::string("abcdefg"), res->body);
  4724. }
  4725. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4726. auto res = cli_.Get("/with-range", Headers{
  4727. {"Range", "bytes=0-"},
  4728. {"Accept-Encoding", ""},
  4729. });
  4730. ASSERT_TRUE(res);
  4731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4732. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4733. EXPECT_EQ(true, res->has_header("Content-Range"));
  4734. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4735. EXPECT_EQ(std::string("abcdefg"), res->body);
  4736. }
  4737. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4738. auto res = cli_.Get("/streamed-with-range",
  4739. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4742. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4743. EXPECT_EQ(false, res->has_header("Content-Range"));
  4744. EXPECT_EQ(267U, res->body.size());
  4745. // Check that both range contents are present
  4746. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4747. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4748. // Check that Content-Range headers are present for both ranges
  4749. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4750. std::string::npos);
  4751. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4752. std::string::npos);
  4753. }
  4754. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4755. Ranges ranges;
  4756. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4757. ranges.emplace_back(0, -1);
  4758. }
  4759. auto res = cli_.Get("/streamed-with-range?error",
  4760. Headers{{make_range_header(ranges)}});
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4763. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4764. EXPECT_EQ(false, res->has_header("Content-Range"));
  4765. EXPECT_EQ(0U, res->body.size());
  4766. }
  4767. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4768. auto res = cli_.Get("/streamed-with-range",
  4769. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4770. ASSERT_TRUE(res);
  4771. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4772. EXPECT_EQ(5U, res->body.size());
  4773. // Check that overlapping ranges are coalesced into a single range
  4774. EXPECT_EQ("bcdef", res->body);
  4775. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4776. // Should be single range, not multipart
  4777. EXPECT_TRUE(res->has_header("Content-Range"));
  4778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4779. }
  4780. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4781. auto res = cli_.Get("/streamed-with-range",
  4782. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4785. EXPECT_EQ(268U, res->body.size());
  4786. // Check that both range contents are present
  4787. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4788. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4789. // Check that Content-Range headers are present for both ranges
  4790. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4791. std::string::npos);
  4792. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4793. std::string::npos);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4796. auto res = cli_.Get("/streamed-with-range",
  4797. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4798. ASSERT_TRUE(res);
  4799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4800. EXPECT_EQ(269U, res->body.size());
  4801. // Check that both duplicate range contents are present
  4802. size_t first_abc = res->body.find("abc\r\n");
  4803. EXPECT_TRUE(first_abc != std::string::npos);
  4804. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4805. EXPECT_TRUE(second_abc != std::string::npos);
  4806. // Check that Content-Range headers are present for both ranges
  4807. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4808. EXPECT_TRUE(first_range != std::string::npos);
  4809. size_t second_range =
  4810. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4811. EXPECT_TRUE(second_range != std::string::npos);
  4812. }
  4813. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4814. auto res =
  4815. cli_.Get("/streamed-with-range?error",
  4816. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4817. ASSERT_TRUE(res);
  4818. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4819. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4820. EXPECT_EQ(false, res->has_header("Content-Range"));
  4821. EXPECT_EQ(0U, res->body.size());
  4822. }
  4823. TEST_F(ServerTest, GetStreamedEndless) {
  4824. uint64_t offset = 0;
  4825. auto res = cli_.Get("/streamed-cancel",
  4826. [&](const char * /*data*/, uint64_t data_length) {
  4827. if (offset < 100) {
  4828. offset += data_length;
  4829. return true;
  4830. }
  4831. return false;
  4832. });
  4833. ASSERT_TRUE(!res);
  4834. EXPECT_EQ(Error::Canceled, res.error());
  4835. }
  4836. TEST_F(ServerTest, ClientStop) {
  4837. std::atomic_size_t count{4};
  4838. std::vector<std::thread> threads;
  4839. for (auto i = count.load(); i != 0; --i) {
  4840. threads.emplace_back([&]() {
  4841. auto res = cli_.Get("/streamed-cancel",
  4842. [&](const char *, uint64_t) { return true; });
  4843. --count;
  4844. ASSERT_TRUE(!res);
  4845. EXPECT_TRUE(res.error() == Error::Canceled ||
  4846. res.error() == Error::Read || res.error() == Error::Write);
  4847. });
  4848. }
  4849. std::this_thread::sleep_for(std::chrono::seconds(2));
  4850. while (count != 0) {
  4851. cli_.stop();
  4852. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4853. }
  4854. for (auto &t : threads) {
  4855. t.join();
  4856. }
  4857. }
  4858. TEST_F(ServerTest, GetWithRange1) {
  4859. auto res = cli_.Get("/with-range", Headers{
  4860. make_range_header({{3, 5}}),
  4861. {"Accept-Encoding", ""},
  4862. });
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4865. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4866. EXPECT_EQ(true, res->has_header("Content-Range"));
  4867. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4868. EXPECT_EQ(std::string("def"), res->body);
  4869. }
  4870. TEST_F(ServerTest, GetWithRange2) {
  4871. auto res = cli_.Get("/with-range", Headers{
  4872. make_range_header({{1, -1}}),
  4873. {"Accept-Encoding", ""},
  4874. });
  4875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4877. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4878. EXPECT_EQ(true, res->has_header("Content-Range"));
  4879. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4880. EXPECT_EQ(std::string("bcdefg"), res->body);
  4881. }
  4882. TEST_F(ServerTest, GetWithRange3) {
  4883. auto res = cli_.Get("/with-range", Headers{
  4884. make_range_header({{0, 0}}),
  4885. {"Accept-Encoding", ""},
  4886. });
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4889. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4890. EXPECT_EQ(true, res->has_header("Content-Range"));
  4891. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4892. EXPECT_EQ(std::string("a"), res->body);
  4893. }
  4894. TEST_F(ServerTest, GetWithRange4) {
  4895. auto res = cli_.Get("/with-range", Headers{
  4896. make_range_header({{-1, 2}}),
  4897. {"Accept-Encoding", ""},
  4898. });
  4899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4901. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4902. EXPECT_EQ(true, res->has_header("Content-Range"));
  4903. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4904. EXPECT_EQ(std::string("fg"), res->body);
  4905. }
  4906. TEST_F(ServerTest, GetWithRange5) {
  4907. auto res = cli_.Get("/with-range", Headers{
  4908. make_range_header({{0, 5}}),
  4909. {"Accept-Encoding", ""},
  4910. });
  4911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4912. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4913. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4914. EXPECT_EQ(true, res->has_header("Content-Range"));
  4915. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4916. EXPECT_EQ(std::string("abcdef"), res->body);
  4917. }
  4918. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4919. auto res =
  4920. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  4921. ASSERT_TRUE(res);
  4922. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4923. }
  4924. TEST_F(ServerTest, GetWithRangeMultipart) {
  4925. auto res =
  4926. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4927. ASSERT_TRUE(res);
  4928. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4929. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4930. EXPECT_EQ(false, res->has_header("Content-Range"));
  4931. EXPECT_EQ(267U, res->body.size());
  4932. }
  4933. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4934. auto res = cli_.Get("/with-range",
  4935. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4938. }
  4939. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4940. auto res = cli_.Get("/with-range-customized-response",
  4941. Headers{{make_range_header({{1, 2}})}});
  4942. ASSERT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4944. EXPECT_EQ(true, res->has_header("Content-Length"));
  4945. EXPECT_EQ(false, res->has_header("Content-Range"));
  4946. EXPECT_EQ(JSON_DATA, res->body);
  4947. }
  4948. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4949. auto res = cli_.Get("/with-range-customized-response",
  4950. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4951. ASSERT_TRUE(res);
  4952. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4953. EXPECT_EQ(true, res->has_header("Content-Length"));
  4954. EXPECT_EQ(false, res->has_header("Content-Range"));
  4955. EXPECT_EQ(JSON_DATA, res->body);
  4956. }
  4957. TEST_F(ServerTest, Issue1772) {
  4958. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  4959. ASSERT_TRUE(res);
  4960. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4961. }
  4962. TEST_F(ServerTest, Issue609) {
  4963. auto res = cli_.Delete("/issue609");
  4964. ASSERT_TRUE(res);
  4965. EXPECT_EQ(StatusCode::OK_200, res->status);
  4966. EXPECT_EQ(std::string("ok"), res->body);
  4967. }
  4968. TEST_F(ServerTest, GetStreamedChunked) {
  4969. auto res = cli_.Get("/streamed-chunked");
  4970. ASSERT_TRUE(res);
  4971. EXPECT_EQ(StatusCode::OK_200, res->status);
  4972. EXPECT_EQ(std::string("123456789"), res->body);
  4973. }
  4974. TEST_F(ServerTest, GetStreamedChunked2) {
  4975. auto res = cli_.Get("/streamed-chunked2");
  4976. ASSERT_TRUE(res);
  4977. EXPECT_EQ(StatusCode::OK_200, res->status);
  4978. EXPECT_EQ(std::string("123456789"), res->body);
  4979. }
  4980. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4981. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4982. ASSERT_TRUE(res);
  4983. EXPECT_EQ(StatusCode::OK_200, res->status);
  4984. EXPECT_EQ(std::string("123456789"), res->body);
  4985. EXPECT_TRUE(res->has_header("Trailer"));
  4986. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4987. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4988. // Trailers are now stored separately from headers (security fix)
  4989. EXPECT_EQ(2U, res->trailers.size());
  4990. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4991. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4992. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4993. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4994. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4995. // Verify trailers are NOT in headers (security verification)
  4996. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4997. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4998. }
  4999. TEST_F(ServerTest, LargeChunkedPost) {
  5000. Request req;
  5001. req.method = "POST";
  5002. req.path = "/large-chunked";
  5003. std::string host_and_port;
  5004. host_and_port += HOST;
  5005. host_and_port += ":";
  5006. host_and_port += std::to_string(PORT);
  5007. req.headers.emplace("Host", host_and_port.c_str());
  5008. req.headers.emplace("Accept", "*/*");
  5009. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5010. req.headers.emplace("Content-Type", "text/plain");
  5011. req.headers.emplace("Content-Length", "0");
  5012. req.headers.emplace("Transfer-Encoding", "chunked");
  5013. std::string long_string(30 * 1024u, 'a');
  5014. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5015. // Attempt to make a large enough post to exceed OS buffers, to test that
  5016. // the server handles short reads if the full chunk data isn't available.
  5017. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5018. auto res = std::make_shared<Response>();
  5019. auto error = Error::Success;
  5020. auto ret = cli_.send(req, *res, error);
  5021. ASSERT_TRUE(ret);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. }
  5024. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5025. auto res = cli_.Get("/remote_addr");
  5026. ASSERT_TRUE(res);
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5029. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5030. }
  5031. TEST_F(ServerTest, GetMethodLocalAddr) {
  5032. auto res = cli_.Get("/local_addr");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5036. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5037. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5038. }
  5039. TEST_F(ServerTest, HTTPResponseSplitting) {
  5040. auto res = cli_.Get("/http_response_splitting");
  5041. ASSERT_TRUE(res);
  5042. EXPECT_EQ(StatusCode::OK_200, res->status);
  5043. }
  5044. TEST_F(ServerTest, SlowRequest) {
  5045. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5046. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5047. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5048. }
  5049. #if 0
  5050. TEST_F(ServerTest, SlowPost) {
  5051. char buffer[64 * 1024];
  5052. memset(buffer, 0x42, sizeof(buffer));
  5053. auto res = cli_.Post(
  5054. "/slowpost", 64 * 1024 * 1024,
  5055. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5056. auto ret = sink.write(buffer, sizeof(buffer));
  5057. EXPECT_TRUE(ret);
  5058. return true;
  5059. },
  5060. "text/plain");
  5061. ASSERT_TRUE(res);
  5062. EXPECT_EQ(StatusCode::OK_200, res->status);
  5063. }
  5064. TEST_F(ServerTest, SlowPostFail) {
  5065. char buffer[64 * 1024];
  5066. memset(buffer, 0x42, sizeof(buffer));
  5067. cli_.set_write_timeout(std::chrono::seconds(0));
  5068. auto res = cli_.Post(
  5069. "/slowpost", 64 * 1024 * 1024,
  5070. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5071. sink.write(buffer, sizeof(buffer));
  5072. return true;
  5073. },
  5074. "text/plain");
  5075. ASSERT_TRUE(!res);
  5076. EXPECT_EQ(Error::Write, res.error());
  5077. }
  5078. #endif
  5079. TEST_F(ServerTest, Put) {
  5080. auto res = cli_.Put("/put", "PUT", "text/plain");
  5081. ASSERT_TRUE(res);
  5082. EXPECT_EQ(StatusCode::OK_200, res->status);
  5083. EXPECT_EQ("PUT", res->body);
  5084. }
  5085. TEST_F(ServerTest, PutWithContentProvider) {
  5086. auto res = cli_.Put(
  5087. "/put", 3,
  5088. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5089. sink.os << "PUT";
  5090. return true;
  5091. },
  5092. "text/plain");
  5093. ASSERT_TRUE(res);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. EXPECT_EQ("PUT", res->body);
  5096. }
  5097. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5098. auto res = cli_.Post(
  5099. "/post", 42,
  5100. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5101. return false;
  5102. },
  5103. "text/plain");
  5104. ASSERT_TRUE(!res);
  5105. EXPECT_EQ(Error::Canceled, res.error());
  5106. }
  5107. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5108. auto res = cli_.Put(
  5109. "/put",
  5110. [](size_t /*offset*/, DataSink &sink) {
  5111. sink.os << "PUT";
  5112. sink.done();
  5113. return true;
  5114. },
  5115. "text/plain");
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ("PUT", res->body);
  5119. }
  5120. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5121. auto res = cli_.Post(
  5122. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5123. "text/plain");
  5124. ASSERT_TRUE(!res);
  5125. EXPECT_EQ(Error::Canceled, res.error());
  5126. }
  5127. TEST_F(ServerTest, PostLoopBack) {
  5128. std::string body;
  5129. auto res = cli_.Post(
  5130. "/post-loopback", 9,
  5131. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5132. EXPECT_EQ(9u, length);
  5133. sink.write("123", 3);
  5134. sink.write("456", 3);
  5135. sink.write("789", 3);
  5136. return true;
  5137. },
  5138. "text/plain",
  5139. [&body](const char *data, size_t data_length) {
  5140. body.append(data, data_length);
  5141. return true;
  5142. });
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("123456789", body);
  5146. }
  5147. TEST_F(ServerTest, PutLoopBack) {
  5148. std::string body;
  5149. auto res = cli_.Put(
  5150. "/put-loopback", 9,
  5151. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5152. EXPECT_EQ(9u, length);
  5153. sink.write("123", 3);
  5154. sink.write("456", 3);
  5155. sink.write("789", 3);
  5156. return true;
  5157. },
  5158. "text/plain",
  5159. [&body](const char *data, size_t data_length) {
  5160. body.append(data, data_length);
  5161. return true;
  5162. });
  5163. ASSERT_TRUE(res);
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. EXPECT_EQ("123456789", body);
  5166. }
  5167. TEST_F(ServerTest, PatchLoopBack) {
  5168. std::string body;
  5169. auto res = cli_.Patch(
  5170. "/patch-loopback", 9,
  5171. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5172. EXPECT_EQ(9u, length);
  5173. sink.write("123", 3);
  5174. sink.write("456", 3);
  5175. sink.write("789", 3);
  5176. return true;
  5177. },
  5178. "text/plain",
  5179. [&body](const char *data, size_t data_length) {
  5180. body.append(data, data_length);
  5181. return true;
  5182. });
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. EXPECT_EQ("123456789", body);
  5186. }
  5187. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5188. std::string body;
  5189. auto res = cli_.Post(
  5190. "/post-loopback",
  5191. [](size_t /*offset*/, DataSink &sink) {
  5192. sink.write("123", 3);
  5193. sink.write("456", 3);
  5194. sink.write("789", 3);
  5195. sink.done();
  5196. return true;
  5197. },
  5198. "text/plain",
  5199. [&body](const char *data, size_t data_length) {
  5200. body.append(data, data_length);
  5201. return true;
  5202. });
  5203. ASSERT_TRUE(res);
  5204. EXPECT_EQ(StatusCode::OK_200, res->status);
  5205. EXPECT_EQ("123456789", body);
  5206. }
  5207. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5208. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5209. cli_.set_compress(true);
  5210. auto res = cli_.Put(
  5211. "/put", 3,
  5212. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5213. sink.os << "PUT";
  5214. return true;
  5215. },
  5216. "text/plain");
  5217. ASSERT_TRUE(res);
  5218. EXPECT_EQ(StatusCode::OK_200, res->status);
  5219. EXPECT_EQ("PUT", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5222. cli_.set_compress(true);
  5223. auto res = cli_.Post(
  5224. "/post", 42,
  5225. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5226. return false;
  5227. },
  5228. "text/plain");
  5229. ASSERT_TRUE(!res);
  5230. EXPECT_EQ(Error::Canceled, res.error());
  5231. }
  5232. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5233. cli_.set_compress(true);
  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, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5247. cli_.set_compress(true);
  5248. auto res = cli_.Post(
  5249. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5250. "text/plain");
  5251. ASSERT_TRUE(!res);
  5252. EXPECT_EQ(Error::Canceled, res.error());
  5253. }
  5254. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5255. cli_.set_compress(true);
  5256. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. EXPECT_EQ(LARGE_DATA, res->body);
  5260. }
  5261. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5262. #ifdef CPPHTTPLIB_SSL_ENABLED
  5263. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5264. Client cli(s.c_str());
  5265. cli.enable_server_certificate_verification(false);
  5266. #else
  5267. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5268. Client cli(s.c_str());
  5269. #endif
  5270. cli.set_compress(true);
  5271. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5272. ASSERT_TRUE(res);
  5273. EXPECT_EQ(StatusCode::OK_200, res->status);
  5274. EXPECT_EQ(LARGE_DATA, res->body);
  5275. // The compressed size should be less than a 10th of the original. May vary
  5276. // depending on the zlib library.
  5277. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5278. static_cast<uint64_t>(10 * 1024 * 1024));
  5279. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5280. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5281. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5282. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5283. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5284. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5285. #endif
  5286. }
  5287. TEST_F(ServerTest, PutContentWithDeflate) {
  5288. cli_.set_compress(false);
  5289. Headers headers;
  5290. headers.emplace("Content-Encoding", "deflate");
  5291. // PUT in deflate format:
  5292. auto res = cli_.Put("/put", headers,
  5293. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5294. ASSERT_TRUE(res);
  5295. EXPECT_EQ(StatusCode::OK_200, res->status);
  5296. EXPECT_EQ("PUT", res->body);
  5297. }
  5298. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5299. Headers headers;
  5300. headers.emplace("Accept-Encoding", "gzip, deflate");
  5301. auto res = cli_.Get("/streamed-chunked", headers);
  5302. ASSERT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ(std::string("123456789"), res->body);
  5305. }
  5306. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5307. Headers headers;
  5308. headers.emplace("Accept-Encoding", "gzip, deflate");
  5309. auto res = cli_.Get("/streamed-chunked2", headers);
  5310. ASSERT_TRUE(res);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. EXPECT_EQ(std::string("123456789"), res->body);
  5313. }
  5314. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5315. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5316. ASSERT_TRUE(res);
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. }
  5319. TEST(GzipDecompressor, ChunkedDecompression) {
  5320. std::string data;
  5321. for (size_t i = 0; i < 32 * 1024; ++i) {
  5322. data.push_back(static_cast<char>('a' + i % 26));
  5323. }
  5324. std::string compressed_data;
  5325. {
  5326. httplib::detail::gzip_compressor compressor;
  5327. bool result = compressor.compress(
  5328. data.data(), data.size(),
  5329. /*last=*/true,
  5330. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5331. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5332. compressed_data_size);
  5333. return true;
  5334. });
  5335. ASSERT_TRUE(result);
  5336. }
  5337. std::string decompressed_data;
  5338. {
  5339. httplib::detail::gzip_decompressor decompressor;
  5340. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5341. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5342. size_t chunk_size = 130;
  5343. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5344. chunk_begin += chunk_size) {
  5345. size_t current_chunk_size =
  5346. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5347. bool result = decompressor.decompress(
  5348. compressed_data.data() + chunk_begin, current_chunk_size,
  5349. [&](const char *decompressed_data_chunk,
  5350. size_t decompressed_data_chunk_size) {
  5351. decompressed_data.insert(decompressed_data.size(),
  5352. decompressed_data_chunk,
  5353. decompressed_data_chunk_size);
  5354. return true;
  5355. });
  5356. ASSERT_TRUE(result);
  5357. }
  5358. }
  5359. ASSERT_EQ(data, decompressed_data);
  5360. }
  5361. TEST(GzipDecompressor, DeflateDecompression) {
  5362. std::string original_text = "Raw deflate without gzip";
  5363. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5364. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5365. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5366. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5367. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5368. std::string decompressed_data;
  5369. {
  5370. httplib::detail::gzip_decompressor decompressor;
  5371. bool result = decompressor.decompress(
  5372. compressed_data.data(), compressed_data.size(),
  5373. [&](const char *decompressed_data_chunk,
  5374. size_t decompressed_data_chunk_size) {
  5375. decompressed_data.insert(decompressed_data.size(),
  5376. decompressed_data_chunk,
  5377. decompressed_data_chunk_size);
  5378. return true;
  5379. });
  5380. ASSERT_TRUE(result);
  5381. }
  5382. ASSERT_EQ(original_text, decompressed_data);
  5383. }
  5384. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5385. std::string original_text = "Raw deflate without gzip";
  5386. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5387. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5388. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5389. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5390. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5391. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5392. std::string decompressed_data;
  5393. {
  5394. httplib::detail::gzip_decompressor decompressor;
  5395. bool result = decompressor.decompress(
  5396. compressed_data.data(), compressed_data.size(),
  5397. [&](const char *decompressed_data_chunk,
  5398. size_t decompressed_data_chunk_size) {
  5399. decompressed_data.insert(decompressed_data.size(),
  5400. decompressed_data_chunk,
  5401. decompressed_data_chunk_size);
  5402. return true;
  5403. });
  5404. ASSERT_TRUE(result);
  5405. }
  5406. ASSERT_EQ(original_text, decompressed_data);
  5407. }
  5408. #endif
  5409. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5410. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5411. Headers headers;
  5412. headers.emplace("Accept-Encoding", "br");
  5413. auto res = cli_.Get("/streamed-chunked", headers);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. EXPECT_EQ(std::string("123456789"), res->body);
  5417. }
  5418. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5419. Headers headers;
  5420. headers.emplace("Accept-Encoding", "br");
  5421. auto res = cli_.Get("/streamed-chunked2", headers);
  5422. ASSERT_TRUE(res);
  5423. EXPECT_EQ(StatusCode::OK_200, res->status);
  5424. EXPECT_EQ(std::string("123456789"), res->body);
  5425. }
  5426. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5427. cli_.set_compress(true);
  5428. auto res = cli_.Put(
  5429. "/put", 3,
  5430. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5431. sink.os << "PUT";
  5432. return true;
  5433. },
  5434. "text/plain");
  5435. ASSERT_TRUE(res);
  5436. EXPECT_EQ(StatusCode::OK_200, res->status);
  5437. EXPECT_EQ("PUT", res->body);
  5438. }
  5439. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5440. cli_.set_compress(true);
  5441. auto res = cli_.Put(
  5442. "/put",
  5443. [](size_t /*offset*/, DataSink &sink) {
  5444. sink.os << "PUT";
  5445. sink.done();
  5446. return true;
  5447. },
  5448. "text/plain");
  5449. ASSERT_TRUE(res);
  5450. EXPECT_EQ(StatusCode::OK_200, res->status);
  5451. EXPECT_EQ("PUT", res->body);
  5452. }
  5453. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5454. cli_.set_compress(true);
  5455. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5456. ASSERT_TRUE(res);
  5457. EXPECT_EQ(StatusCode::OK_200, res->status);
  5458. EXPECT_EQ(LARGE_DATA, res->body);
  5459. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5460. }
  5461. #endif
  5462. TEST_F(ServerTest, Patch) {
  5463. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("PATCH", res->body);
  5467. }
  5468. TEST_F(ServerTest, Delete) {
  5469. auto res = cli_.Delete("/delete");
  5470. ASSERT_TRUE(res);
  5471. EXPECT_EQ(StatusCode::OK_200, res->status);
  5472. EXPECT_EQ("DELETE", res->body);
  5473. }
  5474. TEST_F(ServerTest, DeleteContentReceiver) {
  5475. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5476. ASSERT_TRUE(res);
  5477. EXPECT_EQ(StatusCode::OK_200, res->status);
  5478. EXPECT_EQ("content", res->body);
  5479. }
  5480. TEST_F(ServerTest, Options) {
  5481. auto res = cli_.Options("*");
  5482. ASSERT_TRUE(res);
  5483. EXPECT_EQ(StatusCode::OK_200, res->status);
  5484. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5485. EXPECT_TRUE(res->body.empty());
  5486. }
  5487. TEST_F(ServerTest, URL) {
  5488. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5489. ASSERT_TRUE(res);
  5490. EXPECT_EQ(StatusCode::OK_200, res->status);
  5491. }
  5492. TEST_F(ServerTest, ArrayParam) {
  5493. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. }
  5497. TEST_F(ServerTest, ArrayParamValues) {
  5498. auto res =
  5499. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5500. ASSERT_TRUE(res);
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. }
  5503. TEST_F(ServerTest, NoMultipleHeaders) {
  5504. Headers headers = {{"Content-Length", "5"}};
  5505. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. }
  5510. TEST_F(ServerTest, PostContentReceiver) {
  5511. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5512. ASSERT_TRUE(res);
  5513. ASSERT_EQ(StatusCode::OK_200, res->status);
  5514. ASSERT_EQ("content", res->body);
  5515. }
  5516. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5517. UploadFormDataItems items = {
  5518. {"text1", "text default", "", ""},
  5519. {"text2", "aωb", "", ""},
  5520. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5521. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5522. {"file3", "", "", "application/octet-stream"},
  5523. };
  5524. auto res = cli_.Post("/content_receiver", items);
  5525. ASSERT_TRUE(res);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5529. UploadFormDataItems items = {
  5530. {"text1", "text default", "", ""},
  5531. {"text2", "aωb", "", ""},
  5532. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5533. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5534. {"file3", "", "", "application/octet-stream"},
  5535. };
  5536. auto boundary = std::string("+++++");
  5537. std::string body;
  5538. for (const auto &item : items) {
  5539. body += "--" + boundary + "\r\n";
  5540. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5541. if (!item.filename.empty()) {
  5542. body += "; filename=\"" + item.filename + "\"";
  5543. }
  5544. body += "\r\n";
  5545. if (!item.content_type.empty()) {
  5546. body += "Content-Type: " + item.content_type + "\r\n";
  5547. }
  5548. body += "\r\n";
  5549. body += item.content + "\r\n";
  5550. }
  5551. body += "--" + boundary + "--\r\n";
  5552. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5553. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. }
  5557. TEST(MultipartFormDataTest, FieldEscaping) {
  5558. Server svr;
  5559. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5560. const ContentReader &content_reader) {
  5561. ASSERT_TRUE(req.is_multipart_form_data());
  5562. std::vector<FormData> received;
  5563. content_reader(
  5564. [&](const FormData &file) {
  5565. received.push_back(file);
  5566. return true;
  5567. },
  5568. [&](const char *data, size_t data_length) {
  5569. received.back().content.append(data, data_length);
  5570. return true;
  5571. });
  5572. // '"', CR and LF in names and filenames are escaped following the
  5573. // WHATWG HTML standard, so each part still parses as a single part
  5574. // with no injected headers. Content types get CR/LF escaped too,
  5575. // while '"' (legal there, e.g. quoted charset) is preserved.
  5576. ASSERT_EQ(4U, received.size());
  5577. EXPECT_EQ("na%22me", received[0].name);
  5578. EXPECT_EQ("quoted name", received[0].content);
  5579. EXPECT_EQ("file", received[1].name);
  5580. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5581. received[1].filename);
  5582. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5583. EXPECT_EQ("injected", received[1].content);
  5584. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5585. EXPECT_EQ("my%22file.txt", received[2].filename);
  5586. EXPECT_EQ("cr lf name", received[2].content);
  5587. EXPECT_EQ("typed", received[3].name);
  5588. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5589. received[3].content_type);
  5590. EXPECT_EQ("typed content", received[3].content);
  5591. });
  5592. auto port = svr.bind_to_any_port("localhost");
  5593. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5594. auto se = detail::scope_exit([&] {
  5595. svr.stop();
  5596. t.join();
  5597. ASSERT_FALSE(svr.is_running());
  5598. });
  5599. svr.wait_until_ready();
  5600. Client cli("localhost", port);
  5601. UploadFormDataItems items = {
  5602. {"na\"me", "quoted name", "", ""},
  5603. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5604. "application/octet-stream"},
  5605. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5606. {"typed", "typed content", "",
  5607. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5608. };
  5609. auto res = cli.Post("/post", items);
  5610. ASSERT_TRUE(res);
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. }
  5613. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5614. const UploadFormDataItems items = {
  5615. {"name1", "Content 1", "", ""},
  5616. {"name2", "Content 2", "file2.txt", "text/plain"},
  5617. };
  5618. Server svr;
  5619. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5620. const ContentReader &content_reader) {
  5621. ASSERT_TRUE(req.is_multipart_form_data());
  5622. std::vector<FormData> received;
  5623. content_reader(
  5624. [&](const FormData &file) {
  5625. received.push_back(file);
  5626. return true;
  5627. },
  5628. [&](const char *data, size_t data_length) {
  5629. received.back().content.append(data, data_length);
  5630. return true;
  5631. });
  5632. ASSERT_EQ(2U, received.size());
  5633. EXPECT_EQ("name1", received[0].name);
  5634. EXPECT_EQ("Content 1", received[0].content);
  5635. EXPECT_EQ("name2", received[1].name);
  5636. EXPECT_EQ("Content 2", received[1].content);
  5637. EXPECT_EQ("file2.txt", received[1].filename);
  5638. EXPECT_EQ("text/plain", received[1].content_type);
  5639. });
  5640. auto port = svr.bind_to_any_port("localhost");
  5641. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5642. auto se = detail::scope_exit([&] {
  5643. svr.stop();
  5644. t.join();
  5645. ASSERT_FALSE(svr.is_running());
  5646. });
  5647. svr.wait_until_ready();
  5648. Client cli("localhost", port);
  5649. // Whole-body serialization with a generated boundary
  5650. {
  5651. MultipartFormDataWriter writer;
  5652. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5653. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5654. writer.content_type());
  5655. auto body = writer.serialize(items);
  5656. EXPECT_EQ(body.size(), writer.content_length(items));
  5657. auto res = cli.Post("/post", body, writer.content_type());
  5658. ASSERT_TRUE(res);
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. }
  5661. // Per-part framing with a custom boundary via a content provider
  5662. {
  5663. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5664. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5665. MultipartFormDataWriter writer("custom-boundary_123");
  5666. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5667. std::string body;
  5668. for (const auto &item : items) {
  5669. body += writer.item_begin(item);
  5670. body += item.content;
  5671. body += MultipartFormDataWriter::item_end();
  5672. }
  5673. body += writer.finish();
  5674. EXPECT_EQ(body.size(), writer.content_length(items));
  5675. auto res = cli.Post(
  5676. "/post", body.size(),
  5677. [&](size_t offset, size_t length, DataSink &sink) {
  5678. sink.write(body.data() + offset, length);
  5679. return true;
  5680. },
  5681. writer.content_type());
  5682. ASSERT_TRUE(res);
  5683. EXPECT_EQ(StatusCode::OK_200, res->status);
  5684. }
  5685. }
  5686. TEST_F(ServerTest, PostContentReceiverGzip) {
  5687. cli_.set_compress(true);
  5688. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5689. ASSERT_TRUE(res);
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ("content", res->body);
  5692. }
  5693. TEST_F(ServerTest, PutContentReceiver) {
  5694. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5695. ASSERT_TRUE(res);
  5696. ASSERT_EQ(StatusCode::OK_200, res->status);
  5697. ASSERT_EQ("content", res->body);
  5698. }
  5699. TEST_F(ServerTest, PatchContentReceiver) {
  5700. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5701. ASSERT_TRUE(res);
  5702. ASSERT_EQ(StatusCode::OK_200, res->status);
  5703. ASSERT_EQ("content", res->body);
  5704. }
  5705. template <typename ClientType>
  5706. void TestWithHeadersAndContentReceiver(
  5707. ClientType &cli,
  5708. std::function<Result(ClientType &, const std::string &, const Headers &,
  5709. const std::string &, const std::string &,
  5710. ContentReceiver, DownloadProgress)>
  5711. request_func) {
  5712. Headers headers;
  5713. headers.emplace("X-Custom-Header", "test-value");
  5714. std::string received_body;
  5715. auto res = request_func(
  5716. cli, "/content_receiver", headers, "content", "application/json",
  5717. [&](const char *data, size_t data_length) {
  5718. received_body.append(data, data_length);
  5719. return true;
  5720. },
  5721. nullptr);
  5722. ASSERT_TRUE(res);
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ("content", received_body);
  5725. }
  5726. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5727. #ifdef CPPHTTPLIB_SSL_ENABLED
  5728. using ClientT = SSLClient;
  5729. #else
  5730. using ClientT = Client;
  5731. #endif
  5732. TestWithHeadersAndContentReceiver<ClientT>(
  5733. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5734. const std::string &body, const std::string &content_type,
  5735. ContentReceiver receiver, DownloadProgress progress) {
  5736. return cli.Post(path, headers, body, content_type, receiver, progress);
  5737. });
  5738. }
  5739. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5740. #ifdef CPPHTTPLIB_SSL_ENABLED
  5741. using ClientT = SSLClient;
  5742. #else
  5743. using ClientT = Client;
  5744. #endif
  5745. TestWithHeadersAndContentReceiver<ClientT>(
  5746. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5747. const std::string &body, const std::string &content_type,
  5748. ContentReceiver receiver, DownloadProgress progress) {
  5749. return cli.Put(path, headers, body, content_type, receiver, progress);
  5750. });
  5751. }
  5752. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5753. #ifdef CPPHTTPLIB_SSL_ENABLED
  5754. using ClientT = SSLClient;
  5755. #else
  5756. using ClientT = Client;
  5757. #endif
  5758. TestWithHeadersAndContentReceiver<ClientT>(
  5759. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5760. const std::string &body, const std::string &content_type,
  5761. ContentReceiver receiver, DownloadProgress progress) {
  5762. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5763. });
  5764. }
  5765. template <typename ClientType>
  5766. void TestWithHeadersAndContentReceiverWithProgress(
  5767. ClientType &cli,
  5768. std::function<Result(ClientType &, const std::string &, const Headers &,
  5769. const std::string &, const std::string &,
  5770. ContentReceiver, DownloadProgress)>
  5771. request_func) {
  5772. Headers headers;
  5773. headers.emplace("X-Test-Header", "progress-test");
  5774. std::string received_body;
  5775. auto progress_called = false;
  5776. auto res = request_func(
  5777. cli, "/content_receiver", headers, "content", "text/plain",
  5778. [&](const char *data, size_t data_length) {
  5779. received_body.append(data, data_length);
  5780. return true;
  5781. },
  5782. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5783. progress_called = true;
  5784. return true;
  5785. });
  5786. ASSERT_TRUE(res);
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. EXPECT_EQ("content", received_body);
  5789. EXPECT_TRUE(progress_called);
  5790. }
  5791. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5792. #ifdef CPPHTTPLIB_SSL_ENABLED
  5793. using ClientT = SSLClient;
  5794. #else
  5795. using ClientT = Client;
  5796. #endif
  5797. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5798. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5799. const std::string &body, const std::string &content_type,
  5800. ContentReceiver receiver, DownloadProgress progress) {
  5801. return cli.Post(path, headers, body, content_type, receiver, progress);
  5802. });
  5803. }
  5804. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5805. #ifdef CPPHTTPLIB_SSL_ENABLED
  5806. using ClientT = SSLClient;
  5807. #else
  5808. using ClientT = Client;
  5809. #endif
  5810. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5811. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5812. const std::string &body, const std::string &content_type,
  5813. ContentReceiver receiver, DownloadProgress progress) {
  5814. return cli.Put(path, headers, body, content_type, receiver, progress);
  5815. });
  5816. }
  5817. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5818. #ifdef CPPHTTPLIB_SSL_ENABLED
  5819. using ClientT = SSLClient;
  5820. #else
  5821. using ClientT = Client;
  5822. #endif
  5823. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5824. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5825. const std::string &body, const std::string &content_type,
  5826. ContentReceiver receiver, DownloadProgress progress) {
  5827. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5828. });
  5829. }
  5830. template <typename ClientType>
  5831. void TestWithHeadersAndContentReceiverError(
  5832. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5833. const Headers &, const std::string &,
  5834. const std::string &, ContentReceiver)>
  5835. request_func) {
  5836. Headers headers;
  5837. headers.emplace("X-Error-Test", "true");
  5838. std::string received_body;
  5839. auto receiver_failed = false;
  5840. auto res =
  5841. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5842. [&](const char *data, size_t data_length) {
  5843. received_body.append(data, data_length);
  5844. receiver_failed = true;
  5845. return false;
  5846. });
  5847. ASSERT_FALSE(res);
  5848. EXPECT_TRUE(receiver_failed);
  5849. }
  5850. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5851. #ifdef CPPHTTPLIB_SSL_ENABLED
  5852. using ClientT = SSLClient;
  5853. #else
  5854. using ClientT = Client;
  5855. #endif
  5856. TestWithHeadersAndContentReceiverError<ClientT>(
  5857. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5858. const std::string &body, const std::string &content_type,
  5859. ContentReceiver receiver) {
  5860. return cli.Post(path, headers, body, content_type, receiver);
  5861. });
  5862. }
  5863. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5864. #ifdef CPPHTTPLIB_SSL_ENABLED
  5865. using ClientT = SSLClient;
  5866. #else
  5867. using ClientT = Client;
  5868. #endif
  5869. TestWithHeadersAndContentReceiverError<ClientT>(
  5870. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5871. const std::string &body, const std::string &content_type,
  5872. ContentReceiver receiver) {
  5873. return cli.Put(path, headers, body, content_type, receiver);
  5874. });
  5875. }
  5876. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5877. #ifdef CPPHTTPLIB_SSL_ENABLED
  5878. using ClientT = SSLClient;
  5879. #else
  5880. using ClientT = Client;
  5881. #endif
  5882. TestWithHeadersAndContentReceiverError<ClientT>(
  5883. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5884. const std::string &body, const std::string &content_type,
  5885. ContentReceiver receiver) {
  5886. return cli.Patch(path, headers, body, content_type, receiver);
  5887. });
  5888. }
  5889. TEST_F(ServerTest, PostQueryStringAndBody) {
  5890. auto res =
  5891. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5892. ASSERT_TRUE(res);
  5893. ASSERT_EQ(StatusCode::OK_200, res->status);
  5894. }
  5895. TEST_F(ServerTest, HTTP2Magic) {
  5896. Request req;
  5897. req.method = "PRI";
  5898. req.path = "*";
  5899. req.body = "SM";
  5900. auto res = std::make_shared<Response>();
  5901. auto error = Error::Success;
  5902. auto ret = cli_.send(req, *res, error);
  5903. ASSERT_TRUE(ret);
  5904. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5905. }
  5906. TEST_F(ServerTest, KeepAlive) {
  5907. auto res = cli_.Get("/hi");
  5908. ASSERT_TRUE(res);
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5911. EXPECT_EQ("Hello World!", res->body);
  5912. res = cli_.Get("/hi");
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5916. EXPECT_EQ("Hello World!", res->body);
  5917. res = cli_.Get("/hi");
  5918. ASSERT_TRUE(res);
  5919. EXPECT_EQ(StatusCode::OK_200, res->status);
  5920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5921. EXPECT_EQ("Hello World!", res->body);
  5922. res = cli_.Get("/not-exist");
  5923. ASSERT_TRUE(res);
  5924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5925. res = cli_.Post("/empty", "", "text/plain");
  5926. ASSERT_TRUE(res);
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5929. EXPECT_EQ("empty", res->body);
  5930. EXPECT_EQ("close", res->get_header_value("Connection"));
  5931. res = cli_.Post(
  5932. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5933. "text/plain");
  5934. ASSERT_TRUE(res);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5937. EXPECT_EQ("empty", res->body);
  5938. cli_.set_keep_alive(false);
  5939. res = cli_.Get("/last-request");
  5940. ASSERT_TRUE(res);
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("close", res->get_header_value("Connection"));
  5943. }
  5944. TEST_F(ServerTest, TooManyRedirect) {
  5945. cli_.set_follow_location(true);
  5946. auto res = cli_.Get("/redirect/0");
  5947. ASSERT_TRUE(!res);
  5948. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5949. }
  5950. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5951. Request req;
  5952. req.method = "FOOBAR";
  5953. req.path = "/hi";
  5954. cli_.set_keep_alive(true);
  5955. auto res = cli_.send(req);
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5958. EXPECT_EQ("close", res->get_header_value("Connection"));
  5959. EXPECT_FALSE(cli_.is_socket_open());
  5960. }
  5961. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5962. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5963. TEST_F(ServerTest, Gzip) {
  5964. Headers headers;
  5965. headers.emplace("Accept-Encoding", "gzip, deflate");
  5966. auto res = cli_.Get("/compress", headers);
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5970. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5971. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5972. "7890123456789012345678901234567890",
  5973. res->body);
  5974. EXPECT_EQ(StatusCode::OK_200, res->status);
  5975. }
  5976. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5977. Headers headers;
  5978. headers.emplace("Accept-Encoding", "gzip, deflate");
  5979. auto res = cli_.Get("/compress-with-charset", headers);
  5980. ASSERT_TRUE(res);
  5981. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5982. EXPECT_EQ("application/json; charset=utf-8",
  5983. res->get_header_value("Content-Type"));
  5984. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5985. "7890123456789012345678901234567890",
  5986. res->body);
  5987. EXPECT_EQ(StatusCode::OK_200, res->status);
  5988. }
  5989. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5990. Headers headers;
  5991. headers.emplace("Accept-Encoding", "");
  5992. auto res = cli_.Get("/compress", headers);
  5993. ASSERT_TRUE(res);
  5994. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5996. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5998. "7890123456789012345678901234567890",
  5999. res->body);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. TEST_F(ServerTest, GzipWithContentReceiver) {
  6003. Headers headers;
  6004. headers.emplace("Accept-Encoding", "gzip, deflate");
  6005. std::string body;
  6006. auto res = cli_.Get("/compress", headers,
  6007. [&](const char *data, uint64_t data_length) {
  6008. EXPECT_EQ(100U, data_length);
  6009. body.append(data, data_length);
  6010. return true;
  6011. });
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6015. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6017. "7890123456789012345678901234567890",
  6018. body);
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. }
  6021. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6022. Headers headers;
  6023. headers.emplace("Accept-Encoding", "gzip, deflate");
  6024. cli_.set_decompress(false);
  6025. auto res = cli_.Get("/compress", headers);
  6026. ASSERT_TRUE(res);
  6027. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6030. EXPECT_EQ(33U, res->body.size());
  6031. EXPECT_EQ(StatusCode::OK_200, res->status);
  6032. }
  6033. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6034. Headers headers;
  6035. headers.emplace("Accept-Encoding", "");
  6036. std::string body;
  6037. auto res = cli_.Get("/compress", headers,
  6038. [&](const char *data, uint64_t data_length) {
  6039. EXPECT_EQ(100U, data_length);
  6040. body.append(data, data_length);
  6041. return true;
  6042. });
  6043. ASSERT_TRUE(res);
  6044. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6046. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6047. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6048. "7890123456789012345678901234567890",
  6049. body);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. }
  6052. TEST_F(ServerTest, NoGzip) {
  6053. Headers headers;
  6054. headers.emplace("Accept-Encoding", "gzip, deflate");
  6055. auto res = cli_.Get("/nocompress", headers);
  6056. ASSERT_TRUE(res);
  6057. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6058. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6059. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6060. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6061. "7890123456789012345678901234567890",
  6062. res->body);
  6063. EXPECT_EQ(StatusCode::OK_200, res->status);
  6064. }
  6065. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6066. Headers headers;
  6067. headers.emplace("Accept-Encoding", "gzip, deflate");
  6068. std::string body;
  6069. auto res = cli_.Get("/nocompress", headers,
  6070. [&](const char *data, uint64_t data_length) {
  6071. EXPECT_EQ(100U, data_length);
  6072. body.append(data, data_length);
  6073. return true;
  6074. });
  6075. ASSERT_TRUE(res);
  6076. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6077. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6080. "7890123456789012345678901234567890",
  6081. body);
  6082. EXPECT_EQ(StatusCode::OK_200, res->status);
  6083. }
  6084. TEST_F(ServerTest, MultipartFormDataGzip) {
  6085. UploadFormDataItems items = {
  6086. {"key1", "test", "", ""},
  6087. {"key2", "--abcdefg123", "", ""},
  6088. };
  6089. cli_.set_compress(true);
  6090. auto res = cli_.Post("/compress-multipart", items);
  6091. ASSERT_TRUE(res);
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. }
  6094. #endif
  6095. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6096. TEST_F(ServerTest, Brotli) {
  6097. Headers headers;
  6098. headers.emplace("Accept-Encoding", "br");
  6099. auto res = cli_.Get("/compress", headers);
  6100. ASSERT_TRUE(res);
  6101. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6103. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6104. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6105. "7890123456789012345678901234567890",
  6106. res->body);
  6107. EXPECT_EQ(StatusCode::OK_200, res->status);
  6108. }
  6109. #endif
  6110. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6111. TEST_F(ServerTest, Zstd) {
  6112. Headers headers;
  6113. headers.emplace("Accept-Encoding", "zstd");
  6114. auto res = cli_.Get("/compress", headers);
  6115. ASSERT_TRUE(res);
  6116. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6118. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6120. "7890123456789012345678901234567890",
  6121. res->body);
  6122. EXPECT_EQ(StatusCode::OK_200, res->status);
  6123. }
  6124. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6125. Headers headers;
  6126. headers.emplace("Accept-Encoding", "");
  6127. auto res = cli_.Get("/compress", headers);
  6128. ASSERT_TRUE(res);
  6129. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6130. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6133. "7890123456789012345678901234567890",
  6134. res->body);
  6135. EXPECT_EQ(StatusCode::OK_200, res->status);
  6136. }
  6137. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "zstd");
  6140. std::string body;
  6141. auto res = cli_.Get("/compress", headers,
  6142. [&](const char *data, uint64_t data_length) {
  6143. EXPECT_EQ(100U, data_length);
  6144. body.append(data, data_length);
  6145. return true;
  6146. });
  6147. ASSERT_TRUE(res);
  6148. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6150. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6152. "7890123456789012345678901234567890",
  6153. body);
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. }
  6156. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6157. Headers headers;
  6158. headers.emplace("Accept-Encoding", "zstd");
  6159. cli_.set_decompress(false);
  6160. auto res = cli_.Get("/compress", headers);
  6161. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6162. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6163. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6164. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6165. ASSERT_TRUE(res);
  6166. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6168. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6169. EXPECT_EQ(StatusCode::OK_200, res->status);
  6170. ASSERT_EQ(26U, res->body.size());
  6171. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6172. 0);
  6173. }
  6174. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6175. Headers headers;
  6176. headers.emplace("Accept-Encoding", "");
  6177. std::string body;
  6178. auto res = cli_.Get("/compress", headers,
  6179. [&](const char *data, uint64_t data_length) {
  6180. EXPECT_EQ(100U, data_length);
  6181. body.append(data, data_length);
  6182. return true;
  6183. });
  6184. ASSERT_TRUE(res);
  6185. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6188. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6189. "7890123456789012345678901234567890",
  6190. body);
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. }
  6193. TEST_F(ServerTest, NoZstd) {
  6194. Headers headers;
  6195. headers.emplace("Accept-Encoding", "zstd");
  6196. auto res = cli_.Get("/nocompress", headers);
  6197. ASSERT_TRUE(res);
  6198. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6199. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6200. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6201. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6202. "7890123456789012345678901234567890",
  6203. res->body);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. }
  6206. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6207. Headers headers;
  6208. headers.emplace("Accept-Encoding", "zstd");
  6209. std::string body;
  6210. auto res = cli_.Get("/nocompress", headers,
  6211. [&](const char *data, uint64_t data_length) {
  6212. EXPECT_EQ(100U, data_length);
  6213. body.append(data, data_length);
  6214. return true;
  6215. });
  6216. ASSERT_TRUE(res);
  6217. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6218. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6219. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6220. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6221. "7890123456789012345678901234567890",
  6222. body);
  6223. EXPECT_EQ(StatusCode::OK_200, res->status);
  6224. }
  6225. // TODO: How to enable zstd ??
  6226. TEST_F(ServerTest, MultipartFormDataZstd) {
  6227. UploadFormDataItems items = {
  6228. {"key1", "test", "", ""},
  6229. {"key2", "--abcdefg123", "", ""},
  6230. };
  6231. Headers headers;
  6232. headers.emplace("Accept-Encoding", "zstd");
  6233. cli_.set_compress(true);
  6234. auto res = cli_.Post("/compress-multipart", headers, items);
  6235. ASSERT_TRUE(res);
  6236. EXPECT_EQ(StatusCode::OK_200, res->status);
  6237. }
  6238. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6239. Headers headers;
  6240. headers.emplace("Accept-Encoding", "zstd");
  6241. cli_.set_compress(true);
  6242. auto res = cli_.Put(
  6243. "/put", headers, 3,
  6244. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6245. sink.os << "PUT";
  6246. return true;
  6247. },
  6248. "text/plain");
  6249. ASSERT_TRUE(res);
  6250. EXPECT_EQ(StatusCode::OK_200, res->status);
  6251. EXPECT_EQ("PUT", res->body);
  6252. }
  6253. // Pre-compression logging tests
  6254. TEST_F(ServerTest, PreCompressionLogging) {
  6255. // Test data for compression (matches the actual /compress endpoint content)
  6256. const std::string test_content =
  6257. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6258. "3456789012345678901234567890";
  6259. // Variables to capture logging data
  6260. std::string pre_compression_body;
  6261. std::string pre_compression_content_type;
  6262. std::string pre_compression_content_encoding;
  6263. std::string post_compression_body;
  6264. std::string post_compression_content_type;
  6265. std::string post_compression_content_encoding;
  6266. // Set up pre-compression logger
  6267. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6268. const Response &res) {
  6269. pre_compression_body = res.body;
  6270. pre_compression_content_type = res.get_header_value("Content-Type");
  6271. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6272. });
  6273. // Set up post-compression logger
  6274. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6275. post_compression_body = res.body;
  6276. post_compression_content_type = res.get_header_value("Content-Type");
  6277. post_compression_content_encoding =
  6278. res.get_header_value("Content-Encoding");
  6279. });
  6280. // Test with gzip compression
  6281. Headers headers;
  6282. headers.emplace("Accept-Encoding", "gzip");
  6283. auto res = cli_.Get("/compress", headers);
  6284. // Verify response was compressed
  6285. ASSERT_TRUE(res);
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6288. // Verify pre-compression logger captured uncompressed content
  6289. EXPECT_EQ(test_content, pre_compression_body);
  6290. EXPECT_EQ("text/plain", pre_compression_content_type);
  6291. EXPECT_TRUE(pre_compression_content_encoding
  6292. .empty()); // No encoding header before compression
  6293. // Verify post-compression logger captured compressed content
  6294. EXPECT_NE(test_content,
  6295. post_compression_body); // Should be different after compression
  6296. EXPECT_EQ("text/plain", post_compression_content_type);
  6297. EXPECT_EQ("gzip", post_compression_content_encoding);
  6298. // Verify compressed content is smaller
  6299. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6300. }
  6301. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6302. const std::string test_content =
  6303. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6304. "3456789012345678901234567890";
  6305. std::string pre_compression_body;
  6306. std::string post_compression_body;
  6307. svr_.set_pre_compression_logger(
  6308. [&](const Request & /*req*/, const Response &res) {
  6309. pre_compression_body = res.body;
  6310. });
  6311. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6312. post_compression_body = res.body;
  6313. });
  6314. Headers headers;
  6315. headers.emplace("Accept-Encoding", "br");
  6316. auto res = cli_.Get("/compress", headers);
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6320. // Verify pre-compression content is uncompressed
  6321. EXPECT_EQ(test_content, pre_compression_body);
  6322. // Verify post-compression content is compressed
  6323. EXPECT_NE(test_content, post_compression_body);
  6324. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6325. }
  6326. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6327. const std::string test_content =
  6328. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6329. "3456789012345678901234567890";
  6330. std::string pre_compression_body;
  6331. std::string post_compression_body;
  6332. svr_.set_pre_compression_logger(
  6333. [&](const Request & /*req*/, const Response &res) {
  6334. pre_compression_body = res.body;
  6335. });
  6336. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6337. post_compression_body = res.body;
  6338. });
  6339. // Request without compression (use /nocompress endpoint)
  6340. Headers headers;
  6341. auto res = cli_.Get("/nocompress", headers);
  6342. ASSERT_TRUE(res);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6345. // Pre-compression logger should not be called when no compression is applied
  6346. EXPECT_TRUE(
  6347. pre_compression_body.empty()); // Pre-compression logger not called
  6348. EXPECT_EQ(
  6349. test_content,
  6350. post_compression_body); // Post-compression logger captures final content
  6351. }
  6352. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6353. const std::string test_content =
  6354. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6355. "3456789012345678901234567890";
  6356. std::string pre_compression_body;
  6357. bool pre_logger_called = false;
  6358. // Set only pre-compression logger
  6359. svr_.set_pre_compression_logger(
  6360. [&](const Request & /*req*/, const Response &res) {
  6361. pre_compression_body = res.body;
  6362. pre_logger_called = true;
  6363. });
  6364. Headers headers;
  6365. headers.emplace("Accept-Encoding", "gzip");
  6366. auto res = cli_.Get("/compress", headers);
  6367. ASSERT_TRUE(res);
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6370. // Verify pre-compression logger was called
  6371. EXPECT_TRUE(pre_logger_called);
  6372. EXPECT_EQ(test_content, pre_compression_body);
  6373. }
  6374. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6375. {
  6376. // Test with Expect: 100-continue header - success case
  6377. // Server returns 100 Continue, client sends body, server returns 200 OK
  6378. Request req;
  6379. req.method = "POST";
  6380. req.path = "/post-large";
  6381. req.set_header("Expect", "100-continue");
  6382. req.body = LARGE_DATA;
  6383. Response res;
  6384. auto error = Error::Success;
  6385. cli_.set_keep_alive(true);
  6386. auto ret = cli_.send(req, res, error);
  6387. EXPECT_TRUE(ret);
  6388. EXPECT_EQ(StatusCode::OK_200, res.status);
  6389. EXPECT_EQ(LARGE_DATA, res.body);
  6390. }
  6391. {
  6392. // Test with Expect: 100-continue header - error case
  6393. // Client should not send the body when server returns an error
  6394. Request req;
  6395. req.method = "POST";
  6396. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6397. req.set_header("Expect", "100-continue");
  6398. req.body = LARGE_DATA;
  6399. Response res;
  6400. auto error = Error::Success;
  6401. auto start = std::chrono::high_resolution_clock::now();
  6402. cli_.set_keep_alive(true);
  6403. auto ret = cli_.send(req, res, error);
  6404. auto end = std::chrono::high_resolution_clock::now();
  6405. auto elapsed =
  6406. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6407. .count();
  6408. // With Expect: 100-continue, request completes successfully but with error
  6409. EXPECT_TRUE(ret);
  6410. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6411. EXPECT_EQ("close", res.get_header_value("Connection"));
  6412. EXPECT_FALSE(cli_.is_socket_open());
  6413. EXPECT_LE(elapsed, 2000);
  6414. }
  6415. {
  6416. // Send an extra GET request to ensure error recovery without hanging
  6417. Request req;
  6418. req.method = "GET";
  6419. req.path = "/hi";
  6420. auto start = std::chrono::high_resolution_clock::now();
  6421. auto res = cli_.send(req);
  6422. auto end = std::chrono::high_resolution_clock::now();
  6423. auto elapsed =
  6424. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6425. .count();
  6426. ASSERT_TRUE(res);
  6427. EXPECT_EQ(StatusCode::OK_200, res->status);
  6428. EXPECT_EQ("Hello World!", res->body);
  6429. EXPECT_LE(elapsed, 500);
  6430. }
  6431. }
  6432. TEST(ZstdDecompressor, ChunkedDecompression) {
  6433. std::string data;
  6434. for (size_t i = 0; i < 32 * 1024; ++i) {
  6435. data.push_back(static_cast<char>('a' + i % 26));
  6436. }
  6437. std::string compressed_data;
  6438. {
  6439. httplib::detail::zstd_compressor compressor;
  6440. bool result = compressor.compress(
  6441. data.data(), data.size(),
  6442. /*last=*/true,
  6443. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6444. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6445. compressed_data_size);
  6446. return true;
  6447. });
  6448. ASSERT_TRUE(result);
  6449. }
  6450. std::string decompressed_data;
  6451. {
  6452. httplib::detail::zstd_decompressor decompressor;
  6453. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6454. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6455. size_t chunk_size = 130;
  6456. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6457. chunk_begin += chunk_size) {
  6458. size_t current_chunk_size =
  6459. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6460. bool result = decompressor.decompress(
  6461. compressed_data.data() + chunk_begin, current_chunk_size,
  6462. [&](const char *decompressed_data_chunk,
  6463. size_t decompressed_data_chunk_size) {
  6464. decompressed_data.insert(decompressed_data.size(),
  6465. decompressed_data_chunk,
  6466. decompressed_data_chunk_size);
  6467. return true;
  6468. });
  6469. ASSERT_TRUE(result);
  6470. }
  6471. }
  6472. ASSERT_EQ(data, decompressed_data);
  6473. }
  6474. TEST(ZstdDecompressor, Decompress) {
  6475. std::string original_text = "Compressed with ZSTD";
  6476. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6477. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6478. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6479. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6480. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6481. std::string decompressed_data;
  6482. {
  6483. httplib::detail::zstd_decompressor decompressor;
  6484. bool result = decompressor.decompress(
  6485. compressed_data.data(), compressed_data.size(),
  6486. [&](const char *decompressed_data_chunk,
  6487. size_t decompressed_data_chunk_size) {
  6488. decompressed_data.insert(decompressed_data.size(),
  6489. decompressed_data_chunk,
  6490. decompressed_data_chunk_size);
  6491. return true;
  6492. });
  6493. ASSERT_TRUE(result);
  6494. }
  6495. ASSERT_EQ(original_text, decompressed_data);
  6496. }
  6497. #endif
  6498. // Sends a raw request to a server listening at HOST:PORT.
  6499. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6500. std::string *resp = nullptr) {
  6501. auto error = Error::Success;
  6502. auto client_sock = detail::create_client_socket(
  6503. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6504. /*connection_timeout_sec=*/5, 0,
  6505. /*read_timeout_sec=*/5, 0,
  6506. /*write_timeout_sec=*/5, 0, std::string(), error);
  6507. if (client_sock == INVALID_SOCKET) { return false; }
  6508. auto ret = detail::process_client_socket(
  6509. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6510. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6511. if (req.size() !=
  6512. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6513. return false;
  6514. }
  6515. char buf[512];
  6516. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6517. while (line_reader.getline()) {
  6518. if (resp) { *resp += line_reader.ptr(); }
  6519. }
  6520. return true;
  6521. });
  6522. detail::close_socket(client_sock);
  6523. return ret;
  6524. }
  6525. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6526. Server svr;
  6527. std::string header_value;
  6528. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6529. header_value = req.get_header_value("foo");
  6530. res.set_content("ok", "text/plain");
  6531. });
  6532. thread t = thread([&] { svr.listen(HOST, PORT); });
  6533. auto se = detail::scope_exit([&] {
  6534. svr.stop();
  6535. t.join();
  6536. ASSERT_FALSE(svr.is_running());
  6537. });
  6538. svr.wait_until_ready();
  6539. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6540. // like characters are not treated the same - use vertical tab and escape.
  6541. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6542. "foo: \t \v bar \x1B\t \r\n"
  6543. "Connection: close\r\n"
  6544. "\r\n";
  6545. std::string res;
  6546. ASSERT_TRUE(send_request(5, req, &res));
  6547. EXPECT_EQ(header_value, "");
  6548. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6549. }
  6550. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6551. Server svr;
  6552. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6553. auto i = new int(0);
  6554. res.set_header("Trailer", "X-Safe, X-Reflected");
  6555. res.set_chunked_content_provider(
  6556. "text/plain",
  6557. [i](size_t /*offset*/, DataSink &sink) {
  6558. if (*i == 0) {
  6559. sink.os << "body";
  6560. } else {
  6561. Headers trailer;
  6562. // A valid trailer that must survive.
  6563. trailer.emplace("X-Safe", "safe");
  6564. // Attacker-controlled value carrying CR/LF (response splitting).
  6565. trailer.emplace("X-Reflected",
  6566. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6567. // Attacker-controlled name carrying CR/LF.
  6568. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6569. sink.done_with_trailer(trailer);
  6570. }
  6571. (*i)++;
  6572. return true;
  6573. },
  6574. [i](bool /*success*/) { delete i; });
  6575. });
  6576. thread t = thread([&] { svr.listen(HOST, PORT); });
  6577. auto se = detail::scope_exit([&] {
  6578. svr.stop();
  6579. t.join();
  6580. ASSERT_FALSE(svr.is_running());
  6581. });
  6582. svr.wait_until_ready();
  6583. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6584. "Host: " + HOST +
  6585. "\r\n"
  6586. "Connection: close\r\n"
  6587. "\r\n";
  6588. std::string res;
  6589. ASSERT_TRUE(send_request(5, req, &res));
  6590. // The injected fields must not appear anywhere in the raw response.
  6591. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6592. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6593. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6594. // Invalid trailers are dropped entirely, matching set_header().
  6595. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6596. // The valid trailer still passes through.
  6597. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6598. }
  6599. // Sends a raw request and verifies that there isn't a crash or exception.
  6600. static void test_raw_request(const std::string &req,
  6601. std::string *out = nullptr) {
  6602. Server svr;
  6603. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6604. res.set_content("ok", "text/plain");
  6605. });
  6606. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6607. res.set_content("ok", "text/plain");
  6608. });
  6609. svr.Get("/header_field_value_check",
  6610. [&](const Request & /*req*/, Response &res) {
  6611. res.set_content("ok", "text/plain");
  6612. });
  6613. // Server read timeout must be longer than the client read timeout for the
  6614. // bug to reproduce, probably to force the server to process a request
  6615. // without a trailing blank line.
  6616. const time_t client_read_timeout_sec = 1;
  6617. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6618. bool listen_thread_ok = false;
  6619. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6620. auto se = detail::scope_exit([&] {
  6621. svr.stop();
  6622. t.join();
  6623. ASSERT_FALSE(svr.is_running());
  6624. EXPECT_TRUE(listen_thread_ok);
  6625. });
  6626. svr.wait_until_ready();
  6627. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6628. }
  6629. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6630. // A certain header line causes an exception if the header property is parsed
  6631. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6632. test_raw_request(
  6633. "GET /hi HTTP/1.1\r\n"
  6634. " : "
  6635. " "
  6636. " ");
  6637. }
  6638. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6639. // A certain header line causes an exception if the header property *name* is
  6640. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6641. // greedy matcher and requires backtracking when there are a lot of ":"
  6642. // characters.
  6643. // This occurs with libc++ but not libstdc++.
  6644. test_raw_request(
  6645. "GET /hi HTTP/1.1\r\n"
  6646. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6647. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6648. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6649. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6650. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6651. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6652. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6653. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6654. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6655. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6656. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6657. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6658. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6659. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6660. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6661. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6662. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6663. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6664. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6665. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6666. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6667. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6668. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6669. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6670. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6671. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6672. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6673. "&&&%%%");
  6674. }
  6675. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6676. // Make sure this doesn't crash the server.
  6677. // In a previous version of the header line regex, the "\r" rendered the line
  6678. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6679. // a new position where the leading white space ended and the field value
  6680. // began.
  6681. // The crash occurs with libc++ but not libstdc++.
  6682. test_raw_request("GET /hi HTTP/1.1\r\n"
  6683. "a:" +
  6684. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6685. "\r\n"
  6686. "\r\n");
  6687. }
  6688. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6689. std::string out;
  6690. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6691. "Content-Type: text/plain\r\n"
  6692. "Transfer-Encoding: chunked\r\n"
  6693. "\r\n"
  6694. "nothex\r\n",
  6695. &out);
  6696. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6697. }
  6698. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6699. std::string out;
  6700. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6701. "Content-Type: text/plain\r\n"
  6702. "Transfer-Encoding: chunked\r\n"
  6703. "\r\n"
  6704. "3\r\n"
  6705. "xyz\r\n"
  6706. "NaN\r\n",
  6707. &out);
  6708. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6709. }
  6710. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6711. std::string out;
  6712. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6713. "Content-Type: text/plain\r\n"
  6714. "Transfer-Encoding: chunked\r\n"
  6715. "\r\n"
  6716. // Length is too large for 64 bits.
  6717. "1ffffffffffffffff\r\n"
  6718. "xyz\r\n",
  6719. &out);
  6720. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6721. }
  6722. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6723. test_raw_request("GET /hi HTTP/1.1\r\n"
  6724. "Content-Type: text/plain\r\n\r");
  6725. }
  6726. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6727. std::string out;
  6728. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6729. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6730. }
  6731. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6732. Server svr;
  6733. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6734. EXPECT_TRUE(!req.remote_addr.empty());
  6735. });
  6736. thread t = thread([&] { svr.listen(HOST, PORT); });
  6737. auto se = detail::scope_exit([&] {
  6738. svr.stop();
  6739. t.join();
  6740. ASSERT_FALSE(svr.is_running());
  6741. });
  6742. svr.wait_until_ready();
  6743. // Send an invalid request line to trigger Bad Request
  6744. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6745. std::string out;
  6746. ASSERT_TRUE(send_request(5, bad_req, &out));
  6747. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6748. }
  6749. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6750. std::string out;
  6751. std::string request(
  6752. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6753. test_raw_request(request, &out);
  6754. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6755. }
  6756. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6757. std::string out;
  6758. std::string request(
  6759. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6760. test_raw_request(request, &out);
  6761. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6762. }
  6763. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6764. std::string out;
  6765. std::string request(
  6766. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6767. test_raw_request(request, &out);
  6768. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6769. }
  6770. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6771. std::string out;
  6772. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6773. "Test: \r\n\r\n",
  6774. &out);
  6775. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6776. }
  6777. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6778. Server svr;
  6779. std::string x_custom;
  6780. std::string cookie;
  6781. std::string xff;
  6782. std::string x_unicode;
  6783. std::string x_iis;
  6784. svr.Get("/check", [&](const Request &req, Response &res) {
  6785. x_custom = req.get_header_value("X-Custom");
  6786. cookie = req.get_header_value("Cookie");
  6787. xff = req.get_header_value("X-Forwarded-For");
  6788. x_unicode = req.get_header_value("X-Unicode");
  6789. x_iis = req.get_header_value("X-IIS");
  6790. res.set_content("ok", "text/plain");
  6791. });
  6792. thread t = thread([&] { svr.listen(HOST, PORT); });
  6793. auto se = detail::scope_exit([&] {
  6794. svr.stop();
  6795. t.join();
  6796. ASSERT_FALSE(svr.is_running());
  6797. });
  6798. svr.wait_until_ready();
  6799. const std::string req = "GET /check HTTP/1.1\r\n"
  6800. "Host: localhost\r\n"
  6801. "X-Custom: a%0D%0AInjected: b\r\n"
  6802. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6803. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6804. "X-Unicode: %E3%81%82\r\n"
  6805. "X-IIS: %u00E9\r\n"
  6806. "Connection: close\r\n"
  6807. "\r\n";
  6808. std::string res;
  6809. ASSERT_TRUE(send_request(5, req, &res));
  6810. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6811. // Every value must be returned verbatim (wire form), with no decoding.
  6812. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6813. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6814. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6815. EXPECT_EQ("%E3%81%82", x_unicode);
  6816. EXPECT_EQ("%u00E9", x_iis);
  6817. }
  6818. // Applications that previously relied on automatic percent-decoding can
  6819. // reproduce the old behavior by explicitly calling decode_path_component()
  6820. // or, for RFC 3986 conformance, decode_uri_component().
  6821. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6822. Server svr;
  6823. std::string decoded;
  6824. svr.Get("/check", [&](const Request &req, Response &res) {
  6825. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6826. res.set_content("ok", "text/plain");
  6827. });
  6828. thread t = thread([&] { svr.listen(HOST, PORT); });
  6829. auto se = detail::scope_exit([&] {
  6830. svr.stop();
  6831. t.join();
  6832. ASSERT_FALSE(svr.is_running());
  6833. });
  6834. svr.wait_until_ready();
  6835. const std::string req = "GET /check HTTP/1.1\r\n"
  6836. "Host: localhost\r\n"
  6837. "X-Custom: hello%20world\r\n"
  6838. "Connection: close\r\n"
  6839. "\r\n";
  6840. std::string res;
  6841. ASSERT_TRUE(send_request(5, req, &res));
  6842. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6843. EXPECT_EQ("hello world", decoded);
  6844. }
  6845. // Regression test for #2033. Browsers send Referer values that include
  6846. // percent-encoded characters such as %0A inside the URL. Decoding the
  6847. // header value would either trip the post-decode CR/LF/NUL guard (the
  6848. // original bug, returning 400) or, after that guard was relaxed, silently
  6849. // store a literal LF — both unacceptable. The wire form must round-trip.
  6850. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6851. Server svr;
  6852. std::string referer;
  6853. svr.Get("/check", [&](const Request &req, Response &res) {
  6854. referer = req.get_header_value("Referer");
  6855. res.set_content("ok", "text/plain");
  6856. });
  6857. thread t = thread([&] { svr.listen(HOST, PORT); });
  6858. auto se = detail::scope_exit([&] {
  6859. svr.stop();
  6860. t.join();
  6861. ASSERT_FALSE(svr.is_running());
  6862. });
  6863. svr.wait_until_ready();
  6864. const std::string req = "GET /check HTTP/1.1\r\n"
  6865. "Host: localhost\r\n"
  6866. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6867. "Connection: close\r\n"
  6868. "\r\n";
  6869. std::string res;
  6870. ASSERT_TRUE(send_request(5, req, &res));
  6871. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6872. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6873. }
  6874. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6875. Server svr;
  6876. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6877. res.set_header("Cache-Control", "no-cache");
  6878. res.set_chunked_content_provider(
  6879. "text/event-stream", [](size_t offset, DataSink &sink) {
  6880. std::string s = "data:";
  6881. s += std::to_string(offset);
  6882. s += "\n\n";
  6883. auto ret = sink.write(s.data(), s.size());
  6884. EXPECT_TRUE(ret);
  6885. std::this_thread::sleep_for(std::chrono::seconds(1));
  6886. return true;
  6887. });
  6888. });
  6889. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6890. svr.wait_until_ready();
  6891. Client client(HOST, PORT);
  6892. const Headers headers = {{"Accept", "text/event-stream"}};
  6893. auto get_thread = std::thread([&client, &headers]() {
  6894. auto res = client.Get(
  6895. "/events", headers,
  6896. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6897. });
  6898. auto se = detail::scope_exit([&] {
  6899. svr.stop();
  6900. get_thread.join();
  6901. listen_thread.join();
  6902. ASSERT_FALSE(svr.is_running());
  6903. });
  6904. // Give GET time to get a few messages.
  6905. std::this_thread::sleep_for(std::chrono::seconds(2));
  6906. }
  6907. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6908. httplib::Server svr;
  6909. svr.Post("/hi",
  6910. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6911. res.status = StatusCode::OK_200;
  6912. });
  6913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6914. svr.wait_until_ready();
  6915. Client cli(HOST, PORT);
  6916. auto res = cli.Post("/hi", "data", "text/plain");
  6917. ASSERT_TRUE(res);
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. svr.stop();
  6920. thread.join();
  6921. ASSERT_FALSE(svr.is_running());
  6922. res = cli.Post("/hi", "data", "text/plain");
  6923. ASSERT_FALSE(res);
  6924. }
  6925. TEST(ServerStopTest, ListenFailure) {
  6926. Server svr;
  6927. auto t = thread([&]() {
  6928. auto ret = svr.listen("????", PORT);
  6929. EXPECT_FALSE(ret);
  6930. });
  6931. svr.wait_until_ready();
  6932. svr.stop();
  6933. t.join();
  6934. }
  6935. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6936. TEST(ServerStopTest, Decommision) {
  6937. Server svr;
  6938. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6939. for (int i = 0; i < 4; i++) {
  6940. auto is_even = !(i % 2);
  6941. std::thread t{[&] {
  6942. try {
  6943. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6944. if (is_even) {
  6945. throw std::runtime_error("Some thing that happens to go wrong.");
  6946. }
  6947. svr.listen(HOST, PORT);
  6948. } catch (...) { svr.decommission(); }
  6949. }};
  6950. svr.wait_until_ready();
  6951. // Server is up
  6952. {
  6953. Client cli(HOST, PORT);
  6954. auto res = cli.Get("/hi");
  6955. if (is_even) {
  6956. EXPECT_FALSE(res);
  6957. } else {
  6958. EXPECT_TRUE(res);
  6959. EXPECT_EQ("hi...", res->body);
  6960. }
  6961. }
  6962. svr.stop();
  6963. t.join();
  6964. // Server is down...
  6965. {
  6966. Client cli(HOST, PORT);
  6967. auto res = cli.Get("/hi");
  6968. EXPECT_FALSE(res);
  6969. }
  6970. }
  6971. }
  6972. #endif
  6973. // Helper function for string body upload progress tests
  6974. template <typename SetupHandler, typename ClientCall>
  6975. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6976. ClientCall &&client_call,
  6977. const string &body) {
  6978. Server svr;
  6979. setup_handler(svr);
  6980. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6981. auto se = detail::scope_exit([&] {
  6982. svr.stop();
  6983. t.join();
  6984. });
  6985. svr.wait_until_ready();
  6986. Client cli(HOST, PORT);
  6987. vector<uint64_t> progress_values;
  6988. bool progress_called = false;
  6989. auto res =
  6990. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6991. progress_values.push_back(current);
  6992. progress_called = true;
  6993. return true;
  6994. });
  6995. ASSERT_TRUE(res);
  6996. EXPECT_EQ(200, res->status);
  6997. EXPECT_TRUE(progress_called);
  6998. }
  6999. TEST(UploadProgressTest, PostStringBodyBasic) {
  7000. TestStringBodyUploadProgress(
  7001. [](Server &svr) {
  7002. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7003. res.set_content("received", "text/plain");
  7004. });
  7005. },
  7006. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7007. return cli.Post("/test", body, "text/plain", progress_callback);
  7008. },
  7009. "test data for upload progress");
  7010. }
  7011. TEST(UploadProgressTest, PutStringBodyBasic) {
  7012. TestStringBodyUploadProgress(
  7013. [](Server &svr) {
  7014. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7015. res.set_content("put received", "text/plain");
  7016. });
  7017. },
  7018. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7019. return cli.Put("/test", body, "text/plain", progress_callback);
  7020. },
  7021. "put test data for upload progress");
  7022. }
  7023. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7024. TestStringBodyUploadProgress(
  7025. [](Server &svr) {
  7026. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7027. res.set_content("patch received", "text/plain");
  7028. });
  7029. },
  7030. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7031. return cli.Patch("/test", body, "text/plain", progress_callback);
  7032. },
  7033. "patch test data for upload progress");
  7034. }
  7035. // Helper function for content provider upload progress tests
  7036. template <typename SetupHandler, typename ClientCall>
  7037. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7038. ClientCall &&client_call) {
  7039. Server svr;
  7040. setup_handler(svr);
  7041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7042. auto se = detail::scope_exit([&] {
  7043. svr.stop();
  7044. t.join();
  7045. });
  7046. svr.wait_until_ready();
  7047. Client cli(HOST, PORT);
  7048. vector<uint64_t> progress_values;
  7049. auto res =
  7050. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7051. progress_values.push_back(current);
  7052. return true;
  7053. });
  7054. ASSERT_TRUE(res);
  7055. EXPECT_EQ(200, res->status);
  7056. EXPECT_FALSE(progress_values.empty());
  7057. }
  7058. TEST(UploadProgressTest, PostContentProviderProgress) {
  7059. TestContentProviderUploadProgress(
  7060. [](Server &svr) {
  7061. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7062. res.set_content("provider received", "text/plain");
  7063. });
  7064. },
  7065. [](Client &cli, UploadProgress progress_callback) {
  7066. return cli.Post(
  7067. "/test", 10,
  7068. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7069. sink.os << "test data";
  7070. return true;
  7071. },
  7072. "text/plain", progress_callback);
  7073. });
  7074. }
  7075. // Helper function for multipart upload progress tests
  7076. template <typename SetupHandler, typename ClientCall>
  7077. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7078. ClientCall &&client_call,
  7079. const string &endpoint) {
  7080. Server svr;
  7081. setup_handler(svr);
  7082. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7083. auto se = detail::scope_exit([&] {
  7084. svr.stop();
  7085. t.join();
  7086. });
  7087. svr.wait_until_ready();
  7088. Client cli(HOST, PORT);
  7089. vector<uint64_t> progress_values;
  7090. UploadFormDataItems items = {
  7091. {"field1", "value1", "", ""},
  7092. {"field2", "longer value for progress tracking test", "", ""},
  7093. {"file1", "file content data for upload progress", "test.txt",
  7094. "text/plain"}};
  7095. auto res = client_call(cli, endpoint, items,
  7096. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7097. progress_values.push_back(current);
  7098. return true;
  7099. });
  7100. ASSERT_TRUE(res);
  7101. EXPECT_EQ(200, res->status);
  7102. EXPECT_FALSE(progress_values.empty());
  7103. }
  7104. TEST(UploadProgressTest, PostMultipartProgress) {
  7105. TestMultipartUploadProgress(
  7106. [](Server &svr) {
  7107. svr.Post("/multipart", [](const Request &req, Response &res) {
  7108. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7109. res.set_content("multipart received", "text/plain");
  7110. });
  7111. },
  7112. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7113. UploadProgress progress_callback) {
  7114. return cli.Post(endpoint, items, progress_callback);
  7115. },
  7116. "/multipart");
  7117. }
  7118. // Helper function for basic download progress tests
  7119. template <typename SetupHandler, typename ClientCall>
  7120. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7121. ClientCall &&client_call, const string &endpoint,
  7122. size_t expected_content_size) {
  7123. Server svr;
  7124. setup_handler(svr);
  7125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7126. auto se = detail::scope_exit([&] {
  7127. svr.stop();
  7128. t.join();
  7129. });
  7130. svr.wait_until_ready();
  7131. Client cli(HOST, PORT);
  7132. vector<uint64_t> progress_values;
  7133. auto res = client_call(cli, endpoint,
  7134. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7135. progress_values.push_back(current);
  7136. return true;
  7137. });
  7138. ASSERT_TRUE(res);
  7139. EXPECT_EQ(200, res->status);
  7140. EXPECT_FALSE(progress_values.empty());
  7141. EXPECT_EQ(expected_content_size, res->body.size());
  7142. }
  7143. TEST(DownloadProgressTest, GetBasic) {
  7144. TestBasicDownloadProgress(
  7145. [](Server &svr) {
  7146. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7147. string content(1000, 'D');
  7148. res.set_content(content, "text/plain");
  7149. });
  7150. },
  7151. [](Client &cli, const string &endpoint,
  7152. DownloadProgress progress_callback) {
  7153. return cli.Get(endpoint, progress_callback);
  7154. },
  7155. "/download", 1000u);
  7156. }
  7157. // Helper function for content receiver download progress tests
  7158. template <typename SetupHandler, typename ClientCall>
  7159. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7160. ClientCall &&client_call,
  7161. const string &endpoint,
  7162. size_t expected_content_size) {
  7163. Server svr;
  7164. setup_handler(svr);
  7165. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7166. auto se = detail::scope_exit([&] {
  7167. svr.stop();
  7168. t.join();
  7169. });
  7170. svr.wait_until_ready();
  7171. Client cli(HOST, PORT);
  7172. vector<uint64_t> progress_values;
  7173. string received_body;
  7174. auto res = client_call(
  7175. cli, endpoint,
  7176. [&](const char *data, size_t data_length) -> bool {
  7177. received_body.append(data, data_length);
  7178. return true;
  7179. },
  7180. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7181. progress_values.push_back(current);
  7182. return true;
  7183. });
  7184. ASSERT_TRUE(res);
  7185. EXPECT_EQ(200, res->status);
  7186. EXPECT_FALSE(progress_values.empty());
  7187. EXPECT_EQ(expected_content_size, received_body.size());
  7188. EXPECT_TRUE(res->body.empty());
  7189. }
  7190. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7191. TestContentReceiverDownloadProgress(
  7192. [](Server &svr) {
  7193. svr.Get("/download-receiver",
  7194. [](const Request & /*req*/, Response &res) {
  7195. string content(2000, 'R');
  7196. res.set_content(content, "text/plain");
  7197. });
  7198. },
  7199. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7200. DownloadProgress progress_callback) {
  7201. return cli.Get(endpoint, content_receiver, progress_callback);
  7202. },
  7203. "/download-receiver", 2000u);
  7204. }
  7205. TEST(StreamingTest, NoContentLengthStreaming) {
  7206. Server svr;
  7207. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7208. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7209. if (offset < 6) {
  7210. sink.os << (offset < 3 ? "a" : "b");
  7211. } else {
  7212. sink.done();
  7213. }
  7214. return true;
  7215. });
  7216. });
  7217. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7218. auto listen_se = detail::scope_exit([&] {
  7219. svr.stop();
  7220. listen_thread.join();
  7221. ASSERT_FALSE(svr.is_running());
  7222. });
  7223. svr.wait_until_ready();
  7224. Client client(HOST, PORT);
  7225. auto get_thread = std::thread([&client]() {
  7226. std::string s;
  7227. auto res =
  7228. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7229. s += std::string(data, len);
  7230. return true;
  7231. });
  7232. ASSERT_TRUE(res);
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. EXPECT_EQ("aaabbb", s);
  7235. });
  7236. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7237. // Give GET time to get a few messages.
  7238. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7239. }
  7240. TEST(MountTest, Unmount) {
  7241. Server svr;
  7242. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7243. auto se = detail::scope_exit([&] {
  7244. svr.stop();
  7245. listen_thread.join();
  7246. ASSERT_FALSE(svr.is_running());
  7247. });
  7248. svr.wait_until_ready();
  7249. Client cli("localhost", PORT);
  7250. svr.set_mount_point("/mount2", "./www2");
  7251. auto res = cli.Get("/");
  7252. ASSERT_TRUE(res);
  7253. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7254. res = cli.Get("/mount2/dir/test.html");
  7255. ASSERT_TRUE(res);
  7256. EXPECT_EQ(StatusCode::OK_200, res->status);
  7257. svr.set_mount_point("/", "./www");
  7258. res = cli.Get("/dir/");
  7259. ASSERT_TRUE(res);
  7260. EXPECT_EQ(StatusCode::OK_200, res->status);
  7261. svr.remove_mount_point("/");
  7262. res = cli.Get("/dir/");
  7263. ASSERT_TRUE(res);
  7264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7265. svr.remove_mount_point("/mount2");
  7266. res = cli.Get("/mount2/dir/test.html");
  7267. ASSERT_TRUE(res);
  7268. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7269. }
  7270. TEST(MountTest, Redicect) {
  7271. Server svr;
  7272. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7273. auto se = detail::scope_exit([&] {
  7274. svr.stop();
  7275. listen_thread.join();
  7276. ASSERT_FALSE(svr.is_running());
  7277. });
  7278. svr.set_mount_point("/", "./www");
  7279. svr.wait_until_ready();
  7280. Client cli("localhost", PORT);
  7281. auto res = cli.Get("/dir/");
  7282. ASSERT_TRUE(res);
  7283. EXPECT_EQ(StatusCode::OK_200, res->status);
  7284. res = cli.Get("/dir");
  7285. ASSERT_TRUE(res);
  7286. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7287. res = cli.Get("/file");
  7288. ASSERT_TRUE(res);
  7289. EXPECT_EQ(StatusCode::OK_200, res->status);
  7290. res = cli.Get("/file/");
  7291. ASSERT_TRUE(res);
  7292. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7293. cli.set_follow_location(true);
  7294. res = cli.Get("/dir");
  7295. ASSERT_TRUE(res);
  7296. EXPECT_EQ(StatusCode::OK_200, res->status);
  7297. }
  7298. TEST(MountTest, MultibytesPathName) {
  7299. Server svr;
  7300. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7301. auto se = detail::scope_exit([&] {
  7302. svr.stop();
  7303. listen_thread.join();
  7304. ASSERT_FALSE(svr.is_running());
  7305. });
  7306. svr.set_mount_point("/", "./www");
  7307. svr.wait_until_ready();
  7308. Client cli("localhost", PORT);
  7309. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7310. ASSERT_TRUE(res);
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7313. }
  7314. #ifdef _WIN32
  7315. // Issue #2435: mmap::open() must succeed even when another handle holds
  7316. // the file open for writing (e.g. an active log file).
  7317. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7318. const char *path = "mmap_concurrent_writer_test.txt";
  7319. const char *content = "hello";
  7320. {
  7321. std::ofstream f(path, std::ios::binary);
  7322. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7323. }
  7324. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7325. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7326. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7327. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7328. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7329. detail::mmap m(path);
  7330. ASSERT_TRUE(m.is_open());
  7331. EXPECT_EQ(strlen(content), m.size());
  7332. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7333. }
  7334. #endif
  7335. TEST(KeepAliveTest, ReadTimeout) {
  7336. Server svr;
  7337. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7338. std::this_thread::sleep_for(std::chrono::seconds(2));
  7339. res.set_content("a", "text/plain");
  7340. });
  7341. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7342. res.set_content("b", "text/plain");
  7343. });
  7344. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7345. auto se = detail::scope_exit([&] {
  7346. svr.stop();
  7347. listen_thread.join();
  7348. ASSERT_FALSE(svr.is_running());
  7349. });
  7350. svr.wait_until_ready();
  7351. Client cli("localhost", PORT);
  7352. cli.set_keep_alive(true);
  7353. cli.set_read_timeout(std::chrono::seconds(1));
  7354. auto resa = cli.Get("/a");
  7355. ASSERT_FALSE(resa);
  7356. EXPECT_EQ(Error::Read, resa.error());
  7357. auto resb = cli.Get("/b");
  7358. ASSERT_TRUE(resb);
  7359. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7360. EXPECT_EQ("b", resb->body);
  7361. }
  7362. TEST(KeepAliveTest, MaxCount) {
  7363. size_t keep_alive_max_count = 3;
  7364. Server svr;
  7365. svr.set_keep_alive_max_count(keep_alive_max_count);
  7366. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7367. res.set_content("Hello World!", "text/plain");
  7368. });
  7369. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7370. auto se = detail::scope_exit([&] {
  7371. svr.stop();
  7372. listen_thread.join();
  7373. ASSERT_FALSE(svr.is_running());
  7374. });
  7375. svr.wait_until_ready();
  7376. Client cli(HOST, PORT);
  7377. cli.set_keep_alive(true);
  7378. for (size_t i = 0; i < 5; i++) {
  7379. auto result = cli.Get("/hi");
  7380. ASSERT_TRUE(result);
  7381. EXPECT_EQ(StatusCode::OK_200, result->status);
  7382. if (i == keep_alive_max_count - 1) {
  7383. EXPECT_EQ("close", result->get_header_value("Connection"));
  7384. } else {
  7385. EXPECT_FALSE(result->has_header("Connection"));
  7386. }
  7387. }
  7388. }
  7389. TEST(KeepAliveTest, Issue1041) {
  7390. Server svr;
  7391. svr.set_keep_alive_timeout(3);
  7392. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7393. res.set_content("Hello World!", "text/plain");
  7394. });
  7395. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7396. auto se = detail::scope_exit([&] {
  7397. svr.stop();
  7398. listen_thread.join();
  7399. ASSERT_FALSE(svr.is_running());
  7400. });
  7401. svr.wait_until_ready();
  7402. Client cli(HOST, PORT);
  7403. cli.set_keep_alive(true);
  7404. auto result = cli.Get("/hi");
  7405. ASSERT_TRUE(result);
  7406. EXPECT_EQ(StatusCode::OK_200, result->status);
  7407. std::this_thread::sleep_for(std::chrono::seconds(5));
  7408. result = cli.Get("/hi");
  7409. ASSERT_TRUE(result);
  7410. EXPECT_EQ(StatusCode::OK_200, result->status);
  7411. }
  7412. TEST(KeepAliveTest, Issue1959) {
  7413. Server svr;
  7414. svr.set_keep_alive_timeout(5);
  7415. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7416. res.set_content("a", "text/plain");
  7417. });
  7418. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7419. auto se = detail::scope_exit([&] {
  7420. if (!svr.is_running()) return;
  7421. svr.stop();
  7422. listen_thread.join();
  7423. ASSERT_FALSE(svr.is_running());
  7424. });
  7425. svr.wait_until_ready();
  7426. Client cli("localhost", PORT);
  7427. cli.set_keep_alive(true);
  7428. using namespace std::chrono;
  7429. auto start = steady_clock::now();
  7430. cli.Get("/a");
  7431. svr.stop();
  7432. listen_thread.join();
  7433. auto end = steady_clock::now();
  7434. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7435. EXPECT_LT(elapsed, 5000);
  7436. }
  7437. #ifdef CPPHTTPLIB_SSL_ENABLED
  7438. TEST(KeepAliveTest, SSLClientReconnection) {
  7439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7440. ASSERT_TRUE(svr.is_valid());
  7441. svr.set_keep_alive_timeout(1);
  7442. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7443. res.set_content("Hello World!", "text/plain");
  7444. });
  7445. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7446. auto se = detail::scope_exit([&] {
  7447. svr.stop();
  7448. listen_thread.join();
  7449. ASSERT_FALSE(svr.is_running());
  7450. });
  7451. svr.wait_until_ready();
  7452. SSLClient cli(HOST, PORT);
  7453. cli.enable_server_certificate_verification(false);
  7454. cli.set_keep_alive(true);
  7455. auto result = cli.Get("/hi");
  7456. ASSERT_TRUE(result);
  7457. EXPECT_EQ(StatusCode::OK_200, result->status);
  7458. result = cli.Get("/hi");
  7459. ASSERT_TRUE(result);
  7460. EXPECT_EQ(StatusCode::OK_200, result->status);
  7461. std::this_thread::sleep_for(std::chrono::seconds(2));
  7462. // Recoonect
  7463. result = cli.Get("/hi");
  7464. ASSERT_TRUE(result);
  7465. EXPECT_EQ(StatusCode::OK_200, result->status);
  7466. result = cli.Get("/hi");
  7467. ASSERT_TRUE(result);
  7468. EXPECT_EQ(StatusCode::OK_200, result->status);
  7469. }
  7470. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7472. ASSERT_TRUE(svr.is_valid());
  7473. svr.set_keep_alive_timeout(1);
  7474. std::string content = "reconnect";
  7475. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7476. res.set_content("Hello World!", "text/plain");
  7477. });
  7478. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7479. auto se = detail::scope_exit([&] {
  7480. svr.stop();
  7481. listen_thread.join();
  7482. ASSERT_FALSE(svr.is_running());
  7483. });
  7484. svr.wait_until_ready();
  7485. SSLClient cli(HOST, PORT);
  7486. cli.enable_server_certificate_verification(false);
  7487. cli.set_keep_alive(true);
  7488. auto result = cli.Post(
  7489. "/hi", content.size(),
  7490. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7491. sink.write(content.c_str(), content.size());
  7492. return true;
  7493. },
  7494. "text/plain");
  7495. ASSERT_TRUE(result);
  7496. EXPECT_EQ(200, result->status);
  7497. std::this_thread::sleep_for(std::chrono::seconds(2));
  7498. // Recoonect
  7499. result = cli.Post(
  7500. "/hi", content.size(),
  7501. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7502. sink.write(content.c_str(), content.size());
  7503. return true;
  7504. },
  7505. "text/plain");
  7506. ASSERT_TRUE(result);
  7507. EXPECT_EQ(200, result->status);
  7508. result = cli.Post(
  7509. "/hi", content.size(),
  7510. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7511. sink.write(content.c_str(), content.size());
  7512. return true;
  7513. },
  7514. "text/plain");
  7515. ASSERT_TRUE(result);
  7516. EXPECT_EQ(200, result->status);
  7517. }
  7518. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7519. using namespace httplib::tls;
  7520. {
  7521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7522. ASSERT_TRUE(svr.is_valid());
  7523. svr.Get("/sni", [&](const Request &req, Response &res) {
  7524. std::string expected = req.sni();
  7525. EXPECT_EQ(expected, req.get_param_value("expected"));
  7526. res.set_content("ok", "text/plain");
  7527. });
  7528. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7529. auto se = detail::scope_exit([&] {
  7530. svr.stop();
  7531. listen_thread.join();
  7532. ASSERT_FALSE(svr.is_running());
  7533. });
  7534. svr.wait_until_ready();
  7535. {
  7536. SSLClient cli("localhost", PORT);
  7537. cli.enable_server_certificate_verification(false);
  7538. auto res = cli.Get("/sni?expected=localhost");
  7539. ASSERT_TRUE(res);
  7540. }
  7541. {
  7542. SSLClient cli("::1", PORT);
  7543. cli.enable_server_certificate_verification(false);
  7544. auto res = cli.Get("/sni?expected=");
  7545. // NOTE: This may fail if the server is listening on IPv4 only
  7546. // (e.g., when localhost resolves to 127.0.0.1 only)
  7547. if (res) {
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. } else {
  7550. EXPECT_EQ(Error::Connection, res.error());
  7551. }
  7552. }
  7553. }
  7554. }
  7555. #endif
  7556. TEST(ClientProblemDetectionTest, ContentProvider) {
  7557. Server svr;
  7558. size_t content_length = 1024 * 1024;
  7559. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7560. res.set_content_provider(
  7561. content_length, "text/plain",
  7562. [&](size_t offset, size_t length, DataSink &sink) {
  7563. auto out_len = std::min(length, static_cast<size_t>(1024));
  7564. std::string out(out_len, '@');
  7565. sink.write(out.data(), out_len);
  7566. return offset < 4096;
  7567. },
  7568. [](bool success) { ASSERT_FALSE(success); });
  7569. });
  7570. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7571. res.set_content_provider(
  7572. 0, "text/plain",
  7573. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7574. EXPECT_TRUE(false);
  7575. return true;
  7576. },
  7577. [](bool success) { ASSERT_FALSE(success); });
  7578. });
  7579. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7580. auto se = detail::scope_exit([&] {
  7581. svr.stop();
  7582. listen_thread.join();
  7583. ASSERT_FALSE(svr.is_running());
  7584. });
  7585. svr.wait_until_ready();
  7586. Client cli("localhost", PORT);
  7587. {
  7588. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7589. size_t /*data_length*/) { return false; });
  7590. ASSERT_FALSE(res);
  7591. }
  7592. {
  7593. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7594. size_t /*data_length*/) { return false; });
  7595. ASSERT_TRUE(res);
  7596. }
  7597. }
  7598. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7599. Server svr;
  7600. svr.set_error_handler([](Request const &, Response &res) -> void {
  7601. res.set_chunked_content_provider(
  7602. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7603. sink.os << "hello";
  7604. sink.os << "world";
  7605. sink.done();
  7606. return true;
  7607. });
  7608. });
  7609. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7610. auto se = detail::scope_exit([&] {
  7611. svr.stop();
  7612. listen_thread.join();
  7613. ASSERT_FALSE(svr.is_running());
  7614. });
  7615. svr.wait_until_ready();
  7616. Client cli("localhost", PORT);
  7617. auto res = cli.Get("/");
  7618. ASSERT_TRUE(res);
  7619. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7620. EXPECT_EQ("helloworld", res->body);
  7621. }
  7622. TEST(LongPollingTest, ClientCloseDetection) {
  7623. Server svr;
  7624. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7625. res.set_chunked_content_provider(
  7626. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7627. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7628. sink.os << "hello";
  7629. auto count = 10;
  7630. while (count > 0 && sink.is_writable()) {
  7631. this_thread::sleep_for(chrono::milliseconds(10));
  7632. count--;
  7633. }
  7634. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7635. return true;
  7636. });
  7637. });
  7638. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7639. auto se = detail::scope_exit([&] {
  7640. svr.stop();
  7641. listen_thread.join();
  7642. ASSERT_FALSE(svr.is_running());
  7643. });
  7644. svr.wait_until_ready();
  7645. Client cli("localhost", PORT);
  7646. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7647. EXPECT_EQ("hello", string(data, data_length));
  7648. return false; // close the socket immediately.
  7649. });
  7650. ASSERT_FALSE(res);
  7651. }
  7652. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7653. Server svr;
  7654. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7655. res.set_chunked_content_provider(
  7656. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7657. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7658. sink.os << "hello";
  7659. EXPECT_TRUE(sink.os.good());
  7660. // Wait for the client to close the connection
  7661. auto count = 10;
  7662. while (count > 0 && sink.is_writable()) {
  7663. this_thread::sleep_for(chrono::milliseconds(10));
  7664. count--;
  7665. }
  7666. // After client disconnect, write repeatedly until the socket
  7667. // write actually fails (small writes may be absorbed by the
  7668. // kernel buffer)
  7669. std::string chunk(1024, 'x');
  7670. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7671. sink.os << chunk;
  7672. }
  7673. EXPECT_TRUE(sink.os.fail());
  7674. return true;
  7675. });
  7676. });
  7677. auto port = svr.bind_to_any_port("localhost");
  7678. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7679. auto se = detail::scope_exit([&] {
  7680. svr.stop();
  7681. listen_thread.join();
  7682. ASSERT_FALSE(svr.is_running());
  7683. });
  7684. svr.wait_until_ready();
  7685. Client cli("localhost", port);
  7686. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7687. EXPECT_EQ("hello", string(data, data_length));
  7688. return false; // close the socket immediately.
  7689. });
  7690. ASSERT_FALSE(res);
  7691. }
  7692. TEST(GetWithParametersTest, GetWithParameters) {
  7693. Server svr;
  7694. svr.Get("/", [&](const Request &req, Response &) {
  7695. EXPECT_EQ("world", req.get_param_value("hello"));
  7696. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7697. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7698. });
  7699. svr.Get("/params", [&](const Request &req, Response &) {
  7700. EXPECT_EQ("world", req.get_param_value("hello"));
  7701. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7702. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7703. });
  7704. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7705. EXPECT_EQ("resource-id", req.matches[1]);
  7706. EXPECT_EQ("foo", req.get_param_value("param1"));
  7707. EXPECT_EQ("bar", req.get_param_value("param2"));
  7708. });
  7709. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7710. EXPECT_EQ("user-id", req.path_params.at("id"));
  7711. EXPECT_EQ("foo", req.get_param_value("param1"));
  7712. EXPECT_EQ("bar", req.get_param_value("param2"));
  7713. });
  7714. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7715. auto se = detail::scope_exit([&] {
  7716. svr.stop();
  7717. listen_thread.join();
  7718. ASSERT_FALSE(svr.is_running());
  7719. });
  7720. svr.wait_until_ready();
  7721. {
  7722. Client cli(HOST, PORT);
  7723. Params params;
  7724. params.emplace("hello", "world");
  7725. params.emplace("hello2", "world2");
  7726. params.emplace("hello3", "world3");
  7727. auto res = cli.Get("/", params, Headers{});
  7728. ASSERT_TRUE(res);
  7729. EXPECT_EQ(StatusCode::OK_200, res->status);
  7730. }
  7731. {
  7732. Client cli(HOST, PORT);
  7733. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7734. ASSERT_TRUE(res);
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. }
  7737. {
  7738. Client cli(HOST, PORT);
  7739. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7740. ASSERT_TRUE(res);
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. }
  7743. {
  7744. Client cli(HOST, PORT);
  7745. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7746. ASSERT_TRUE(res);
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. }
  7749. }
  7750. TEST(GetWithParametersTest, GetWithParameters2) {
  7751. Server svr;
  7752. svr.Get("/", [&](const Request &req, Response &res) {
  7753. auto text = req.get_param_value("hello");
  7754. res.set_content(text, "text/plain");
  7755. });
  7756. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7757. auto se = detail::scope_exit([&] {
  7758. svr.stop();
  7759. listen_thread.join();
  7760. ASSERT_FALSE(svr.is_running());
  7761. });
  7762. svr.wait_until_ready();
  7763. Client cli("localhost", PORT);
  7764. Params params;
  7765. params.emplace("hello", "world");
  7766. std::string body;
  7767. auto res = cli.Get("/", params, Headers{},
  7768. [&](const char *data, size_t data_length) {
  7769. body.append(data, data_length);
  7770. return true;
  7771. });
  7772. ASSERT_TRUE(res);
  7773. EXPECT_EQ(StatusCode::OK_200, res->status);
  7774. EXPECT_EQ("world", body);
  7775. }
  7776. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7777. Server svr;
  7778. svr.Get("/search", [&](const Request &req, Response &res) {
  7779. auto q = req.get_param_value("q");
  7780. res.set_content(q, "text/plain");
  7781. });
  7782. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7783. auto se = detail::scope_exit([&] {
  7784. svr.stop();
  7785. listen_thread.join();
  7786. ASSERT_FALSE(svr.is_running());
  7787. });
  7788. svr.wait_until_ready();
  7789. Client cli("localhost", PORT);
  7790. // Verify that Get(path, params) works without requiring Headers argument
  7791. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7792. ASSERT_TRUE(res);
  7793. EXPECT_EQ(StatusCode::OK_200, res->status);
  7794. EXPECT_EQ("cpp-httplib", res->body);
  7795. }
  7796. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7797. auto host = "httpbingo.org";
  7798. auto path = std::string{"/range/32"};
  7799. #ifdef CPPHTTPLIB_SSL_ENABLED
  7800. SSLClient cli(host);
  7801. #else
  7802. Client cli(host);
  7803. #endif
  7804. cli.set_default_headers({make_range_header({{1, 10}})});
  7805. cli.set_connection_timeout(5);
  7806. {
  7807. auto res = cli.Get(path);
  7808. ASSERT_TRUE(res);
  7809. EXPECT_EQ("bcdefghijk", res->body);
  7810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7811. }
  7812. {
  7813. auto res = cli.Get(path);
  7814. ASSERT_TRUE(res);
  7815. EXPECT_EQ("bcdefghijk", res->body);
  7816. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7817. }
  7818. }
  7819. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7820. Server svr;
  7821. svr.set_default_headers({{"Hello", "World"}});
  7822. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7823. res.set_content("ok", "text/plain");
  7824. });
  7825. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7826. auto se = detail::scope_exit([&] {
  7827. svr.stop();
  7828. listen_thread.join();
  7829. ASSERT_FALSE(svr.is_running());
  7830. });
  7831. svr.wait_until_ready();
  7832. Client cli("localhost", PORT);
  7833. auto res = cli.Get("/");
  7834. ASSERT_TRUE(res);
  7835. EXPECT_EQ(StatusCode::OK_200, res->status);
  7836. EXPECT_EQ("ok", res->body);
  7837. EXPECT_EQ("World", res->get_header_value("Hello"));
  7838. }
  7839. #ifdef CPPHTTPLIB_SSL_ENABLED
  7840. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7842. ASSERT_TRUE(svr.is_valid());
  7843. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7844. std::this_thread::sleep_for(std::chrono::seconds(2));
  7845. res.set_content("a", "text/plain");
  7846. });
  7847. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7848. res.set_content("b", "text/plain");
  7849. });
  7850. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7851. auto se = detail::scope_exit([&] {
  7852. svr.stop();
  7853. listen_thread.join();
  7854. ASSERT_FALSE(svr.is_running());
  7855. });
  7856. svr.wait_until_ready();
  7857. SSLClient cli("localhost", PORT);
  7858. cli.enable_server_certificate_verification(false);
  7859. cli.set_keep_alive(true);
  7860. cli.set_read_timeout(std::chrono::seconds(1));
  7861. auto resa = cli.Get("/a");
  7862. ASSERT_TRUE(!resa);
  7863. EXPECT_EQ(Error::Read, resa.error());
  7864. auto resb = cli.Get("/b");
  7865. ASSERT_TRUE(resb);
  7866. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7867. EXPECT_EQ("b", resb->body);
  7868. }
  7869. #endif
  7870. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7871. protected:
  7872. ServerTestWithAI_PASSIVE()
  7873. : cli_(HOST, PORT)
  7874. #ifdef CPPHTTPLIB_SSL_ENABLED
  7875. ,
  7876. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7877. #endif
  7878. {
  7879. #ifdef CPPHTTPLIB_SSL_ENABLED
  7880. cli_.enable_server_certificate_verification(false);
  7881. #endif
  7882. }
  7883. virtual void SetUp() {
  7884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7885. res.set_content("Hello World!", "text/plain");
  7886. });
  7887. t_ = thread(
  7888. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7889. svr_.wait_until_ready();
  7890. }
  7891. virtual void TearDown() {
  7892. svr_.stop();
  7893. t_.join();
  7894. }
  7895. #ifdef CPPHTTPLIB_SSL_ENABLED
  7896. SSLClient cli_;
  7897. SSLServer svr_;
  7898. #else
  7899. Client cli_;
  7900. Server svr_;
  7901. #endif
  7902. thread t_;
  7903. };
  7904. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7905. auto res = cli_.Get("/hi");
  7906. ASSERT_TRUE(res);
  7907. EXPECT_EQ(StatusCode::OK_200, res->status);
  7908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7909. EXPECT_EQ("Hello World!", res->body);
  7910. }
  7911. class ServerUpDownTest : public ::testing::Test {
  7912. protected:
  7913. ServerUpDownTest() : cli_(HOST, PORT) {}
  7914. virtual void SetUp() {
  7915. t_ = thread([&]() {
  7916. svr_.bind_to_any_port(HOST);
  7917. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7918. ASSERT_TRUE(svr_.listen_after_bind());
  7919. });
  7920. svr_.wait_until_ready();
  7921. }
  7922. virtual void TearDown() {
  7923. svr_.stop();
  7924. t_.join();
  7925. }
  7926. Client cli_;
  7927. Server svr_;
  7928. thread t_;
  7929. };
  7930. TEST_F(ServerUpDownTest, QuickStartStop) {
  7931. // Should not crash, especially when run with
  7932. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7933. }
  7934. class PayloadMaxLengthTest : public ::testing::Test {
  7935. protected:
  7936. PayloadMaxLengthTest()
  7937. : cli_(HOST, PORT)
  7938. #ifdef CPPHTTPLIB_SSL_ENABLED
  7939. ,
  7940. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7941. #endif
  7942. {
  7943. #ifdef CPPHTTPLIB_SSL_ENABLED
  7944. cli_.enable_server_certificate_verification(false);
  7945. #endif
  7946. }
  7947. virtual void SetUp() {
  7948. svr_.set_payload_max_length(8);
  7949. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7950. res.set_content("test", "text/plain");
  7951. });
  7952. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7953. svr_.wait_until_ready();
  7954. }
  7955. virtual void TearDown() {
  7956. svr_.stop();
  7957. t_.join();
  7958. }
  7959. #ifdef CPPHTTPLIB_SSL_ENABLED
  7960. SSLClient cli_;
  7961. SSLServer svr_;
  7962. #else
  7963. Client cli_;
  7964. Server svr_;
  7965. #endif
  7966. thread t_;
  7967. };
  7968. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7969. auto res = cli_.Post("/test", "123456789", "text/plain");
  7970. ASSERT_TRUE(res);
  7971. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7972. res = cli_.Post("/test", "12345678", "text/plain");
  7973. ASSERT_TRUE(res);
  7974. EXPECT_EQ(StatusCode::OK_200, res->status);
  7975. }
  7976. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7977. // Test chunked encoding with payload exceeding the 8-byte limit
  7978. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7979. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7980. ASSERT_TRUE(res);
  7981. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7982. }
  7983. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7984. // Test chunked encoding with payload within the 8-byte limit
  7985. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7986. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7987. ASSERT_TRUE(res);
  7988. EXPECT_EQ(StatusCode::OK_200, res->status);
  7989. }
  7990. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7991. // Test using send_request to send chunked data exceeding payload limit
  7992. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7993. "Host: " +
  7994. std::string(HOST) + ":" + std::to_string(PORT) +
  7995. "\r\n"
  7996. "Transfer-Encoding: chunked\r\n"
  7997. "Connection: close\r\n"
  7998. "\r\n"
  7999. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8000. "0123456789\r\n"
  8001. "0\r\n" // End chunk
  8002. "\r\n";
  8003. std::string response;
  8004. bool result = send_request(1, chunked_request, &response);
  8005. if (!result) {
  8006. // If send_request fails, it might be because the server closed the
  8007. // connection due to payload limit enforcement, which is acceptable
  8008. SUCCEED()
  8009. << "Server rejected oversized chunked request (connection closed)";
  8010. } else {
  8011. // If we got a response, check if it's an error response or connection was
  8012. // closed early Short response length indicates connection was closed due to
  8013. // payload limit
  8014. if (response.length() <= 10) {
  8015. SUCCEED() << "Server closed connection for oversized chunked request";
  8016. } else {
  8017. // Check for error status codes
  8018. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8019. response.find("Payload Too Large") != std::string::npos ||
  8020. response.find("400") != std::string::npos);
  8021. }
  8022. }
  8023. }
  8024. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8025. // Test request without Content-Length header exceeding payload limit
  8026. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8027. "Host: " +
  8028. std::string(HOST) + ":" +
  8029. std::to_string(PORT) +
  8030. "\r\n"
  8031. "Connection: close\r\n"
  8032. "\r\n";
  8033. // Add payload exceeding the 8-byte limit
  8034. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8035. request_without_content_length += large_payload;
  8036. std::string response;
  8037. bool result = send_request(1, request_without_content_length, &response);
  8038. if (!result) {
  8039. // If send_request fails, server likely closed connection due to payload
  8040. // limit
  8041. SUCCEED() << "Server rejected oversized request without Content-Length "
  8042. "(connection closed)";
  8043. } else {
  8044. // Check if server responded with error or closed connection early
  8045. if (response.length() <= 10) {
  8046. SUCCEED() << "Server closed connection for oversized request without "
  8047. "Content-Length";
  8048. } else {
  8049. // Check for error status codes
  8050. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8051. response.find("Payload Too Large") != std::string::npos ||
  8052. response.find("400") != std::string::npos);
  8053. }
  8054. }
  8055. }
  8056. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8057. // Test request without Content-Length header within payload limit
  8058. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8059. "Host: " +
  8060. std::string(HOST) + ":" +
  8061. std::to_string(PORT) +
  8062. "\r\n"
  8063. "Connection: close\r\n"
  8064. "\r\n";
  8065. // Add payload within the 8-byte limit
  8066. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8067. request_without_content_length += small_payload;
  8068. std::string response;
  8069. bool result = send_request(1, request_without_content_length, &response);
  8070. // For requests without Content-Length, the server may have different behavior
  8071. // The key is that it should not reject due to payload limit for small
  8072. // payloads
  8073. if (result) {
  8074. // Check for any HTTP response (success or error, but not connection closed)
  8075. if (response.length() > 10) {
  8076. SUCCEED()
  8077. << "Server processed request without Content-Length within limit";
  8078. } else {
  8079. // Short response might indicate connection closed, which is acceptable
  8080. SUCCEED() << "Server closed connection for request without "
  8081. "Content-Length (acceptable behavior)";
  8082. }
  8083. } else {
  8084. // Connection failure might be due to protocol requirements
  8085. SUCCEED() << "Connection issue with request without Content-Length "
  8086. "(environment-specific)";
  8087. }
  8088. }
  8089. class LargePayloadMaxLengthTest : public ::testing::Test {
  8090. protected:
  8091. LargePayloadMaxLengthTest()
  8092. : cli_(HOST, PORT)
  8093. #ifdef CPPHTTPLIB_SSL_ENABLED
  8094. ,
  8095. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8096. #endif
  8097. {
  8098. #ifdef CPPHTTPLIB_SSL_ENABLED
  8099. cli_.enable_server_certificate_verification(false);
  8100. #endif
  8101. }
  8102. virtual void SetUp() {
  8103. // Set 10MB payload limit
  8104. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8105. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8106. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8107. res.set_content("Large payload test", "text/plain");
  8108. });
  8109. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8110. svr_.wait_until_ready();
  8111. }
  8112. virtual void TearDown() {
  8113. svr_.stop();
  8114. t_.join();
  8115. }
  8116. #ifdef CPPHTTPLIB_SSL_ENABLED
  8117. SSLClient cli_;
  8118. SSLServer svr_;
  8119. #else
  8120. Client cli_;
  8121. Server svr_;
  8122. #endif
  8123. thread t_;
  8124. };
  8125. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8126. // Test chunked encoding with payload within 10MB limit
  8127. std::string medium_payload(5 * 1024 * 1024,
  8128. 'A'); // 5MB payload, within 10MB limit
  8129. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8130. ASSERT_TRUE(res);
  8131. EXPECT_EQ(StatusCode::OK_200, res->status);
  8132. }
  8133. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8134. // Test chunked encoding with payload exceeding 10MB limit
  8135. std::string large_payload(12 * 1024 * 1024,
  8136. 'B'); // 12MB payload, exceeds 10MB limit
  8137. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8138. // Server may either return 413 or close the connection
  8139. if (res) {
  8140. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8141. } else {
  8142. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8143. }
  8144. }
  8145. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8146. // Test request without Content-Length header within 10MB limit
  8147. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8148. "Host: " +
  8149. std::string(HOST) + ":" +
  8150. std::to_string(PORT) +
  8151. "\r\n"
  8152. "Connection: close\r\n"
  8153. "\r\n";
  8154. // Add 1MB payload (within 10MB limit)
  8155. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8156. request_without_content_length += medium_payload;
  8157. std::string response;
  8158. bool result = send_request(5, request_without_content_length, &response);
  8159. if (result) {
  8160. // Should get a proper HTTP response for payloads within limit
  8161. if (response.length() > 10) {
  8162. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8163. "10MB limit";
  8164. } else {
  8165. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8166. "Content-Length)";
  8167. }
  8168. } else {
  8169. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8170. }
  8171. }
  8172. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8173. // Test request without Content-Length header exceeding 10MB limit
  8174. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8175. "Host: " +
  8176. std::string(HOST) + ":" +
  8177. std::to_string(PORT) +
  8178. "\r\n"
  8179. "Connection: close\r\n"
  8180. "\r\n";
  8181. // Add 12MB payload (exceeds 10MB limit)
  8182. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8183. request_without_content_length += large_payload;
  8184. std::string response;
  8185. bool result = send_request(10, request_without_content_length, &response);
  8186. if (!result) {
  8187. // Server should close connection due to payload limit
  8188. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8189. "(connection closed)";
  8190. } else {
  8191. // Check for error response
  8192. if (response.length() <= 10) {
  8193. SUCCEED()
  8194. << "Server closed connection for 12MB request exceeding 10MB limit";
  8195. } else {
  8196. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8197. response.find("Payload Too Large") != std::string::npos ||
  8198. response.find("400") != std::string::npos);
  8199. }
  8200. }
  8201. }
  8202. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8203. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8204. // path.
  8205. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8206. Server svr;
  8207. const size_t LIMIT = 64 * 1024; // 64KB
  8208. svr.set_payload_max_length(LIMIT);
  8209. size_t total = 0;
  8210. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8211. const ContentReader &content_reader) {
  8212. content_reader([&](const char * /*data*/, size_t len) {
  8213. total += len;
  8214. return true;
  8215. });
  8216. res.status = 200;
  8217. res.set_content("stream_ok", "text/plain");
  8218. });
  8219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8220. auto se = detail::scope_exit([&] {
  8221. svr.stop();
  8222. thread.join();
  8223. ASSERT_FALSE(svr.is_running());
  8224. });
  8225. svr.wait_until_ready();
  8226. // Prepare 256KB raw data and gzip-compress it
  8227. std::string raw(256 * 1024, 'A');
  8228. std::string gz;
  8229. {
  8230. z_stream zs{};
  8231. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8232. Z_DEFAULT_STRATEGY);
  8233. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8234. zs.avail_in = static_cast<uInt>(raw.size());
  8235. char outbuf[4096];
  8236. int ret;
  8237. do {
  8238. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8239. zs.avail_out = sizeof(outbuf);
  8240. ret = deflate(&zs, Z_FINISH);
  8241. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8242. } while (ret != Z_STREAM_END);
  8243. deflateEnd(&zs);
  8244. }
  8245. Client cli(HOST, PORT);
  8246. cli.set_connection_timeout(std::chrono::seconds(5));
  8247. Headers headers = {{"Content-Encoding", "gzip"}};
  8248. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8249. "application/octet-stream");
  8250. ASSERT_TRUE(res);
  8251. // Server must reject oversized decompressed payloads with 413.
  8252. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8253. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8254. EXPECT_LE(total, LIMIT);
  8255. }
  8256. #endif
  8257. // Regression test for DoS vulnerability: a malicious server sending a response
  8258. // without Content-Length header must not cause unbounded memory consumption on
  8259. // the client side. The client should stop reading after a reasonable limit,
  8260. // similar to the server-side set_payload_max_length protection.
  8261. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8262. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8263. #ifndef _WIN32
  8264. signal(SIGPIPE, SIG_IGN);
  8265. #endif
  8266. auto server_thread = std::thread([] {
  8267. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8268. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8269. default_socket_options(srv);
  8270. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8271. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8272. sockaddr_in addr{};
  8273. addr.sin_family = AF_INET;
  8274. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8275. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8276. int opt = 1;
  8277. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8278. #ifdef _WIN32
  8279. reinterpret_cast<const char *>(&opt),
  8280. #else
  8281. &opt,
  8282. #endif
  8283. sizeof(opt));
  8284. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8285. ::listen(srv, 1);
  8286. sockaddr_in cli_addr{};
  8287. socklen_t cli_len = sizeof(cli_addr);
  8288. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8289. if (cli != INVALID_SOCKET) {
  8290. char buf[4096];
  8291. ::recv(cli, buf, sizeof(buf), 0);
  8292. // Malicious response: no Content-Length, no chunked encoding
  8293. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8294. "Connection: close\r\n"
  8295. "\r\n";
  8296. ::send(cli,
  8297. #ifdef _WIN32
  8298. static_cast<const char *>(response_header.c_str()),
  8299. static_cast<int>(response_header.size()),
  8300. #else
  8301. response_header.c_str(), response_header.size(),
  8302. #endif
  8303. 0);
  8304. // Send 10MB of data
  8305. std::string chunk(64 * 1024, 'A');
  8306. size_t total_sent = 0;
  8307. while (total_sent < MALICIOUS_DATA_SIZE) {
  8308. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8309. auto sent = ::send(cli,
  8310. #ifdef _WIN32
  8311. static_cast<const char *>(chunk.c_str()),
  8312. static_cast<int>(to_send),
  8313. #else
  8314. chunk.c_str(), to_send,
  8315. #endif
  8316. 0);
  8317. if (sent <= 0) break;
  8318. total_sent += static_cast<size_t>(sent);
  8319. }
  8320. detail::close_socket(cli);
  8321. }
  8322. detail::close_socket(srv);
  8323. });
  8324. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8325. size_t total_read = 0;
  8326. {
  8327. Client cli("127.0.0.1", PORT + 2);
  8328. cli.set_read_timeout(5, 0);
  8329. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8330. auto stream = cli.open_stream("GET", "/malicious");
  8331. ASSERT_TRUE(stream.is_valid());
  8332. char buffer[64 * 1024];
  8333. ssize_t n;
  8334. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8335. total_read += static_cast<size_t>(n);
  8336. }
  8337. } // StreamHandle and Client destroyed here, closing the socket
  8338. server_thread.join();
  8339. // With set_payload_max_length, the client must stop reading before consuming
  8340. // all 10MB. The read loop should be cut off at or near the configured limit.
  8341. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8342. << "Client read " << total_read << " bytes, exceeding the configured "
  8343. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8344. }
  8345. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8346. // the entire response body without truncation.
  8347. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8348. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8349. #ifndef _WIN32
  8350. signal(SIGPIPE, SIG_IGN);
  8351. #endif
  8352. auto server_thread = std::thread([] {
  8353. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8354. default_socket_options(srv);
  8355. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8356. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8357. sockaddr_in addr{};
  8358. addr.sin_family = AF_INET;
  8359. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8360. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8361. int opt = 1;
  8362. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8363. #ifdef _WIN32
  8364. reinterpret_cast<const char *>(&opt),
  8365. #else
  8366. &opt,
  8367. #endif
  8368. sizeof(opt));
  8369. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8370. ::listen(srv, 1);
  8371. sockaddr_in cli_addr{};
  8372. socklen_t cli_len = sizeof(cli_addr);
  8373. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8374. if (cli != INVALID_SOCKET) {
  8375. char buf[4096];
  8376. ::recv(cli, buf, sizeof(buf), 0);
  8377. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8378. "Connection: close\r\n"
  8379. "\r\n";
  8380. ::send(cli,
  8381. #ifdef _WIN32
  8382. static_cast<const char *>(response_header.c_str()),
  8383. static_cast<int>(response_header.size()),
  8384. #else
  8385. response_header.c_str(), response_header.size(),
  8386. #endif
  8387. 0);
  8388. std::string chunk(64 * 1024, 'A');
  8389. size_t total_sent = 0;
  8390. while (total_sent < DATA_SIZE) {
  8391. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8392. auto sent = ::send(cli,
  8393. #ifdef _WIN32
  8394. static_cast<const char *>(chunk.c_str()),
  8395. static_cast<int>(to_send),
  8396. #else
  8397. chunk.c_str(), to_send,
  8398. #endif
  8399. 0);
  8400. if (sent <= 0) break;
  8401. total_sent += static_cast<size_t>(sent);
  8402. }
  8403. #ifdef _WIN32
  8404. ::shutdown(cli, SD_SEND);
  8405. #else
  8406. ::shutdown(cli, SHUT_WR);
  8407. #endif
  8408. // Drain until the client closes its end, ensuring all data is delivered
  8409. char drain[1024];
  8410. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8411. detail::close_socket(cli);
  8412. }
  8413. detail::close_socket(srv);
  8414. });
  8415. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8416. size_t total_read = 0;
  8417. {
  8418. Client cli("127.0.0.1", PORT + 2);
  8419. cli.set_read_timeout(5, 0);
  8420. cli.set_payload_max_length(0); // 0 means no limit
  8421. auto stream = cli.open_stream("GET", "/data");
  8422. ASSERT_TRUE(stream.is_valid());
  8423. char buffer[64 * 1024];
  8424. ssize_t n;
  8425. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8426. total_read += static_cast<size_t>(n);
  8427. }
  8428. }
  8429. server_thread.join();
  8430. EXPECT_EQ(total_read, DATA_SIZE)
  8431. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8432. << " bytes without truncation, but only read " << total_read << " bytes.";
  8433. }
  8434. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8435. // enormous Content-Length must not cause the client to pre-allocate a huge
  8436. // response body buffer. The reservation is capped at payload_max_length_, and
  8437. // the read itself fails when the body exceeds the limit.
  8438. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8439. #ifndef _WIN32
  8440. signal(SIGPIPE, SIG_IGN);
  8441. #endif
  8442. auto server_thread = std::thread([] {
  8443. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8444. default_socket_options(srv);
  8445. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8446. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8447. sockaddr_in addr{};
  8448. addr.sin_family = AF_INET;
  8449. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8450. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8451. int opt = 1;
  8452. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8453. #ifdef _WIN32
  8454. reinterpret_cast<const char *>(&opt),
  8455. #else
  8456. &opt,
  8457. #endif
  8458. sizeof(opt));
  8459. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8460. ::listen(srv, 1);
  8461. sockaddr_in cli_addr{};
  8462. socklen_t cli_len = sizeof(cli_addr);
  8463. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8464. if (cli != INVALID_SOCKET) {
  8465. char buf[4096];
  8466. ::recv(cli, buf, sizeof(buf), 0);
  8467. // Malicious response: claim a 20GB body but send only a tiny payload.
  8468. std::string response = "HTTP/1.1 200 OK\r\n"
  8469. "Content-Length: 20000000000\r\n"
  8470. "\r\n"
  8471. "abc";
  8472. ::send(cli,
  8473. #ifdef _WIN32
  8474. static_cast<const char *>(response.c_str()),
  8475. static_cast<int>(response.size()),
  8476. #else
  8477. response.c_str(), response.size(),
  8478. #endif
  8479. 0);
  8480. detail::close_socket(cli);
  8481. }
  8482. detail::close_socket(srv);
  8483. });
  8484. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8485. {
  8486. Client cli("127.0.0.1", PORT + 2);
  8487. cli.set_read_timeout(5, 0);
  8488. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8489. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8490. // (server claims more bytes than payload_max_length permits), but it must
  8491. // not exhaust memory before getting there.
  8492. auto res = cli.Get("/malicious");
  8493. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8494. }
  8495. server_thread.join();
  8496. }
  8497. // Verify that content_receiver bypasses the default payload_max_length,
  8498. // allowing streaming downloads larger than 100MB without requiring an explicit
  8499. // set_payload_max_length call.
  8500. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8501. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8502. #ifndef _WIN32
  8503. signal(SIGPIPE, SIG_IGN);
  8504. #endif
  8505. auto server_thread = std::thread([] {
  8506. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8507. default_socket_options(srv);
  8508. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8509. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8510. sockaddr_in addr{};
  8511. addr.sin_family = AF_INET;
  8512. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8513. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8514. int opt = 1;
  8515. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8516. #ifdef _WIN32
  8517. reinterpret_cast<const char *>(&opt),
  8518. #else
  8519. &opt,
  8520. #endif
  8521. sizeof(opt));
  8522. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8523. ::listen(srv, 1);
  8524. sockaddr_in cli_addr{};
  8525. socklen_t cli_len = sizeof(cli_addr);
  8526. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8527. if (cli != INVALID_SOCKET) {
  8528. char buf[4096];
  8529. ::recv(cli, buf, sizeof(buf), 0);
  8530. // Response with Content-Length larger than default 100MB limit
  8531. auto content_length = std::to_string(DATA_SIZE);
  8532. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8533. "Content-Length: " +
  8534. content_length +
  8535. "\r\n"
  8536. "Connection: close\r\n"
  8537. "\r\n";
  8538. ::send(cli,
  8539. #ifdef _WIN32
  8540. static_cast<const char *>(response_header.c_str()),
  8541. static_cast<int>(response_header.size()),
  8542. #else
  8543. response_header.c_str(), response_header.size(),
  8544. #endif
  8545. 0);
  8546. std::string chunk(64 * 1024, 'A');
  8547. size_t total_sent = 0;
  8548. while (total_sent < DATA_SIZE) {
  8549. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8550. auto sent = ::send(cli,
  8551. #ifdef _WIN32
  8552. static_cast<const char *>(chunk.c_str()),
  8553. static_cast<int>(to_send),
  8554. #else
  8555. chunk.c_str(), to_send,
  8556. #endif
  8557. 0);
  8558. if (sent <= 0) break;
  8559. total_sent += static_cast<size_t>(sent);
  8560. }
  8561. detail::close_socket(cli);
  8562. }
  8563. detail::close_socket(srv);
  8564. });
  8565. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8566. size_t total_received = 0;
  8567. {
  8568. Client cli("127.0.0.1", PORT + 2);
  8569. cli.set_read_timeout(10, 0);
  8570. // Do NOT call set_payload_max_length — use the default 100MB limit
  8571. auto res =
  8572. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8573. total_received += data_length;
  8574. return true;
  8575. });
  8576. ASSERT_TRUE(res);
  8577. EXPECT_EQ(StatusCode::OK_200, res->status);
  8578. }
  8579. server_thread.join();
  8580. EXPECT_EQ(total_received, DATA_SIZE)
  8581. << "With content_receiver, the client should read all " << DATA_SIZE
  8582. << " bytes despite the default 100MB payload_max_length, but only read "
  8583. << total_received << " bytes.";
  8584. }
  8585. // Verify that an explicit set_payload_max_length smaller than the response is
  8586. // enforced even when a content_receiver is used.
  8587. TEST(ClientVulnerabilityTest,
  8588. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8589. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8590. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8591. #ifndef _WIN32
  8592. signal(SIGPIPE, SIG_IGN);
  8593. #endif
  8594. auto server_thread = std::thread([] {
  8595. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8596. default_socket_options(srv);
  8597. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8598. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8599. sockaddr_in addr{};
  8600. addr.sin_family = AF_INET;
  8601. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8602. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8603. int opt = 1;
  8604. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8605. #ifdef _WIN32
  8606. reinterpret_cast<const char *>(&opt),
  8607. #else
  8608. &opt,
  8609. #endif
  8610. sizeof(opt));
  8611. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8612. ::listen(srv, 1);
  8613. sockaddr_in cli_addr{};
  8614. socklen_t cli_len = sizeof(cli_addr);
  8615. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8616. if (cli != INVALID_SOCKET) {
  8617. char buf[4096];
  8618. ::recv(cli, buf, sizeof(buf), 0);
  8619. auto content_length = std::to_string(DATA_SIZE);
  8620. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8621. "Content-Length: " +
  8622. content_length +
  8623. "\r\n"
  8624. "Connection: close\r\n"
  8625. "\r\n";
  8626. ::send(cli,
  8627. #ifdef _WIN32
  8628. static_cast<const char *>(response_header.c_str()),
  8629. static_cast<int>(response_header.size()),
  8630. #else
  8631. response_header.c_str(), response_header.size(),
  8632. #endif
  8633. 0);
  8634. std::string chunk(64 * 1024, 'A');
  8635. size_t total_sent = 0;
  8636. while (total_sent < DATA_SIZE) {
  8637. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8638. auto sent = ::send(cli,
  8639. #ifdef _WIN32
  8640. static_cast<const char *>(chunk.c_str()),
  8641. static_cast<int>(to_send),
  8642. #else
  8643. chunk.c_str(), to_send,
  8644. #endif
  8645. 0);
  8646. if (sent <= 0) break;
  8647. total_sent += static_cast<size_t>(sent);
  8648. }
  8649. detail::close_socket(cli);
  8650. }
  8651. detail::close_socket(srv);
  8652. });
  8653. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8654. size_t total_received = 0;
  8655. {
  8656. Client cli("127.0.0.1", PORT + 2);
  8657. cli.set_read_timeout(10, 0);
  8658. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8659. auto res =
  8660. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8661. total_received += data_length;
  8662. return true;
  8663. });
  8664. // Should fail because 200MB exceeds the explicit 150MB limit
  8665. EXPECT_FALSE(res);
  8666. }
  8667. server_thread.join();
  8668. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8669. << "Client with content_receiver should respect the explicit "
  8670. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8671. << total_received << " bytes.";
  8672. }
  8673. // Verify that an explicit set_payload_max_length larger than the response
  8674. // allows the content_receiver to read all data successfully.
  8675. TEST(ClientVulnerabilityTest,
  8676. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8677. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8678. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8679. #ifndef _WIN32
  8680. signal(SIGPIPE, SIG_IGN);
  8681. #endif
  8682. auto server_thread = std::thread([] {
  8683. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8684. default_socket_options(srv);
  8685. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8687. sockaddr_in addr{};
  8688. addr.sin_family = AF_INET;
  8689. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8690. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8691. int opt = 1;
  8692. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8693. #ifdef _WIN32
  8694. reinterpret_cast<const char *>(&opt),
  8695. #else
  8696. &opt,
  8697. #endif
  8698. sizeof(opt));
  8699. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8700. ::listen(srv, 1);
  8701. sockaddr_in cli_addr{};
  8702. socklen_t cli_len = sizeof(cli_addr);
  8703. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8704. if (cli != INVALID_SOCKET) {
  8705. char buf[4096];
  8706. ::recv(cli, buf, sizeof(buf), 0);
  8707. auto content_length = std::to_string(DATA_SIZE);
  8708. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8709. "Content-Length: " +
  8710. content_length +
  8711. "\r\n"
  8712. "Connection: close\r\n"
  8713. "\r\n";
  8714. ::send(cli,
  8715. #ifdef _WIN32
  8716. static_cast<const char *>(response_header.c_str()),
  8717. static_cast<int>(response_header.size()),
  8718. #else
  8719. response_header.c_str(), response_header.size(),
  8720. #endif
  8721. 0);
  8722. std::string chunk(64 * 1024, 'A');
  8723. size_t total_sent = 0;
  8724. while (total_sent < DATA_SIZE) {
  8725. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8726. auto sent = ::send(cli,
  8727. #ifdef _WIN32
  8728. static_cast<const char *>(chunk.c_str()),
  8729. static_cast<int>(to_send),
  8730. #else
  8731. chunk.c_str(), to_send,
  8732. #endif
  8733. 0);
  8734. if (sent <= 0) break;
  8735. total_sent += static_cast<size_t>(sent);
  8736. }
  8737. #ifdef _WIN32
  8738. ::shutdown(cli, SD_SEND);
  8739. #else
  8740. ::shutdown(cli, SHUT_WR);
  8741. #endif
  8742. char drain[1024];
  8743. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8744. detail::close_socket(cli);
  8745. }
  8746. detail::close_socket(srv);
  8747. });
  8748. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8749. size_t total_received = 0;
  8750. {
  8751. Client cli("127.0.0.1", PORT + 2);
  8752. cli.set_read_timeout(10, 0);
  8753. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8754. auto res =
  8755. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8756. total_received += data_length;
  8757. return true;
  8758. });
  8759. ASSERT_TRUE(res);
  8760. EXPECT_EQ(StatusCode::OK_200, res->status);
  8761. }
  8762. server_thread.join();
  8763. EXPECT_EQ(total_received, DATA_SIZE)
  8764. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8765. << " bytes (larger than " << DATA_SIZE
  8766. << " bytes response), content_receiver should read all data, but only "
  8767. "read "
  8768. << total_received << " bytes.";
  8769. }
  8770. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8771. // Regression test for "zip bomb" attack on the client side: a malicious server
  8772. // sends a small gzip-compressed response that decompresses to a huge payload.
  8773. // The client must enforce payload_max_length on the decompressed size.
  8774. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8775. constexpr size_t DECOMPRESSED_SIZE =
  8776. 10 * 1024 * 1024; // 10MB after decompression
  8777. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8778. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8779. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8780. std::string compressed;
  8781. {
  8782. httplib::detail::gzip_compressor compressor;
  8783. bool ok =
  8784. compressor.compress(uncompressed.data(), uncompressed.size(),
  8785. /*last=*/true, [&](const char *buf, size_t len) {
  8786. compressed.append(buf, len);
  8787. return true;
  8788. });
  8789. ASSERT_TRUE(ok);
  8790. }
  8791. // Sanity: compressed data should be much smaller than the decompressed size
  8792. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8793. #ifndef _WIN32
  8794. signal(SIGPIPE, SIG_IGN);
  8795. #endif
  8796. // Set up the listening socket in the main thread so the server is guaranteed
  8797. // to be ready before the client connects (eliminates race condition).
  8798. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8799. default_socket_options(srv);
  8800. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8801. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8802. sockaddr_in addr{};
  8803. addr.sin_family = AF_INET;
  8804. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8805. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8806. int opt = 1;
  8807. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8808. #ifdef _WIN32
  8809. reinterpret_cast<const char *>(&opt),
  8810. #else
  8811. &opt,
  8812. #endif
  8813. sizeof(opt));
  8814. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8815. ASSERT_EQ(0, ::listen(srv, 1));
  8816. auto server_thread = std::thread([&compressed, srv] {
  8817. sockaddr_in cli_addr{};
  8818. socklen_t cli_len = sizeof(cli_addr);
  8819. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8820. if (cli != INVALID_SOCKET) {
  8821. // Read the full HTTP request (until \r\n\r\n)
  8822. char buf[4096];
  8823. size_t total = 0;
  8824. while (total < sizeof(buf)) {
  8825. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8826. if (n <= 0) break;
  8827. total += static_cast<size_t>(n);
  8828. // Check for end of headers
  8829. if (total >= 4) {
  8830. std::string req(buf, total);
  8831. if (req.find("\r\n\r\n") != std::string::npos) break;
  8832. }
  8833. }
  8834. // Malicious response: gzip-compressed body, no Content-Length
  8835. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8836. "Content-Encoding: gzip\r\n"
  8837. "Connection: close\r\n"
  8838. "\r\n";
  8839. ::send(cli,
  8840. #ifdef _WIN32
  8841. static_cast<const char *>(response_header.c_str()),
  8842. static_cast<int>(response_header.size()),
  8843. #else
  8844. response_header.c_str(), response_header.size(),
  8845. #endif
  8846. 0);
  8847. // Send the compressed payload (small on the wire, huge when decompressed)
  8848. size_t total_sent = 0;
  8849. while (total_sent < compressed.size()) {
  8850. auto to_send = std::min(compressed.size() - total_sent,
  8851. static_cast<size_t>(64 * 1024));
  8852. auto sent =
  8853. ::send(cli,
  8854. #ifdef _WIN32
  8855. static_cast<const char *>(compressed.c_str() + total_sent),
  8856. static_cast<int>(to_send),
  8857. #else
  8858. compressed.c_str() + total_sent, to_send,
  8859. #endif
  8860. 0);
  8861. if (sent <= 0) break;
  8862. total_sent += static_cast<size_t>(sent);
  8863. }
  8864. detail::close_socket(cli);
  8865. }
  8866. });
  8867. auto se = detail::scope_exit([&] {
  8868. detail::close_socket(srv);
  8869. server_thread.join();
  8870. });
  8871. size_t total_decompressed = 0;
  8872. {
  8873. Client cli("127.0.0.1", PORT + 3);
  8874. cli.set_read_timeout(5, 0);
  8875. cli.set_decompress(true);
  8876. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8877. auto stream = cli.open_stream("GET", "/zipbomb");
  8878. ASSERT_TRUE(stream.is_valid());
  8879. char buffer[64 * 1024];
  8880. ssize_t n;
  8881. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8882. total_decompressed += static_cast<size_t>(n);
  8883. }
  8884. }
  8885. // The decompressed size must be capped by payload_max_length. Without
  8886. // protection, the client would decompress the full 10MB from a tiny
  8887. // compressed payload, enabling a zip bomb DoS attack.
  8888. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8889. << "Client decompressed " << total_decompressed
  8890. << " bytes from a gzip response. The decompressed size should be "
  8891. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8892. }
  8893. #endif
  8894. TEST(HostAndPortPropertiesTest, NoSSL) {
  8895. httplib::Client cli("www.google.com", 1234);
  8896. ASSERT_EQ("www.google.com", cli.host());
  8897. ASSERT_EQ(1234, cli.port());
  8898. }
  8899. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8900. httplib::Client cli("www.google.com:1234");
  8901. ASSERT_EQ("www.google.com", cli.host());
  8902. ASSERT_EQ(1234, cli.port());
  8903. }
  8904. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8905. // Port number that overflows int — should not crash, client becomes invalid
  8906. httplib::Client cli("http://www.google.com:99999999999999999999");
  8907. ASSERT_FALSE(cli.is_valid());
  8908. }
  8909. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8910. // Port 99999 exceeds valid range (1-65535) — should not crash
  8911. httplib::Client cli("http://www.google.com:99999");
  8912. ASSERT_FALSE(cli.is_valid());
  8913. }
  8914. #ifdef CPPHTTPLIB_SSL_ENABLED
  8915. TEST(HostAndPortPropertiesTest, SSL) {
  8916. httplib::SSLClient cli("www.google.com");
  8917. ASSERT_EQ("www.google.com", cli.host());
  8918. ASSERT_EQ(443, cli.port());
  8919. }
  8920. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8921. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8922. std::string cert;
  8923. read_file(CA_CERT_FILE, cert);
  8924. httplib::SSLClient httplib_client("www.google.com");
  8925. // Load CA store first time
  8926. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8927. // Load CA store second time (update)
  8928. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8929. // Verify client is still valid and can make connections
  8930. httplib_client.enable_server_certificate_verification(true);
  8931. auto res = httplib_client.Get("/");
  8932. ASSERT_TRUE(res);
  8933. // Google may return 200 or 301 depending on various factors
  8934. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8935. res->status == StatusCode::MovedPermanently_301);
  8936. }
  8937. TEST(SSLClientTest, ServerNameIndication_Online) {
  8938. auto host = "httpbingo.org";
  8939. auto path = std::string{"/get"};
  8940. SSLClient cli(host, 443);
  8941. auto res = cli.Get(path);
  8942. ASSERT_TRUE(res);
  8943. ASSERT_EQ(StatusCode::OK_200, res->status);
  8944. }
  8945. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8946. // Use a site that will cause SSL verification failure due to self-signed cert
  8947. SSLClient cli("self-signed.badssl.com", 443);
  8948. cli.enable_server_certificate_verification(true);
  8949. auto res = cli.Get("/");
  8950. ASSERT_TRUE(!res);
  8951. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8952. // Verify backend error is captured for SSLServerVerification
  8953. // This occurs when certificate verification fails
  8954. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8955. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8956. EXPECT_NE(0UL, res.ssl_backend_error());
  8957. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8958. // For OpenSSL, ssl_error is 0 for verification errors
  8959. EXPECT_EQ(0, res.ssl_error());
  8960. #if !defined(_WIN32) || \
  8961. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8962. // On non-Windows or when Windows Schannel is disabled, the error comes
  8963. // from OpenSSL's verification
  8964. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8965. res.ssl_backend_error());
  8966. #endif
  8967. #endif
  8968. }
  8969. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8970. // Use a site where hostname doesn't match the certificate
  8971. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8972. SSLClient cli("wrong.host.badssl.com", 443);
  8973. cli.enable_server_certificate_verification(true);
  8974. cli.enable_server_hostname_verification(true);
  8975. auto res = cli.Get("/");
  8976. ASSERT_TRUE(!res);
  8977. // The error type depends on when hostname verification occurs:
  8978. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8979. // - Mbed TLS: SSLServerVerification (during handshake)
  8980. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8981. res.error() == Error::SSLServerVerification);
  8982. // Verify backend error is captured for hostname verification failure
  8983. EXPECT_NE(0UL, res.ssl_backend_error());
  8984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8985. // For OpenSSL, ssl_error is 0 for verification errors
  8986. EXPECT_EQ(0, res.ssl_error());
  8987. #if !defined(_WIN32) || \
  8988. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8989. // On non-Windows or when Windows Schannel is disabled, the error comes
  8990. // from OpenSSL's hostname verification
  8991. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8992. res.ssl_backend_error());
  8993. #endif
  8994. #endif
  8995. }
  8996. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8997. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8998. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8999. SSLClient cli("www.google.com", 443);
  9000. cli.enable_server_certificate_verification(true);
  9001. auto res = cli.Get("/");
  9002. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9003. }
  9004. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9005. SSLClient cli("www.google.com", 443);
  9006. cli.enable_server_certificate_verification(true);
  9007. cli.enable_windows_certificate_verification(false);
  9008. auto res = cli.Get("/");
  9009. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9010. }
  9011. #endif
  9012. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9013. Client cli("https://google.com");
  9014. auto res = cli.Get("/");
  9015. ASSERT_TRUE(res);
  9016. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9017. }
  9018. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9019. SSLClient cli("google.com");
  9020. cli.set_ca_cert_path(CA_CERT_FILE);
  9021. auto res = cli.Get("/");
  9022. ASSERT_TRUE(res);
  9023. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9024. }
  9025. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9026. SSLClient cli("google.com");
  9027. cli.enable_server_certificate_verification(true);
  9028. cli.set_ca_cert_path("hello");
  9029. auto res = cli.Get("/");
  9030. ASSERT_TRUE(!res);
  9031. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9032. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9033. // should be set
  9034. EXPECT_EQ(0, res.ssl_error());
  9035. // Verify backend error is captured for SSLLoadingCerts
  9036. // This error occurs when loading CA certificates fails
  9037. EXPECT_NE(0UL, res.ssl_backend_error());
  9038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9039. // OpenSSL specific error codes:
  9040. // > openssl errstr 0x80000002
  9041. // error:80000002:system library::No such file or directory
  9042. // > openssl errstr 0xA000126
  9043. // error:0A000126:SSL routines::unexpected eof while reading
  9044. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9045. res.ssl_backend_error() == 0xA000126);
  9046. #endif
  9047. }
  9048. TEST(SSLClientTest, ServerCertificateVerification4) {
  9049. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9050. ASSERT_TRUE(svr.is_valid());
  9051. svr.Get("/test", [&](const Request &, Response &res) {
  9052. res.set_content("test", "text/plain");
  9053. svr.stop();
  9054. ASSERT_TRUE(true);
  9055. });
  9056. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9057. auto se = detail::scope_exit([&] {
  9058. t.join();
  9059. ASSERT_FALSE(svr.is_running());
  9060. });
  9061. svr.wait_until_ready();
  9062. SSLClient cli("127.0.0.1", PORT);
  9063. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9064. cli.enable_server_certificate_verification(true);
  9065. cli.set_connection_timeout(30);
  9066. auto res = cli.Get("/test");
  9067. ASSERT_TRUE(res);
  9068. ASSERT_EQ(StatusCode::OK_200, res->status);
  9069. }
  9070. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9071. std::string cert;
  9072. read_file(CA_CERT_FILE, cert);
  9073. SSLClient cli("google.com");
  9074. cli.load_ca_cert_store(cert.data(), cert.size());
  9075. const auto res = cli.Get("/");
  9076. ASSERT_TRUE(res);
  9077. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9078. }
  9079. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9080. // clang-format off
  9081. static constexpr char cert[] =
  9082. "GlobalSign Root CA\n"
  9083. "==================\n"
  9084. "-----BEGIN CERTIFICATE-----\n"
  9085. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9086. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9087. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9088. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9089. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9090. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9091. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9092. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9093. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9094. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9095. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9096. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9097. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9098. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9099. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9100. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9101. "-----END CERTIFICATE-----\n";
  9102. // clang-format on
  9103. SSLClient cli("google.com");
  9104. cli.load_ca_cert_store(cert, sizeof(cert));
  9105. const auto res = cli.Get("/");
  9106. ASSERT_TRUE(res);
  9107. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9108. }
  9109. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9110. SSLClient cli("www.youtube.com");
  9111. cli.set_ca_cert_path(CA_CERT_FILE);
  9112. cli.enable_server_certificate_verification(true);
  9113. cli.set_follow_location(true);
  9114. auto res = cli.Get("/");
  9115. ASSERT_TRUE(res);
  9116. ASSERT_EQ(StatusCode::OK_200, res->status);
  9117. }
  9118. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9119. SSLClient cli("wWw.YouTube.Com");
  9120. cli.set_ca_cert_path(CA_CERT_FILE);
  9121. cli.enable_server_certificate_verification(true);
  9122. cli.enable_server_hostname_verification(true);
  9123. cli.set_follow_location(true);
  9124. auto res = cli.Get("/");
  9125. ASSERT_TRUE(res);
  9126. ASSERT_EQ(StatusCode::OK_200, res->status);
  9127. }
  9128. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9129. SSLClient cli("gOoGlE.COm");
  9130. cli.enable_server_certificate_verification(true);
  9131. cli.enable_server_hostname_verification(true);
  9132. cli.set_follow_location(true);
  9133. auto res = cli.Get("/");
  9134. ASSERT_TRUE(res);
  9135. ASSERT_EQ(StatusCode::OK_200, res->status);
  9136. }
  9137. TEST(SSLClientTest, Issue2004_Online) {
  9138. Client client("https://google.com");
  9139. client.set_follow_location(true);
  9140. auto res = client.Get("/");
  9141. ASSERT_TRUE(res);
  9142. ASSERT_EQ(StatusCode::OK_200, res->status);
  9143. auto body = res->body;
  9144. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9145. }
  9146. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9147. // Create SSLClient with invalid cert/key to make is_valid() return false
  9148. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9149. "nonexistent_key.pem");
  9150. // is_valid() should be false due to cert loading failure
  9151. ASSERT_FALSE(cli.is_valid());
  9152. auto res = cli.Get("/");
  9153. ASSERT_FALSE(res);
  9154. EXPECT_EQ(Error::SSLConnection, res.error());
  9155. }
  9156. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9157. // Test for Issue #2251: SSL error not properly reported when client cert
  9158. // and key paths are swapped or mismatched
  9159. // This simulates the scenario where user accidentally swaps the cert and key
  9160. // files
  9161. // Using client cert file as private key and vice versa (completely wrong)
  9162. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9163. // Should fail validation due to cert/key mismatch
  9164. ASSERT_FALSE(cli.is_valid());
  9165. // Attempt to make a request should fail with proper error
  9166. auto res = cli.Get("/");
  9167. ASSERT_FALSE(res);
  9168. EXPECT_EQ(Error::SSLConnection, res.error());
  9169. // SSL error should be recorded in the Result object (this is the key fix for
  9170. // Issue #2251)
  9171. auto backend_error = res.ssl_backend_error();
  9172. EXPECT_NE(0u, backend_error);
  9173. }
  9174. // Tests cert/key mismatch detection at the TLS context level
  9175. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9176. // Test that using mismatched cert/key causes connection failure.
  9177. // We verify this at the SSLClient level rather than through internal
  9178. // TLS API functions.
  9179. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9180. cli.enable_server_certificate_verification(false);
  9181. cli.set_connection_timeout(2);
  9182. // The mismatch should cause a connection or handshake error
  9183. auto res = cli.Get("/test");
  9184. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9185. // Either way, the request should fail
  9186. EXPECT_FALSE(res);
  9187. }
  9188. #endif
  9189. #if 0
  9190. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9191. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9192. ASSERT_TRUE(cli != nullptr);
  9193. cli->set_address_family(AF_INET6);
  9194. cli->set_interface("en0");
  9195. auto res = cli->Get("/get");
  9196. ASSERT_TRUE(res);
  9197. ASSERT_EQ(StatusCode::OK_200, res->status);
  9198. }
  9199. #endif
  9200. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9201. #ifdef CPPHTTPLIB_SSL_ENABLED
  9202. void ClientCertPresent(
  9203. const std::string &client_cert_file,
  9204. const std::string &client_private_key_file,
  9205. const std::string &client_encrypted_private_key_pass = std::string()) {
  9206. using namespace httplib::tls;
  9207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9208. CLIENT_CA_CERT_DIR);
  9209. ASSERT_TRUE(svr.is_valid());
  9210. svr.Get("/test", [&](const Request &req, Response &res) {
  9211. res.set_content("test", "text/plain");
  9212. auto cert = req.peer_cert();
  9213. ASSERT_TRUE(static_cast<bool>(cert));
  9214. std::string common_name = cert.subject_cn();
  9215. EXPECT_EQ("Common Name", common_name);
  9216. });
  9217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9218. auto se = detail::scope_exit([&] {
  9219. svr.stop();
  9220. t.join();
  9221. ASSERT_FALSE(svr.is_running());
  9222. });
  9223. svr.wait_until_ready();
  9224. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9225. client_encrypted_private_key_pass);
  9226. cli.enable_server_certificate_verification(false);
  9227. cli.set_connection_timeout(30);
  9228. auto res = cli.Get("/test");
  9229. ASSERT_TRUE(res);
  9230. ASSERT_EQ(StatusCode::OK_200, res->status);
  9231. }
  9232. TEST(SSLClientServerTest, ClientCertPresent) {
  9233. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9234. }
  9235. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9236. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9237. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9238. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9239. }
  9240. // PEM memory-based constructor tests (works with all TLS backends)
  9241. void PemMemoryClientCertPresent(
  9242. const std::string &client_cert_file,
  9243. const std::string &client_private_key_file,
  9244. const std::string &client_encrypted_private_key_pass = std::string()) {
  9245. // Read PEM files into memory
  9246. std::string server_cert_pem, server_key_pem;
  9247. std::string client_ca_pem;
  9248. std::string client_cert_pem, client_key_pem;
  9249. read_file(SERVER_CERT_FILE, server_cert_pem);
  9250. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9251. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9252. read_file(client_cert_file, client_cert_pem);
  9253. read_file(client_private_key_file, client_key_pem);
  9254. // Create server with PEM memory
  9255. SSLServer::PemMemory server_pem = {
  9256. server_cert_pem.c_str(),
  9257. server_cert_pem.size(),
  9258. server_key_pem.c_str(),
  9259. server_key_pem.size(),
  9260. client_ca_pem.c_str(),
  9261. client_ca_pem.size(),
  9262. nullptr // no password for server key
  9263. };
  9264. SSLServer svr(server_pem);
  9265. ASSERT_TRUE(svr.is_valid());
  9266. svr.Get("/test", [&](const Request &, Response &res) {
  9267. res.set_content("test", "text/plain");
  9268. });
  9269. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9270. auto se = detail::scope_exit([&] {
  9271. svr.stop();
  9272. t.join();
  9273. ASSERT_FALSE(svr.is_running());
  9274. });
  9275. svr.wait_until_ready();
  9276. // Create client with PEM memory
  9277. const char *password = client_encrypted_private_key_pass.empty()
  9278. ? nullptr
  9279. : client_encrypted_private_key_pass.c_str();
  9280. SSLClient::PemMemory client_pem = {
  9281. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9282. client_key_pem.size(), password};
  9283. SSLClient cli(HOST, PORT, client_pem);
  9284. cli.enable_server_certificate_verification(false);
  9285. cli.set_connection_timeout(30);
  9286. auto res = cli.Get("/test");
  9287. ASSERT_TRUE(res);
  9288. ASSERT_EQ(StatusCode::OK_200, res->status);
  9289. }
  9290. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9291. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9292. }
  9293. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9294. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9295. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9296. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9297. }
  9298. TEST(SSLClientServerTest, ClientCertMissing) {
  9299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9300. CLIENT_CA_CERT_DIR);
  9301. ASSERT_TRUE(svr.is_valid());
  9302. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9303. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9304. auto se = detail::scope_exit([&] {
  9305. svr.stop();
  9306. t.join();
  9307. ASSERT_FALSE(svr.is_running());
  9308. });
  9309. svr.wait_until_ready();
  9310. SSLClient cli(HOST, PORT);
  9311. cli.set_connection_timeout(30);
  9312. auto res = cli.Get("/test");
  9313. ASSERT_TRUE(!res);
  9314. // When client cert is missing and server requires it, connection fails
  9315. // Error type depends on backend implementation
  9316. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9317. res.error() == Error::SSLConnection);
  9318. // Verify backend error is captured
  9319. // Note: This test may have different error codes depending on the exact
  9320. // verification failure
  9321. EXPECT_NE(0UL, res.ssl_backend_error());
  9322. }
  9323. TEST(SSLClientServerTest, TrustDirOptional) {
  9324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9325. ASSERT_TRUE(svr.is_valid());
  9326. svr.Get("/test", [&](const Request &, Response &res) {
  9327. res.set_content("test", "text/plain");
  9328. });
  9329. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9330. auto se = detail::scope_exit([&] {
  9331. svr.stop();
  9332. t.join();
  9333. ASSERT_FALSE(svr.is_running());
  9334. });
  9335. svr.wait_until_ready();
  9336. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9337. cli.enable_server_certificate_verification(false);
  9338. cli.set_connection_timeout(30);
  9339. auto res = cli.Get("/test");
  9340. ASSERT_TRUE(res);
  9341. ASSERT_EQ(StatusCode::OK_200, res->status);
  9342. }
  9343. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9344. class NoListenSSLServer : public SSLServer {
  9345. public:
  9346. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9347. const char *client_ca_cert_file_path,
  9348. const char *client_ca_cert_dir_path = nullptr)
  9349. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9350. client_ca_cert_dir_path),
  9351. stop_(false) {}
  9352. std::atomic_bool stop_;
  9353. private:
  9354. bool process_and_close_socket(socket_t /*sock*/) override {
  9355. // Don't create SSL context
  9356. while (!stop_.load()) {
  9357. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9358. }
  9359. return true;
  9360. }
  9361. };
  9362. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9363. CLIENT_CA_CERT_FILE);
  9364. ASSERT_TRUE(svr.is_valid());
  9365. svr.Get("/test", [&](const Request &, Response &res) {
  9366. res.set_content("test", "text/plain");
  9367. });
  9368. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9369. auto se = detail::scope_exit([&] {
  9370. svr.stop_ = true;
  9371. svr.stop();
  9372. t.join();
  9373. ASSERT_FALSE(svr.is_running());
  9374. });
  9375. svr.wait_until_ready();
  9376. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9377. cli.enable_server_certificate_verification(false);
  9378. cli.set_connection_timeout(1);
  9379. auto res = cli.Get("/test");
  9380. ASSERT_TRUE(!res);
  9381. EXPECT_EQ(Error::SSLConnection, res.error());
  9382. // Timeout results in WantRead error code (maps to backend-specific value)
  9383. EXPECT_NE(0, res.ssl_error());
  9384. }
  9385. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9386. // Test SSLServer with client certificate verification using the standard
  9387. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9389. CLIENT_CA_CERT_DIR);
  9390. ASSERT_TRUE(svr.is_valid());
  9391. svr.Get("/test", [&](const Request &req, Response &res) {
  9392. res.set_content("test", "text/plain");
  9393. auto cert = req.peer_cert();
  9394. ASSERT_TRUE(static_cast<bool>(cert));
  9395. auto common_name = cert.subject_cn();
  9396. EXPECT_EQ("Common Name", common_name);
  9397. });
  9398. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9399. auto se = detail::scope_exit([&] {
  9400. svr.stop();
  9401. t.join();
  9402. ASSERT_FALSE(svr.is_running());
  9403. });
  9404. svr.wait_until_ready();
  9405. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9406. cli.enable_server_certificate_verification(false);
  9407. cli.set_connection_timeout(30);
  9408. auto res = cli.Get("/test");
  9409. ASSERT_TRUE(res);
  9410. ASSERT_EQ(StatusCode::OK_200, res->status);
  9411. }
  9412. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9413. // Verifies that wildcard matching and exact matching work consistently
  9414. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9415. using namespace httplib::tls;
  9416. // We need a running server to test against
  9417. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9418. ASSERT_TRUE(svr.is_valid());
  9419. svr.Get("/test", [](const Request &, Response &res) {
  9420. res.set_content("ok", "text/plain");
  9421. });
  9422. thread t([&]() { svr.listen(HOST, PORT); });
  9423. auto se = detail::scope_exit([&] {
  9424. svr.stop();
  9425. t.join();
  9426. });
  9427. svr.wait_until_ready();
  9428. bool verify_callback_called = false;
  9429. bool verify_result_wrong = false;
  9430. SSLClient cli(HOST, PORT);
  9431. cli.enable_server_certificate_verification(true);
  9432. cli.set_ca_cert_path(CA_CERT_FILE);
  9433. cli.set_connection_timeout(5);
  9434. // Note: Test certificate has CN="Common Name", not "localhost"
  9435. bool verify_result_cn = false;
  9436. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9437. verify_callback_called = true;
  9438. if (!ctx.cert) return false;
  9439. // Test 1: "Common Name" should match (our test server cert CN)
  9440. verify_result_cn = ctx.check_hostname("Common Name");
  9441. // Test 2: wrong hostname should not match
  9442. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9443. return true; // Accept for the purpose of this test
  9444. });
  9445. auto res = cli.Get("/test");
  9446. // The request may succeed or fail depending on cert configuration
  9447. // but the callback should have been called
  9448. ASSERT_TRUE(verify_callback_called)
  9449. << "Verify callback should have been called";
  9450. // CN="Common Name" should match our test certificate
  9451. //
  9452. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9453. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9454. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9455. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9456. // <openssl/base.h>, which is included transitively when
  9457. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9458. #if defined(OPENSSL_IS_BORINGSSL)
  9459. EXPECT_FALSE(verify_result_cn)
  9460. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9461. #else
  9462. EXPECT_TRUE(verify_result_cn)
  9463. << "verify_hostname should match 'Common Name' (certificate CN)";
  9464. #endif
  9465. // Wrong hostname should not match
  9466. EXPECT_FALSE(verify_result_wrong)
  9467. << "verify_hostname should not match 'wronghost.example.com'";
  9468. }
  9469. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9470. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9471. // X509_check_ip behavior and must hold for every backend.
  9472. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9473. using namespace httplib::tls;
  9474. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9475. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9476. ASSERT_TRUE(svr.is_valid());
  9477. svr.Get("/test", [](const Request &, Response &res) {
  9478. res.set_content("ok", "text/plain");
  9479. });
  9480. thread t([&]() { svr.listen(HOST, PORT); });
  9481. auto se = detail::scope_exit([&] {
  9482. svr.stop();
  9483. t.join();
  9484. });
  9485. svr.wait_until_ready();
  9486. bool verify_callback_called = false;
  9487. bool ip_matched_via_cn = true;
  9488. SSLClient cli(HOST, PORT);
  9489. cli.enable_server_certificate_verification(true);
  9490. cli.set_ca_cert_path(CA_CERT_FILE);
  9491. cli.set_connection_timeout(5);
  9492. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9493. verify_callback_called = true;
  9494. if (!ctx.cert) return false;
  9495. // The IP appears only in the CN, so it must NOT be accepted.
  9496. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9497. return true; // Accept for the purpose of this test
  9498. });
  9499. cli.Get("/test");
  9500. ASSERT_TRUE(verify_callback_called)
  9501. << "Verify callback should have been called";
  9502. EXPECT_FALSE(ip_matched_via_cn)
  9503. << "An IP host must not be authenticated via the certificate CN";
  9504. }
  9505. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9506. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9507. using namespace httplib::tls;
  9508. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9509. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9510. ASSERT_TRUE(svr.is_valid());
  9511. svr.Get("/test", [](const Request &, Response &res) {
  9512. res.set_content("ok", "text/plain");
  9513. });
  9514. thread t([&]() { svr.listen(HOST, PORT); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. t.join();
  9518. });
  9519. svr.wait_until_ready();
  9520. bool verify_callback_called = false;
  9521. bool san_matched = false;
  9522. bool wrong_ipv6_matched = true;
  9523. bool cn_ipv6_matched = true;
  9524. SSLClient cli(HOST, PORT);
  9525. cli.enable_server_certificate_verification(true);
  9526. cli.set_ca_cert_path(CA_CERT_FILE);
  9527. cli.set_connection_timeout(5);
  9528. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9529. verify_callback_called = true;
  9530. if (!ctx.cert) return false;
  9531. // Matches the IPv6 iPAddress SAN.
  9532. san_matched = ctx.check_hostname("2001:db8::1");
  9533. // A different IPv6 address must not match.
  9534. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9535. // "::1" lives only in the CN, so it must not be accepted.
  9536. cn_ipv6_matched = ctx.check_hostname("::1");
  9537. return true; // Accept for the purpose of this test
  9538. });
  9539. cli.Get("/test");
  9540. ASSERT_TRUE(verify_callback_called)
  9541. << "Verify callback should have been called";
  9542. EXPECT_TRUE(san_matched)
  9543. << "verify_hostname should match an IPv6 iPAddress SAN";
  9544. EXPECT_FALSE(wrong_ipv6_matched)
  9545. << "verify_hostname should not match a non-matching IPv6 address";
  9546. EXPECT_FALSE(cn_ipv6_matched)
  9547. << "An IPv6 host must not be authenticated via the certificate CN";
  9548. }
  9549. #endif
  9550. // mbedTLS-specific callback constructor test
  9551. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9552. #ifdef CPPHTTPLIB_SSL_ENABLED
  9553. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9555. ASSERT_TRUE(svr.is_valid());
  9556. // Set up a handler to verify client certificate is present
  9557. bool client_cert_verified = false;
  9558. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9559. // Verify that client certificate was provided
  9560. client_cert_verified = true;
  9561. res.set_content("success", "text/plain");
  9562. });
  9563. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9564. auto se = detail::scope_exit([&] {
  9565. svr.stop();
  9566. t.join();
  9567. ASSERT_FALSE(svr.is_running());
  9568. });
  9569. svr.wait_until_ready();
  9570. // Client with certificate
  9571. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9572. cli.enable_server_certificate_verification(false);
  9573. cli.set_connection_timeout(30);
  9574. auto res = cli.Get("/test");
  9575. ASSERT_TRUE(res);
  9576. ASSERT_EQ(StatusCode::OK_200, res->status);
  9577. ASSERT_TRUE(client_cert_verified);
  9578. EXPECT_EQ("success", res->body);
  9579. }
  9580. #endif
  9581. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9582. // backends
  9583. #ifdef CPPHTTPLIB_SSL_ENABLED
  9584. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9585. using namespace httplib::tls;
  9586. // Test that when client CA cert file is provided,
  9587. // the server properly requests and validates client certificates
  9588. // Create a server with client authentication
  9589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9590. ASSERT_TRUE(svr.is_valid());
  9591. bool handler_called = false;
  9592. svr.Get("/test", [&](const Request &req, Response &res) {
  9593. handler_called = true;
  9594. // Verify that a client certificate was provided
  9595. auto cert = req.peer_cert();
  9596. ASSERT_TRUE(static_cast<bool>(cert));
  9597. // Get the issuer name
  9598. std::string issuer_str = cert.issuer_name();
  9599. ASSERT_FALSE(issuer_str.empty());
  9600. // The client certificate should be issued by our test CA
  9601. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9602. res.set_content("authenticated", "text/plain");
  9603. });
  9604. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9605. auto se = detail::scope_exit([&] {
  9606. svr.stop();
  9607. t.join();
  9608. ASSERT_FALSE(svr.is_running());
  9609. });
  9610. svr.wait_until_ready();
  9611. // Connect with a client certificate issued by the CA
  9612. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9613. cli.enable_server_certificate_verification(false);
  9614. cli.set_connection_timeout(30);
  9615. auto res = cli.Get("/test");
  9616. ASSERT_TRUE(res);
  9617. ASSERT_EQ(StatusCode::OK_200, res->status);
  9618. ASSERT_TRUE(handler_called);
  9619. EXPECT_EQ("authenticated", res->body);
  9620. }
  9621. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9622. using namespace httplib::tls;
  9623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9624. ASSERT_TRUE(svr.is_valid());
  9625. svr.Get("/test", [](const Request &, Response &res) {
  9626. res.set_content("ok", "text/plain");
  9627. });
  9628. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9629. auto se = detail::scope_exit([&] {
  9630. svr.stop();
  9631. t.join();
  9632. });
  9633. svr.wait_until_ready();
  9634. SSLClient cli(HOST, PORT);
  9635. cli.enable_server_certificate_verification(false);
  9636. cli.set_connection_timeout(30);
  9637. bool cert_checked = false;
  9638. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9639. if (ctx.cert) {
  9640. auto sans = ctx.sans();
  9641. // Test certificate may or may not have SANs - just verify the API
  9642. // works If SANs exist, verify the types are valid
  9643. for (const auto &san : sans) {
  9644. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9645. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9646. san.type == SanType::OTHER);
  9647. EXPECT_FALSE(san.value.empty());
  9648. }
  9649. cert_checked = true;
  9650. }
  9651. return true;
  9652. });
  9653. auto res = cli.Get("/test");
  9654. ASSERT_TRUE(res);
  9655. EXPECT_TRUE(cert_checked);
  9656. }
  9657. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9658. using namespace httplib::tls;
  9659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9660. ASSERT_TRUE(svr.is_valid());
  9661. svr.Get("/test", [](const Request &, Response &res) {
  9662. res.set_content("ok", "text/plain");
  9663. });
  9664. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9665. auto se = detail::scope_exit([&] {
  9666. svr.stop();
  9667. t.join();
  9668. });
  9669. svr.wait_until_ready();
  9670. SSLClient cli(HOST, PORT);
  9671. cli.enable_server_certificate_verification(false);
  9672. cli.set_connection_timeout(30);
  9673. bool validity_checked = false;
  9674. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9675. if (ctx.cert) {
  9676. time_t not_before = 0, not_after = 0;
  9677. bool result = ctx.validity(not_before, not_after);
  9678. EXPECT_TRUE(result);
  9679. // Verify that not_before < now < not_after for a valid cert
  9680. time_t now = time(nullptr);
  9681. EXPECT_LT(not_before, now);
  9682. EXPECT_GT(not_after, now);
  9683. validity_checked = true;
  9684. }
  9685. return true;
  9686. });
  9687. auto res = cli.Get("/test");
  9688. ASSERT_TRUE(res);
  9689. EXPECT_TRUE(validity_checked);
  9690. }
  9691. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9692. using namespace httplib::tls;
  9693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9694. ASSERT_TRUE(svr.is_valid());
  9695. svr.Get("/test", [](const Request &, Response &res) {
  9696. res.set_content("ok", "text/plain");
  9697. });
  9698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9699. auto se = detail::scope_exit([&] {
  9700. svr.stop();
  9701. t.join();
  9702. });
  9703. svr.wait_until_ready();
  9704. SSLClient cli(HOST, PORT);
  9705. cli.enable_server_certificate_verification(false);
  9706. cli.set_connection_timeout(30);
  9707. bool serial_checked = false;
  9708. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9709. if (ctx.cert) {
  9710. std::string serial = ctx.serial();
  9711. EXPECT_FALSE(serial.empty());
  9712. // Serial should be a hex string
  9713. for (char c : serial) {
  9714. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9715. (c >= 'a' && c <= 'f'));
  9716. }
  9717. serial_checked = true;
  9718. }
  9719. return true;
  9720. });
  9721. auto res = cli.Get("/test");
  9722. ASSERT_TRUE(res);
  9723. EXPECT_TRUE(serial_checked);
  9724. }
  9725. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9726. // Test 1: Valid CA file - no error should be recorded
  9727. {
  9728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9729. CLIENT_CA_CERT_FILE);
  9730. ASSERT_TRUE(svr.is_valid());
  9731. // With valid setup, last_ssl_error should be 0
  9732. EXPECT_EQ(0, svr.ssl_last_error());
  9733. }
  9734. // Test 2: Invalid CA file content
  9735. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9736. {
  9737. // Create a temporary file with completely invalid content
  9738. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9739. {
  9740. std::ofstream ofs(temp_invalid_ca);
  9741. ofs << "This is not a certificate file at all\n";
  9742. ofs << "Just plain text content\n";
  9743. }
  9744. // Create server with invalid CA file
  9745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9746. // Clean up temporary file
  9747. std::remove(temp_invalid_ca);
  9748. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9749. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9750. // Note: SSL_CTX_load_verify_locations typically fails first,
  9751. // but our error handling code path is still exercised
  9752. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9753. }
  9754. }
  9755. TEST(VerifyCallbackTest, VerifyContextFields) {
  9756. using namespace httplib::tls;
  9757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9758. ASSERT_TRUE(svr.is_valid());
  9759. svr.Get("/test", [](const Request &, Response &res) {
  9760. res.set_content("ok", "text/plain");
  9761. });
  9762. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9763. auto se = detail::scope_exit([&] {
  9764. svr.stop();
  9765. t.join();
  9766. });
  9767. svr.wait_until_ready();
  9768. SSLClient cli(HOST, PORT);
  9769. cli.enable_server_certificate_verification(false);
  9770. cli.set_connection_timeout(30);
  9771. int callback_count = 0;
  9772. bool saw_leaf_cert = false;
  9773. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9774. if (ctx.cert) {
  9775. callback_count++;
  9776. // We should see at least one certificate (the leaf)
  9777. std::string cn = ctx.subject_cn();
  9778. if (!cn.empty()) { saw_leaf_cert = true; }
  9779. // Verify context fields are populated
  9780. EXPECT_NE(ctx.session, nullptr);
  9781. EXPECT_GE(ctx.depth, 0);
  9782. }
  9783. return true;
  9784. });
  9785. auto res = cli.Get("/test");
  9786. ASSERT_TRUE(res);
  9787. EXPECT_GT(callback_count, 0);
  9788. EXPECT_TRUE(saw_leaf_cert);
  9789. }
  9790. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9791. using httplib::tls::TlsError;
  9792. // Test that verify_error_to_string returns empty for success
  9793. std::string success_str = TlsError::verify_error_to_string(0);
  9794. EXPECT_TRUE(success_str.empty());
  9795. // Test that verify_error_to_string returns non-empty for error codes
  9796. // Using a common error code (certificate expired)
  9797. std::string error_str =
  9798. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9799. EXPECT_FALSE(error_str.empty());
  9800. }
  9801. TEST(SessionVerifierTest, CertificateAccepted) {
  9802. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9803. ASSERT_TRUE(svr.is_valid());
  9804. svr.Get("/test", [](const Request &, Response &res) {
  9805. res.set_content("ok", "text/plain");
  9806. });
  9807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9808. auto se = detail::scope_exit([&] {
  9809. svr.stop();
  9810. t.join();
  9811. });
  9812. svr.wait_until_ready();
  9813. SSLClient cli(HOST, PORT);
  9814. cli.enable_server_certificate_verification(false);
  9815. cli.set_connection_timeout(30);
  9816. bool callback_called = false;
  9817. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9818. EXPECT_NE(session, nullptr);
  9819. callback_called = true;
  9820. return SSLVerifierResponse::CertificateAccepted;
  9821. });
  9822. auto res = cli.Get("/test");
  9823. ASSERT_TRUE(res);
  9824. EXPECT_EQ(200, res->status);
  9825. EXPECT_TRUE(callback_called);
  9826. }
  9827. TEST(SessionVerifierTest, CertificateRejected) {
  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 callback_called = false;
  9843. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9844. EXPECT_NE(session, nullptr);
  9845. callback_called = true;
  9846. return SSLVerifierResponse::CertificateRejected;
  9847. });
  9848. auto res = cli.Get("/test");
  9849. EXPECT_FALSE(res);
  9850. EXPECT_TRUE(callback_called);
  9851. }
  9852. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9854. ASSERT_TRUE(svr.is_valid());
  9855. svr.Get("/test", [](const Request &, Response &res) {
  9856. res.set_content("ok", "text/plain");
  9857. });
  9858. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9859. auto se = detail::scope_exit([&] {
  9860. svr.stop();
  9861. t.join();
  9862. });
  9863. svr.wait_until_ready();
  9864. // NoDecisionMade with verification disabled should succeed (no default check)
  9865. SSLClient cli(HOST, PORT);
  9866. cli.enable_server_certificate_verification(false);
  9867. cli.set_connection_timeout(30);
  9868. bool callback_called = false;
  9869. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9870. EXPECT_NE(session, nullptr);
  9871. callback_called = true;
  9872. return SSLVerifierResponse::NoDecisionMade;
  9873. });
  9874. auto res = cli.Get("/test");
  9875. ASSERT_TRUE(res);
  9876. EXPECT_EQ(200, res->status);
  9877. EXPECT_TRUE(callback_called);
  9878. }
  9879. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9881. ASSERT_TRUE(svr.is_valid());
  9882. svr.Get("/test", [](const Request &, Response &res) {
  9883. res.set_content("ok", "text/plain");
  9884. });
  9885. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9886. auto se = detail::scope_exit([&] {
  9887. svr.stop();
  9888. t.join();
  9889. });
  9890. svr.wait_until_ready();
  9891. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9892. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9893. // so we only check that the request fails, not whether the callback was
  9894. // called.
  9895. SSLClient cli(HOST, PORT);
  9896. cli.enable_server_certificate_verification(true);
  9897. cli.set_connection_timeout(30);
  9898. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9899. EXPECT_NE(session, nullptr);
  9900. return SSLVerifierResponse::NoDecisionMade;
  9901. });
  9902. auto res = cli.Get("/test");
  9903. EXPECT_FALSE(res);
  9904. }
  9905. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9906. // Test SSL server using PemMemory constructor with client CA certificates
  9907. // Read PEM files
  9908. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9909. read_file(SERVER_CERT_FILE, server_cert_pem);
  9910. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9911. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9912. // Create SSLServer with PemMemory constructor including client CA
  9913. SSLServer::PemMemory server_pem = {
  9914. server_cert_pem.c_str(),
  9915. server_cert_pem.size(),
  9916. server_key_pem.c_str(),
  9917. server_key_pem.size(),
  9918. client_ca_pem.c_str(),
  9919. client_ca_pem.size(),
  9920. nullptr // no password for server key
  9921. };
  9922. SSLServer svr(server_pem);
  9923. ASSERT_TRUE(svr.is_valid());
  9924. // No SSL error should be recorded for valid setup
  9925. EXPECT_EQ(0, svr.ssl_last_error());
  9926. // Set up server endpoints
  9927. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9928. res.set_content("ok", "text/plain");
  9929. });
  9930. // Start server in a thread
  9931. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9932. svr.wait_until_ready();
  9933. // Connect with client certificate (using constructor with paths)
  9934. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9935. cli.enable_server_certificate_verification(false);
  9936. auto res = cli.Get("/test-pem-ca");
  9937. ASSERT_TRUE(res);
  9938. EXPECT_EQ(200, res->status);
  9939. EXPECT_EQ("ok", res->body);
  9940. svr.stop();
  9941. server_thread.join();
  9942. }
  9943. #endif
  9944. #ifdef _WIN32
  9945. TEST(CleanupTest, WSACleanup) {
  9946. int ret = WSACleanup();
  9947. ASSERT_EQ(0, ret);
  9948. }
  9949. #endif
  9950. #ifndef CPPHTTPLIB_SSL_ENABLED
  9951. TEST(NoSSLSupport, SimpleInterface) {
  9952. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9953. }
  9954. #endif
  9955. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9956. TEST(InvalidScheme, SimpleInterface) {
  9957. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9958. }
  9959. #endif
  9960. TEST(NoScheme, SimpleInterface) {
  9961. Client cli("yahoo.com:80");
  9962. ASSERT_TRUE(cli.is_valid());
  9963. }
  9964. TEST(SendAPI, SimpleInterface_Online) {
  9965. Client cli("http://yahoo.com");
  9966. Request req;
  9967. req.method = "GET";
  9968. req.path = "/";
  9969. auto res = cli.send(req);
  9970. ASSERT_TRUE(res);
  9971. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9972. }
  9973. TEST(SendAPI, WithParamsInRequest) {
  9974. Server svr;
  9975. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9976. EXPECT_TRUE(req.has_param("test"));
  9977. EXPECT_EQ("test_value", req.get_param_value("test"));
  9978. });
  9979. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9980. auto se = detail::scope_exit([&] {
  9981. svr.stop();
  9982. t.join();
  9983. ASSERT_FALSE(svr.is_running());
  9984. });
  9985. svr.wait_until_ready();
  9986. Client cli(HOST, PORT);
  9987. {
  9988. Request req;
  9989. req.method = "GET";
  9990. req.path = "/";
  9991. req.params.emplace("test", "test_value");
  9992. auto res = cli.send(req);
  9993. ASSERT_TRUE(res);
  9994. }
  9995. {
  9996. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9997. ASSERT_TRUE(res);
  9998. }
  9999. }
  10000. TEST(ClientImplMethods, GetSocketTest) {
  10001. httplib::Server svr;
  10002. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10003. res.status = StatusCode::OK_200;
  10004. });
  10005. auto port = svr.bind_to_any_port("127.0.0.1");
  10006. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10007. auto se = detail::scope_exit([&] {
  10008. svr.stop();
  10009. thread.join();
  10010. ASSERT_FALSE(svr.is_running());
  10011. });
  10012. svr.wait_until_ready();
  10013. {
  10014. httplib::Client cli("127.0.0.1", port);
  10015. cli.set_keep_alive(true);
  10016. // Use the behavior of cpp-httplib of opening the connection
  10017. // only when the first request happens. If that changes,
  10018. // this test would be obsolete.
  10019. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10020. // This also implicitly tests the server. But other tests would fail much
  10021. // earlier than this one to be considered.
  10022. auto res = cli.Get("/");
  10023. ASSERT_TRUE(res);
  10024. EXPECT_EQ(StatusCode::OK_200, res->status);
  10025. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10026. }
  10027. }
  10028. #ifdef CPPHTTPLIB_SSL_ENABLED
  10029. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10030. Client cli("http://yahoo.com");
  10031. auto res = cli.Get("/");
  10032. ASSERT_TRUE(res);
  10033. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10034. cli.set_follow_location(true);
  10035. res = cli.Get("/");
  10036. ASSERT_TRUE(res);
  10037. EXPECT_EQ(StatusCode::OK_200, res->status);
  10038. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10039. }
  10040. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10041. Client cli("https://yahoo.com");
  10042. auto res = cli.Get("/");
  10043. ASSERT_TRUE(res);
  10044. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10045. cli.set_follow_location(true);
  10046. res = cli.Get("/");
  10047. ASSERT_TRUE(res);
  10048. EXPECT_EQ(StatusCode::OK_200, res->status);
  10049. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10050. }
  10051. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10052. Client cli("https://yahoo.com");
  10053. auto res = cli.Get("/");
  10054. ASSERT_TRUE(res);
  10055. ASSERT_FALSE(!res);
  10056. ASSERT_TRUE(res);
  10057. ASSERT_FALSE(res == nullptr);
  10058. ASSERT_TRUE(res != nullptr);
  10059. EXPECT_EQ(Error::Success, res.error());
  10060. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10061. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10062. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10063. cli.set_follow_location(true);
  10064. res = cli.Get("/");
  10065. ASSERT_TRUE(res);
  10066. EXPECT_EQ(Error::Success, res.error());
  10067. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10068. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10069. EXPECT_EQ(StatusCode::OK_200, res->status);
  10070. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10071. }
  10072. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10073. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10074. Client cli("https://cdnjs.cloudflare.com");
  10075. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10076. Headers{{"Accept-Encoding", "br"}});
  10077. ASSERT_TRUE(res);
  10078. EXPECT_EQ(StatusCode::OK_200, res->status);
  10079. EXPECT_EQ(287630U, res->body.size());
  10080. EXPECT_EQ("application/javascript; charset=utf-8",
  10081. res->get_header_value("Content-Type"));
  10082. }
  10083. #endif
  10084. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10085. #undef REDIR_HOST // Silence compiler warning
  10086. #define REDIR_HOST "https://httpbingo.org"
  10087. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10088. Client cli(REDIR_HOST);
  10089. cli.set_follow_location(true);
  10090. auto res =
  10091. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10092. ASSERT_TRUE(res);
  10093. EXPECT_EQ(StatusCode::OK_200, res->status);
  10094. }
  10095. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10096. Client cli(REDIR_HOST);
  10097. cli.set_follow_location(true);
  10098. Params params;
  10099. params.emplace("url", "http://example.com");
  10100. params.emplace("status_code", "302");
  10101. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10102. ASSERT_TRUE(res);
  10103. EXPECT_EQ(StatusCode::OK_200, res->status);
  10104. }
  10105. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10106. Client cli(REDIR_HOST);
  10107. cli.set_follow_location(true);
  10108. Params params;
  10109. params.emplace("url", "http://example.com");
  10110. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10111. ASSERT_TRUE(res);
  10112. EXPECT_EQ(StatusCode::OK_200, res->status);
  10113. }
  10114. TEST(HttpToHttpsRedirectTest, CertFile) {
  10115. auto ssl_port = PORT + 1;
  10116. Server svr;
  10117. ASSERT_TRUE(svr.is_valid());
  10118. svr.Get("/index", [&](const Request &, Response &res) {
  10119. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10120. "/index");
  10121. svr.stop();
  10122. });
  10123. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10124. ASSERT_TRUE(ssl_svr.is_valid());
  10125. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10126. res.set_content("test", "text/plain");
  10127. ssl_svr.stop();
  10128. });
  10129. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10130. thread t2 =
  10131. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10132. auto se = detail::scope_exit([&] {
  10133. t2.join();
  10134. t.join();
  10135. ASSERT_FALSE(svr.is_running());
  10136. });
  10137. svr.wait_until_ready();
  10138. ssl_svr.wait_until_ready();
  10139. Client cli("127.0.0.1", PORT);
  10140. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10141. cli.enable_server_certificate_verification(true);
  10142. cli.set_follow_location(true);
  10143. cli.set_connection_timeout(30);
  10144. auto res = cli.Get("/index");
  10145. ASSERT_TRUE(res);
  10146. ASSERT_EQ(StatusCode::OK_200, res->status);
  10147. }
  10148. TEST(SSLClientRedirectTest, CertFile) {
  10149. auto ssl_port = PORT + 1;
  10150. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10151. ASSERT_TRUE(ssl_svr1.is_valid());
  10152. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10153. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10154. "/index");
  10155. ssl_svr1.stop();
  10156. });
  10157. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10158. ASSERT_TRUE(ssl_svr2.is_valid());
  10159. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10160. res.set_content("test", "text/plain");
  10161. ssl_svr2.stop();
  10162. });
  10163. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10164. thread t2 =
  10165. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10166. auto se = detail::scope_exit([&] {
  10167. t2.join();
  10168. t.join();
  10169. ASSERT_FALSE(ssl_svr1.is_running());
  10170. });
  10171. ssl_svr1.wait_until_ready();
  10172. ssl_svr2.wait_until_ready();
  10173. SSLClient cli("127.0.0.1", PORT);
  10174. std::string cert;
  10175. read_file(SERVER_CERT2_FILE, cert);
  10176. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10177. cli.enable_server_certificate_verification(true);
  10178. cli.set_follow_location(true);
  10179. cli.set_connection_timeout(30);
  10180. auto res = cli.Get("/index");
  10181. ASSERT_TRUE(res);
  10182. ASSERT_EQ(StatusCode::OK_200, res->status);
  10183. }
  10184. #endif
  10185. #ifdef CPPHTTPLIB_SSL_ENABLED
  10186. // Test that set_ca_cert_store() skips system certs (consistent with
  10187. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10188. // should be trusted - system certs should NOT be loaded.
  10189. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10190. // Load a specific cert that is NOT a system CA cert
  10191. std::string cert;
  10192. read_file(SERVER_CERT2_FILE, cert);
  10193. SSLClient cli("google.com");
  10194. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10195. cli.enable_server_certificate_verification(true);
  10196. // This should FAIL because:
  10197. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10198. // 2. System certs should NOT be loaded when custom store is set
  10199. // If system certs WERE loaded, this would succeed
  10200. auto res = cli.Get("/");
  10201. ASSERT_FALSE(res);
  10202. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10203. }
  10204. // Same as above, but through the native store handle path. Regression test:
  10205. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10206. // merged system certs into the user-provided store.
  10207. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10208. std::string cert;
  10209. read_file(SERVER_CERT2_FILE, cert);
  10210. SSLClient cli("google.com");
  10211. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10212. cli.enable_server_certificate_verification(true);
  10213. auto res = cli.Get("/");
  10214. ASSERT_FALSE(res);
  10215. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10216. }
  10217. // A custom store set via the native handle must still verify a server whose
  10218. // cert it does contain.
  10219. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10220. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10221. ASSERT_TRUE(svr.is_valid());
  10222. svr.Get("/test", [&](const Request &, Response &res) {
  10223. res.set_content("test", "text/plain");
  10224. });
  10225. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10226. auto se = detail::scope_exit([&] {
  10227. svr.stop();
  10228. t.join();
  10229. ASSERT_FALSE(svr.is_running());
  10230. });
  10231. svr.wait_until_ready();
  10232. SSLClient cli("127.0.0.1", PORT);
  10233. std::string cert;
  10234. read_file(SERVER_CERT2_FILE, cert);
  10235. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10236. cli.enable_server_certificate_verification(true);
  10237. cli.set_connection_timeout(30);
  10238. auto res = cli.Get("/test");
  10239. ASSERT_TRUE(res);
  10240. ASSERT_EQ(StatusCode::OK_200, res->status);
  10241. }
  10242. // CA certs loaded through the universal Client must be transferred to the
  10243. // client created internally for following an HTTPS redirect. Regression test:
  10244. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10245. // the CA data for redirect transfer.
  10246. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10247. auto ssl_port = PORT + 1;
  10248. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10249. ASSERT_TRUE(ssl_svr1.is_valid());
  10250. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10251. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10252. "/index");
  10253. });
  10254. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10255. ASSERT_TRUE(ssl_svr2.is_valid());
  10256. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10257. res.set_content("test", "text/plain");
  10258. });
  10259. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10260. thread t2 =
  10261. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10262. auto se = detail::scope_exit([&] {
  10263. ssl_svr2.stop();
  10264. ssl_svr1.stop();
  10265. t2.join();
  10266. t.join();
  10267. ASSERT_FALSE(ssl_svr1.is_running());
  10268. });
  10269. ssl_svr1.wait_until_ready();
  10270. ssl_svr2.wait_until_ready();
  10271. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10272. std::string cert;
  10273. read_file(SERVER_CERT2_FILE, cert);
  10274. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10275. cli.enable_server_certificate_verification(true);
  10276. cli.set_follow_location(true);
  10277. cli.set_connection_timeout(30);
  10278. auto res = cli.Get("/index");
  10279. ASSERT_TRUE(res);
  10280. ASSERT_EQ(StatusCode::OK_200, res->status);
  10281. }
  10282. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10283. // so a host signed by a system CA verifies even though a custom CA is set
  10284. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10285. std::string cert;
  10286. read_file(SERVER_CERT2_FILE, cert);
  10287. SSLClient cli("google.com");
  10288. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10289. cli.enable_system_ca(true);
  10290. cli.enable_server_certificate_verification(true);
  10291. auto res = cli.Get("/");
  10292. ASSERT_TRUE(res);
  10293. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10294. }
  10295. // The custom CA remains effective when combined with the system CA
  10296. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10297. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10298. ASSERT_TRUE(svr.is_valid());
  10299. svr.Get("/test", [&](const Request &, Response &res) {
  10300. res.set_content("test", "text/plain");
  10301. });
  10302. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10303. auto se = detail::scope_exit([&] {
  10304. svr.stop();
  10305. t.join();
  10306. ASSERT_FALSE(svr.is_running());
  10307. });
  10308. svr.wait_until_ready();
  10309. SSLClient cli("127.0.0.1", PORT);
  10310. std::string cert;
  10311. read_file(SERVER_CERT2_FILE, cert);
  10312. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10313. cli.enable_system_ca(true);
  10314. cli.enable_server_certificate_verification(true);
  10315. cli.set_connection_timeout(30);
  10316. auto res = cli.Get("/test");
  10317. ASSERT_TRUE(res);
  10318. ASSERT_EQ(StatusCode::OK_200, res->status);
  10319. }
  10320. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10321. // skip chain verification entirely (only the certificate identity was
  10322. // checked), so a server presenting an untrusted certificate with a matching
  10323. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10324. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10325. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10326. ASSERT_TRUE(svr.is_valid());
  10327. svr.Get("/test", [&](const Request &, Response &res) {
  10328. res.set_content("test", "text/plain");
  10329. });
  10330. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10331. auto se = detail::scope_exit([&] {
  10332. svr.stop();
  10333. t.join();
  10334. ASSERT_FALSE(svr.is_running());
  10335. });
  10336. svr.wait_until_ready();
  10337. SSLClient cli("127.0.0.1", PORT);
  10338. std::string cert;
  10339. // A trusted CA that did not sign the server certificate. The server cert
  10340. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10341. // this connection.
  10342. read_file(CLIENT_CA_CERT_FILE, cert);
  10343. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10344. cli.enable_server_certificate_verification(true);
  10345. cli.set_connection_timeout(30);
  10346. auto res = cli.Get("/test");
  10347. ASSERT_FALSE(res);
  10348. }
  10349. // enable_system_ca(false) prevents system CA loading entirely
  10350. TEST(SSLClientTest, DisableSystemCa_Online) {
  10351. SSLClient cli("google.com");
  10352. cli.enable_system_ca(false);
  10353. cli.enable_server_certificate_verification(true);
  10354. auto res = cli.Get("/");
  10355. ASSERT_FALSE(res);
  10356. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10357. // itself when the CA chain is empty
  10358. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10359. res.error() == Error::SSLConnection);
  10360. }
  10361. // The universal Client forwards enable_system_ca()
  10362. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10363. std::string cert;
  10364. read_file(SERVER_CERT2_FILE, cert);
  10365. Client cli("https://google.com");
  10366. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10367. cli.enable_system_ca(true);
  10368. cli.enable_server_certificate_verification(true);
  10369. auto res = cli.Get("/");
  10370. ASSERT_TRUE(res);
  10371. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10372. }
  10373. // The system CA policy must carry over to the client created internally for
  10374. // following a cross-host HTTPS redirect
  10375. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10376. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10377. ASSERT_TRUE(svr.is_valid());
  10378. svr.Get("/index", [&](const Request &, Response &res) {
  10379. res.set_redirect("https://www.google.com/");
  10380. });
  10381. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10382. auto se = detail::scope_exit([&] {
  10383. svr.stop();
  10384. t.join();
  10385. ASSERT_FALSE(svr.is_running());
  10386. });
  10387. svr.wait_until_ready();
  10388. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10389. std::string cert;
  10390. read_file(SERVER_CERT2_FILE, cert);
  10391. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10392. cli.enable_system_ca(true);
  10393. cli.enable_server_certificate_verification(true);
  10394. cli.set_follow_location(true);
  10395. cli.set_connection_timeout(30);
  10396. // Receiving any response proves the redirect client completed the TLS
  10397. // handshake with a system-CA-signed host
  10398. auto res = cli.Get("/index");
  10399. ASSERT_TRUE(res);
  10400. }
  10401. TEST(MultipartFormDataTest, LargeData) {
  10402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10403. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10404. const ContentReader &content_reader) {
  10405. if (req.is_multipart_form_data()) {
  10406. std::vector<FormData> items;
  10407. content_reader(
  10408. [&](const FormData &file) {
  10409. items.push_back(file);
  10410. return true;
  10411. },
  10412. [&](const char *data, size_t data_length) {
  10413. items.back().content.append(data, data_length);
  10414. return true;
  10415. });
  10416. EXPECT_TRUE(std::string(items[0].name) == "document");
  10417. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10418. EXPECT_TRUE(items[0].filename == "2MB_data");
  10419. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10420. EXPECT_TRUE(items[1].name == "hello");
  10421. EXPECT_TRUE(items[1].content == "world");
  10422. EXPECT_TRUE(items[1].filename == "");
  10423. EXPECT_TRUE(items[1].content_type == "");
  10424. } else {
  10425. std::string body;
  10426. content_reader([&](const char *data, size_t data_length) {
  10427. body.append(data, data_length);
  10428. return true;
  10429. });
  10430. }
  10431. });
  10432. auto port = svr.bind_to_any_port(HOST);
  10433. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10434. auto se = detail::scope_exit([&] {
  10435. svr.stop();
  10436. t.join();
  10437. ASSERT_FALSE(svr.is_running());
  10438. });
  10439. svr.wait_until_ready();
  10440. {
  10441. std::string data(1024 * 1024 * 2, '.');
  10442. std::stringstream buffer;
  10443. buffer << data;
  10444. SSLClient cli(HOST, port);
  10445. cli.enable_server_certificate_verification(false);
  10446. UploadFormDataItems items{
  10447. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10448. {"hello", "world", "", ""},
  10449. };
  10450. auto res = cli.Post("/post", items);
  10451. ASSERT_TRUE(res);
  10452. ASSERT_EQ(StatusCode::OK_200, res->status);
  10453. }
  10454. }
  10455. TEST(MultipartFormDataTest, DataProviderItems) {
  10456. std::random_device seed_gen;
  10457. std::mt19937 random(seed_gen());
  10458. std::string rand1;
  10459. rand1.resize(1000);
  10460. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10461. std::string rand2;
  10462. rand2.resize(3000);
  10463. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10465. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10466. const ContentReader &content_reader) {
  10467. ASSERT_FALSE(req.is_multipart_form_data());
  10468. std::string body;
  10469. content_reader([&](const char *data, size_t data_length) {
  10470. body.append(data, data_length);
  10471. return true;
  10472. });
  10473. EXPECT_EQ(body, "");
  10474. });
  10475. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10476. const ContentReader &content_reader) {
  10477. ASSERT_TRUE(req.is_multipart_form_data());
  10478. std::vector<FormData> items;
  10479. content_reader(
  10480. [&](const FormData &file) {
  10481. items.push_back(file);
  10482. return true;
  10483. },
  10484. [&](const char *data, size_t data_length) {
  10485. items.back().content.append(data, data_length);
  10486. return true;
  10487. });
  10488. ASSERT_TRUE(items.size() == 2);
  10489. EXPECT_EQ(std::string(items[0].name), "name1");
  10490. EXPECT_EQ(items[0].content, "Testing123");
  10491. EXPECT_EQ(items[0].filename, "filename1");
  10492. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10493. EXPECT_EQ(items[1].name, "name2");
  10494. EXPECT_EQ(items[1].content, "Testing456");
  10495. EXPECT_EQ(items[1].filename, "");
  10496. EXPECT_EQ(items[1].content_type, "");
  10497. });
  10498. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10499. const ContentReader &content_reader) {
  10500. ASSERT_TRUE(req.is_multipart_form_data());
  10501. std::vector<FormData> items;
  10502. content_reader(
  10503. [&](const FormData &file) {
  10504. items.push_back(file);
  10505. return true;
  10506. },
  10507. [&](const char *data, size_t data_length) {
  10508. items.back().content.append(data, data_length);
  10509. return true;
  10510. });
  10511. ASSERT_TRUE(items.size() == 2);
  10512. EXPECT_EQ(items[0].name, "name3");
  10513. EXPECT_EQ(items[0].content, rand1);
  10514. EXPECT_EQ(items[0].filename, "filename3");
  10515. EXPECT_EQ(items[0].content_type, "");
  10516. EXPECT_EQ(items[1].name, "name4");
  10517. EXPECT_EQ(items[1].content, rand2);
  10518. EXPECT_EQ(items[1].filename, "filename4");
  10519. EXPECT_EQ(items[1].content_type, "");
  10520. });
  10521. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10522. const ContentReader &content_reader) {
  10523. ASSERT_TRUE(req.is_multipart_form_data());
  10524. std::vector<FormData> items;
  10525. content_reader(
  10526. [&](const FormData &file) {
  10527. items.push_back(file);
  10528. return true;
  10529. },
  10530. [&](const char *data, size_t data_length) {
  10531. items.back().content.append(data, data_length);
  10532. return true;
  10533. });
  10534. ASSERT_TRUE(items.size() == 4);
  10535. EXPECT_EQ(std::string(items[0].name), "name1");
  10536. EXPECT_EQ(items[0].content, "Testing123");
  10537. EXPECT_EQ(items[0].filename, "filename1");
  10538. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10539. EXPECT_EQ(items[1].name, "name2");
  10540. EXPECT_EQ(items[1].content, "Testing456");
  10541. EXPECT_EQ(items[1].filename, "");
  10542. EXPECT_EQ(items[1].content_type, "");
  10543. EXPECT_EQ(items[2].name, "name3");
  10544. EXPECT_EQ(items[2].content, rand1);
  10545. EXPECT_EQ(items[2].filename, "filename3");
  10546. EXPECT_EQ(items[2].content_type, "");
  10547. EXPECT_EQ(items[3].name, "name4");
  10548. EXPECT_EQ(items[3].content, rand2);
  10549. EXPECT_EQ(items[3].filename, "filename4");
  10550. EXPECT_EQ(items[3].content_type, "");
  10551. });
  10552. auto port = svr.bind_to_any_port("localhost");
  10553. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10554. auto se = detail::scope_exit([&] {
  10555. svr.stop();
  10556. t.join();
  10557. ASSERT_FALSE(svr.is_running());
  10558. });
  10559. svr.wait_until_ready();
  10560. {
  10561. SSLClient cli("localhost", port);
  10562. cli.enable_server_certificate_verification(false);
  10563. UploadFormDataItems items{
  10564. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10565. {"name2", "Testing456", "", ""}, // not a file
  10566. };
  10567. {
  10568. auto res = cli.Post("/post-none", {}, {}, {});
  10569. ASSERT_TRUE(res);
  10570. ASSERT_EQ(StatusCode::OK_200, res->status);
  10571. }
  10572. FormDataProviderItems providers;
  10573. {
  10574. auto res =
  10575. cli.Post("/post-items", {}, items, providers); // empty providers
  10576. ASSERT_TRUE(res);
  10577. ASSERT_EQ(StatusCode::OK_200, res->status);
  10578. }
  10579. providers.push_back({"name3",
  10580. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10581. // test the offset is given correctly at each step
  10582. if (!offset)
  10583. sink.os.write(rand1.data(), 30);
  10584. else if (offset == 30)
  10585. sink.os.write(rand1.data() + 30, 300);
  10586. else if (offset == 330)
  10587. sink.os.write(rand1.data() + 330, 670);
  10588. else if (offset == rand1.size())
  10589. sink.done();
  10590. return true;
  10591. },
  10592. "filename3",
  10593. {}});
  10594. providers.push_back({"name4",
  10595. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10596. // test the offset is given correctly at each step
  10597. if (!offset)
  10598. sink.os.write(rand2.data(), 2000);
  10599. else if (offset == 2000)
  10600. sink.os.write(rand2.data() + 2000, 1);
  10601. else if (offset == 2001)
  10602. sink.os.write(rand2.data() + 2001, 999);
  10603. else if (offset == rand2.size())
  10604. sink.done();
  10605. return true;
  10606. },
  10607. "filename4",
  10608. {}});
  10609. {
  10610. auto res = cli.Post("/post-providers", {}, {}, providers);
  10611. ASSERT_TRUE(res);
  10612. ASSERT_EQ(StatusCode::OK_200, res->status);
  10613. }
  10614. {
  10615. auto res = cli.Post("/post-both", {}, items, providers);
  10616. ASSERT_TRUE(res);
  10617. ASSERT_EQ(StatusCode::OK_200, res->status);
  10618. }
  10619. }
  10620. }
  10621. TEST(MultipartFormDataTest, BadHeader) {
  10622. Server svr;
  10623. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10624. res.set_content("ok", "text/plain");
  10625. });
  10626. thread t = thread([&] { svr.listen(HOST, PORT); });
  10627. auto se = detail::scope_exit([&] {
  10628. svr.stop();
  10629. t.join();
  10630. ASSERT_FALSE(svr.is_running());
  10631. });
  10632. svr.wait_until_ready();
  10633. const std::string body =
  10634. "This is the preamble. It is to be ignored, though it\r\n"
  10635. "is a handy place for composition agents to include an\r\n"
  10636. "explanatory note to non-MIME conformant readers.\r\n"
  10637. "\r\n"
  10638. "\r\n"
  10639. "--simple boundary\r\n"
  10640. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10641. ": BAD...\r\n"
  10642. "\r\n"
  10643. "value1\r\n"
  10644. "--simple boundary\r\n"
  10645. "Content-Disposition: form-data; name=\"field2\"; "
  10646. "filename=\"example.txt\"\r\n"
  10647. "\r\n"
  10648. "value2\r\n"
  10649. "--simple boundary--\r\n"
  10650. "This is the epilogue. It is also to be ignored.\r\n";
  10651. std::string content_type =
  10652. R"(multipart/form-data; boundary="simple boundary")";
  10653. Client cli(HOST, PORT);
  10654. auto res = cli.Post("/post", body, content_type.c_str());
  10655. ASSERT_TRUE(res);
  10656. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10657. }
  10658. TEST(MultipartFormDataTest, WithPreamble) {
  10659. Server svr;
  10660. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10661. res.set_content("ok", "text/plain");
  10662. });
  10663. thread t = thread([&] { svr.listen(HOST, PORT); });
  10664. auto se = detail::scope_exit([&] {
  10665. svr.stop();
  10666. t.join();
  10667. ASSERT_FALSE(svr.is_running());
  10668. });
  10669. svr.wait_until_ready();
  10670. const std::string body =
  10671. "This is the preamble. It is to be ignored, though it\r\n"
  10672. "is a handy place for composition agents to include an\r\n"
  10673. "explanatory note to non-MIME conformant readers.\r\n"
  10674. "\r\n"
  10675. "\r\n"
  10676. "--simple boundary\r\n"
  10677. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10678. "\r\n"
  10679. "value1\r\n"
  10680. "--simple boundary\r\n"
  10681. "Content-Disposition: form-data; name=\"field2\"; "
  10682. "filename=\"example.txt\"\r\n"
  10683. "\r\n"
  10684. "value2\r\n"
  10685. "--simple boundary--\r\n"
  10686. "This is the epilogue. It is also to be ignored.\r\n";
  10687. std::string content_type =
  10688. R"(multipart/form-data; boundary="simple boundary")";
  10689. Client cli(HOST, PORT);
  10690. auto res = cli.Post("/post", body, content_type.c_str());
  10691. ASSERT_TRUE(res);
  10692. EXPECT_EQ(StatusCode::OK_200, res->status);
  10693. }
  10694. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10695. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10696. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10697. const ContentReader &content_reader) {
  10698. if (req.is_multipart_form_data()) {
  10699. std::vector<FormData> items;
  10700. content_reader(
  10701. [&](const FormData &file) {
  10702. items.push_back(file);
  10703. return true;
  10704. },
  10705. [&](const char *data, size_t data_length) {
  10706. items.back().content.append(data, data_length);
  10707. return true;
  10708. });
  10709. EXPECT_TRUE(std::string(items[0].name) == "document");
  10710. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10711. EXPECT_TRUE(items[0].filename == "2MB_data");
  10712. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10713. EXPECT_TRUE(items[1].name == "hello");
  10714. EXPECT_TRUE(items[1].content == "world");
  10715. EXPECT_TRUE(items[1].filename == "");
  10716. EXPECT_TRUE(items[1].content_type == "");
  10717. } else {
  10718. std::string body;
  10719. content_reader([&](const char *data, size_t data_length) {
  10720. body.append(data, data_length);
  10721. return true;
  10722. });
  10723. }
  10724. });
  10725. auto port = svr.bind_to_any_port("localhost");
  10726. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10727. auto se = detail::scope_exit([&] {
  10728. svr.stop();
  10729. t.join();
  10730. ASSERT_FALSE(svr.is_running());
  10731. });
  10732. svr.wait_until_ready();
  10733. {
  10734. std::string data(1024 * 1024 * 2, '.');
  10735. std::stringstream buffer;
  10736. buffer << data;
  10737. SSLClient cli("localhost", port);
  10738. cli.enable_server_certificate_verification(false);
  10739. UploadFormDataItems items{
  10740. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10741. {"hello", "world", "", ""},
  10742. };
  10743. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10744. ASSERT_TRUE(res);
  10745. ASSERT_EQ(StatusCode::OK_200, res->status);
  10746. }
  10747. }
  10748. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10749. std::string data(1024 * 1024 * 2, '&');
  10750. std::stringstream buffer;
  10751. buffer << data;
  10752. Client cli("https://localhost:8080");
  10753. UploadFormDataItems items{
  10754. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10755. {"hello", "world", "", ""},
  10756. };
  10757. for (const char &c : " \t\r\n") {
  10758. auto res =
  10759. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10760. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10761. ASSERT_FALSE(res);
  10762. }
  10763. }
  10764. TEST(MultipartFormDataTest, PutFormData) {
  10765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10766. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10767. const ContentReader &content_reader) {
  10768. if (req.is_multipart_form_data()) {
  10769. std::vector<FormData> items;
  10770. content_reader(
  10771. [&](const FormData &file) {
  10772. items.push_back(file);
  10773. return true;
  10774. },
  10775. [&](const char *data, size_t data_length) {
  10776. items.back().content.append(data, data_length);
  10777. return true;
  10778. });
  10779. EXPECT_TRUE(std::string(items[0].name) == "document");
  10780. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10781. EXPECT_TRUE(items[0].filename == "2MB_data");
  10782. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10783. EXPECT_TRUE(items[1].name == "hello");
  10784. EXPECT_TRUE(items[1].content == "world");
  10785. EXPECT_TRUE(items[1].filename == "");
  10786. EXPECT_TRUE(items[1].content_type == "");
  10787. } else {
  10788. std::string body;
  10789. content_reader([&](const char *data, size_t data_length) {
  10790. body.append(data, data_length);
  10791. return true;
  10792. });
  10793. }
  10794. });
  10795. auto port = svr.bind_to_any_port("localhost");
  10796. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10797. auto se = detail::scope_exit([&] {
  10798. svr.stop();
  10799. t.join();
  10800. ASSERT_FALSE(svr.is_running());
  10801. });
  10802. svr.wait_until_ready();
  10803. {
  10804. std::string data(1024 * 1024 * 2, '&');
  10805. std::stringstream buffer;
  10806. buffer << data;
  10807. SSLClient cli("localhost", port);
  10808. cli.enable_server_certificate_verification(false);
  10809. UploadFormDataItems items{
  10810. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10811. {"hello", "world", "", ""},
  10812. };
  10813. auto res = cli.Put("/put", items);
  10814. ASSERT_TRUE(res);
  10815. ASSERT_EQ(StatusCode::OK_200, res->status);
  10816. }
  10817. }
  10818. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10820. svr.Put("/put_customboundary",
  10821. [&](const Request &req, const Response & /*res*/,
  10822. const ContentReader &content_reader) {
  10823. if (req.is_multipart_form_data()) {
  10824. std::vector<FormData> items;
  10825. content_reader(
  10826. [&](const FormData &file) {
  10827. items.push_back(file);
  10828. return true;
  10829. },
  10830. [&](const char *data, size_t data_length) {
  10831. items.back().content.append(data, data_length);
  10832. return true;
  10833. });
  10834. EXPECT_TRUE(std::string(items[0].name) == "document");
  10835. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10836. EXPECT_TRUE(items[0].filename == "2MB_data");
  10837. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10838. EXPECT_TRUE(items[1].name == "hello");
  10839. EXPECT_TRUE(items[1].content == "world");
  10840. EXPECT_TRUE(items[1].filename == "");
  10841. EXPECT_TRUE(items[1].content_type == "");
  10842. } else {
  10843. std::string body;
  10844. content_reader([&](const char *data, size_t data_length) {
  10845. body.append(data, data_length);
  10846. return true;
  10847. });
  10848. }
  10849. });
  10850. auto port = svr.bind_to_any_port("localhost");
  10851. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10852. auto se = detail::scope_exit([&] {
  10853. svr.stop();
  10854. t.join();
  10855. ASSERT_FALSE(svr.is_running());
  10856. });
  10857. svr.wait_until_ready();
  10858. {
  10859. std::string data(1024 * 1024 * 2, '&');
  10860. std::stringstream buffer;
  10861. buffer << data;
  10862. SSLClient cli("localhost", port);
  10863. cli.enable_server_certificate_verification(false);
  10864. UploadFormDataItems items{
  10865. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10866. {"hello", "world", "", ""},
  10867. };
  10868. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10869. ASSERT_TRUE(res);
  10870. ASSERT_EQ(StatusCode::OK_200, res->status);
  10871. }
  10872. }
  10873. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10874. std::string data(1024 * 1024 * 2, '&');
  10875. std::stringstream buffer;
  10876. buffer << data;
  10877. Client cli("https://localhost:8080");
  10878. cli.enable_server_certificate_verification(false);
  10879. UploadFormDataItems items{
  10880. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10881. {"hello", "world", "", ""},
  10882. };
  10883. for (const char &c : " \t\r\n") {
  10884. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10885. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10886. ASSERT_FALSE(res);
  10887. }
  10888. }
  10889. TEST(MultipartFormDataTest, AlternateFilename) {
  10890. auto handled = false;
  10891. Server svr;
  10892. svr.Post("/test", [&](const Request &req, Response &res) {
  10893. ASSERT_EQ(2u, req.form.files.size());
  10894. ASSERT_EQ(1u, req.form.fields.size());
  10895. // Test files
  10896. const auto &file1 = req.form.get_file("file1");
  10897. ASSERT_EQ("file1", file1.name);
  10898. ASSERT_EQ("A.txt", file1.filename);
  10899. ASSERT_EQ("text/plain", file1.content_type);
  10900. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10901. const auto &file2 = req.form.get_file("file2");
  10902. ASSERT_EQ("file2", file2.name);
  10903. ASSERT_EQ("a.html", file2.filename);
  10904. ASSERT_EQ("text/html", file2.content_type);
  10905. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10906. file2.content);
  10907. // Test text field
  10908. const auto &text = req.form.get_field("text");
  10909. ASSERT_EQ("text default", text);
  10910. res.set_content("ok", "text/plain");
  10911. handled = true;
  10912. });
  10913. thread t = thread([&] { svr.listen(HOST, PORT); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. t.join();
  10917. ASSERT_FALSE(svr.is_running());
  10918. ASSERT_TRUE(handled);
  10919. });
  10920. svr.wait_until_ready();
  10921. auto req = "POST /test HTTP/1.1\r\n"
  10922. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10923. "Content-Length: 399\r\n"
  10924. "\r\n"
  10925. "----------\r\n"
  10926. "Content-Disposition: form-data; name=\"text\"\r\n"
  10927. "\r\n"
  10928. "text default\r\n"
  10929. "----------\r\n"
  10930. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10931. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10932. "Content-Type: text/plain\r\n"
  10933. "\r\n"
  10934. "Content of a.txt.\r\n"
  10935. "\r\n"
  10936. "----------\r\n"
  10937. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10938. "\"a.html\"\r\n"
  10939. "Content-Type: text/html\r\n"
  10940. "\r\n"
  10941. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10942. "\r\n"
  10943. "------------\r\n";
  10944. ASSERT_TRUE(send_request(1, req));
  10945. }
  10946. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10947. auto handled = false;
  10948. Server svr;
  10949. svr.Post("/test", [&](const Request &req, Response &res) {
  10950. // Case-insensitive "utf-8''" prefix with a long value
  10951. const auto &file = req.form.get_file("file1");
  10952. ASSERT_EQ("file1", file.name);
  10953. // 8000 chars exercises both the Content-Disposition parser and the
  10954. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10955. // Prior to the fix, std::regex_match on this header would cause O(N)
  10956. // stack recursion in libstdc++, leading to SIGSEGV.
  10957. std::string expected_filename(8000, 'A');
  10958. ASSERT_EQ(expected_filename, file.filename);
  10959. res.set_content("ok", "text/plain");
  10960. handled = true;
  10961. });
  10962. thread t = thread([&] { svr.listen(HOST, PORT); });
  10963. auto se = detail::scope_exit([&] {
  10964. svr.stop();
  10965. t.join();
  10966. ASSERT_FALSE(svr.is_running());
  10967. ASSERT_TRUE(handled);
  10968. });
  10969. svr.wait_until_ready();
  10970. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10971. // Regression test for GHSA-qq6v-r583-3h69
  10972. std::string long_filename(8000, 'A');
  10973. std::string body = "----------\r\n"
  10974. "Content-Disposition: form-data; name=\"file1\"; "
  10975. "filename*=\"Utf-8''" +
  10976. long_filename +
  10977. "\"\r\n"
  10978. "\r\n"
  10979. "hello\r\n"
  10980. "------------\r\n";
  10981. auto req = "POST /test HTTP/1.1\r\n"
  10982. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10983. "Content-Length: " +
  10984. std::to_string(body.size()) + "\r\n\r\n" + body;
  10985. ASSERT_TRUE(send_request(1, req));
  10986. }
  10987. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10988. auto handled = false;
  10989. Server svr;
  10990. svr.Post("/test", [&](const Request &req, Response &) {
  10991. ASSERT_EQ(2u, req.form.fields.size());
  10992. const auto &text1 = req.form.get_field("text1");
  10993. ASSERT_EQ("text1", text1);
  10994. const auto &text2 = req.form.get_field("text2");
  10995. ASSERT_EQ("text2", text2);
  10996. handled = true;
  10997. });
  10998. thread t = thread([&] { svr.listen(HOST, PORT); });
  10999. auto se = detail::scope_exit([&] {
  11000. svr.stop();
  11001. t.join();
  11002. ASSERT_FALSE(svr.is_running());
  11003. ASSERT_TRUE(handled);
  11004. });
  11005. svr.wait_until_ready();
  11006. auto req = "POST /test HTTP/1.1\r\n"
  11007. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11008. "Content-Length: 146\r\n"
  11009. "\r\n----------\r\n"
  11010. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11011. "\r\n"
  11012. "text1"
  11013. "\r\n----------\r\n"
  11014. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11015. "\r\n"
  11016. "text2"
  11017. "\r\n------------";
  11018. std::string response;
  11019. ASSERT_TRUE(send_request(1, req, &response));
  11020. ASSERT_EQ("200", response.substr(9, 3));
  11021. }
  11022. TEST(MultipartFormDataTest, ContentLength) {
  11023. auto handled = false;
  11024. Server svr;
  11025. svr.Post("/test", [&](const Request &req, Response &) {
  11026. ASSERT_EQ(2u, req.form.fields.size());
  11027. const auto &text1 = req.form.get_field("text1");
  11028. ASSERT_EQ("text1", text1);
  11029. const auto &text2 = req.form.get_field("text2");
  11030. ASSERT_EQ("text2", text2);
  11031. handled = true;
  11032. });
  11033. thread t = thread([&] { svr.listen(HOST, PORT); });
  11034. auto se = detail::scope_exit([&] {
  11035. svr.stop();
  11036. t.join();
  11037. ASSERT_FALSE(svr.is_running());
  11038. ASSERT_TRUE(handled);
  11039. });
  11040. svr.wait_until_ready();
  11041. auto req = "POST /test HTTP/1.1\r\n"
  11042. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11043. "Content-Length: 167\r\n"
  11044. "\r\n----------\r\n"
  11045. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11046. "Content-Length: 5\r\n"
  11047. "\r\n"
  11048. "text1"
  11049. "\r\n----------\r\n"
  11050. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11051. "\r\n"
  11052. "text2"
  11053. "\r\n------------\r\n";
  11054. std::string response;
  11055. ASSERT_TRUE(send_request(1, req, &response));
  11056. ASSERT_EQ("200", response.substr(9, 3));
  11057. }
  11058. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11059. auto handled = false;
  11060. Server svr;
  11061. svr.Post("/test", [&](const Request &req, Response &) {
  11062. ASSERT_EQ(2u, req.form.fields.size());
  11063. const auto &text1 = req.form.get_field("text1");
  11064. ASSERT_EQ("text1", text1);
  11065. // TODO: Add header access for text fields if needed
  11066. const auto &text2 = req.form.get_field("text2");
  11067. ASSERT_EQ("text2", text2);
  11068. // TODO: Header access for text fields needs to be implemented
  11069. // auto &headers = it->second.headers;
  11070. // ASSERT_EQ(3U, headers.size());
  11071. // auto custom_header = headers.find("x-whatever");
  11072. // ASSERT_TRUE(custom_header != headers.end());
  11073. // ASSERT_NE("customvalue", custom_header->second);
  11074. // ASSERT_EQ("CustomValue", custom_header->second);
  11075. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11076. handled = true;
  11077. });
  11078. thread t = thread([&] { svr.listen(HOST, PORT); });
  11079. auto se = detail::scope_exit([&] {
  11080. svr.stop();
  11081. t.join();
  11082. ASSERT_FALSE(svr.is_running());
  11083. ASSERT_TRUE(handled);
  11084. });
  11085. svr.wait_until_ready();
  11086. auto req = "POST /test HTTP/1.1\r\n"
  11087. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11088. "Content-Length: 232\r\n"
  11089. "\r\n----------\r\n"
  11090. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11091. "Content-Length: 5\r\n"
  11092. "X-Test: 1\r\n"
  11093. "\r\n"
  11094. "text1"
  11095. "\r\n----------\r\n"
  11096. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11097. "Content-Type: text/plain\r\n"
  11098. "X-Whatever: CustomValue\r\n"
  11099. "\r\n"
  11100. "text2"
  11101. "\r\n------------\r\n"
  11102. "That should be disregarded. Not even read";
  11103. std::string response;
  11104. ASSERT_TRUE(send_request(1, req, &response));
  11105. ASSERT_EQ("200", response.substr(9, 3));
  11106. }
  11107. TEST(MultipartFormDataTest, LargeHeader) {
  11108. auto handled = false;
  11109. Server svr;
  11110. svr.Post("/test", [&](const Request &req, Response &) {
  11111. ASSERT_EQ(1u, req.form.fields.size());
  11112. const auto &text = req.form.get_field("name1");
  11113. ASSERT_EQ("text1", text);
  11114. handled = true;
  11115. });
  11116. thread t = thread([&] { svr.listen(HOST, PORT); });
  11117. auto se = detail::scope_exit([&] {
  11118. svr.stop();
  11119. t.join();
  11120. ASSERT_FALSE(svr.is_running());
  11121. ASSERT_TRUE(handled);
  11122. });
  11123. svr.wait_until_ready();
  11124. auto boundary = std::string("cpp-httplib-multipart-data");
  11125. std::string content = "--" + boundary +
  11126. "\r\n"
  11127. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11128. "\r\n"
  11129. "text1\r\n"
  11130. "--" +
  11131. boundary + "--\r\n";
  11132. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11133. "Content-Type: multipart/form-data;boundary=" +
  11134. boundary +
  11135. "\r\n"
  11136. "Content-Length: " +
  11137. std::to_string(content.size()) +
  11138. "\r\n"
  11139. "Dummy-Header: ";
  11140. std::string header_suffix = "\r\n"
  11141. "\r\n";
  11142. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11143. size_t header_dummy_size =
  11144. read_buff_size -
  11145. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11146. auto header_dummy = std::string(header_dummy_size, '@');
  11147. auto req = header_prefix + header_dummy + header_suffix + content;
  11148. std::string response;
  11149. ASSERT_TRUE(send_request(1, req, &response));
  11150. ASSERT_EQ("200", response.substr(9, 3));
  11151. }
  11152. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11153. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11154. // (not chunked Transfer-Encoding) after the streaming refactor.
  11155. auto handled = false;
  11156. Server svr;
  11157. svr.Post("/upload", [&](const Request &req, Response &res) {
  11158. auto cl_it = req.headers.find("Content-Length");
  11159. EXPECT_TRUE(cl_it != req.headers.end());
  11160. auto te_it = req.headers.find("Transfer-Encoding");
  11161. EXPECT_TRUE(te_it == req.headers.end());
  11162. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11163. res.set_content("ok", "text/plain");
  11164. handled = true;
  11165. });
  11166. auto port = svr.bind_to_any_port(HOST);
  11167. auto t = thread([&] { svr.listen_after_bind(); });
  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. UploadFormDataItems items = {
  11176. {"field1", "hello", "", "text/plain"},
  11177. {"file1", "world", "test.txt", "application/octet-stream"},
  11178. };
  11179. Client cli(HOST, port);
  11180. auto res = cli.Post("/upload", {}, items);
  11181. ASSERT_TRUE(res);
  11182. EXPECT_EQ(StatusCode::OK_200, res->status);
  11183. }
  11184. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11185. // Verify that make_multipart_content_provider coalesces many small segments
  11186. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11187. constexpr size_t kItemCount = 1000;
  11188. UploadFormDataItems items;
  11189. items.reserve(kItemCount);
  11190. for (size_t i = 0; i < kItemCount; i++) {
  11191. items.push_back(
  11192. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11193. }
  11194. const std::string boundary = "----test-boundary";
  11195. auto content_length = detail::get_multipart_content_length(items, boundary);
  11196. auto provider = detail::make_multipart_content_provider(items, boundary);
  11197. // Drive the provider the same way write_content_with_progress does
  11198. size_t write_count = 0;
  11199. size_t total_bytes = 0;
  11200. DataSink sink;
  11201. size_t offset = 0;
  11202. sink.write = [&](const char *d, size_t l) -> bool {
  11203. (void)d;
  11204. write_count++;
  11205. total_bytes += l;
  11206. offset += l;
  11207. return true;
  11208. };
  11209. sink.is_writable = []() -> bool { return true; };
  11210. while (offset < content_length) {
  11211. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11212. }
  11213. EXPECT_EQ(content_length, total_bytes);
  11214. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11215. // With buffering into 64KB blocks, write_count should be much smaller.
  11216. auto segment_count = 3 * kItemCount + 1;
  11217. EXPECT_LT(write_count, segment_count / 10);
  11218. }
  11219. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11220. // Integration test: send many UploadFormDataItems and verify the server
  11221. // receives all of them correctly (#2410).
  11222. constexpr size_t kItemCount = 500;
  11223. auto handled = false;
  11224. Server svr;
  11225. svr.Post("/upload", [&](const Request &req, Response &res) {
  11226. EXPECT_EQ(kItemCount, req.form.fields.size());
  11227. for (size_t i = 0; i < kItemCount; i++) {
  11228. auto key = "field" + std::to_string(i);
  11229. auto val = "value" + std::to_string(i);
  11230. auto it = req.form.fields.find(key);
  11231. if (it != req.form.fields.end()) {
  11232. EXPECT_EQ(val, it->second.content);
  11233. } else {
  11234. ADD_FAILURE() << "Missing field: " << key;
  11235. }
  11236. }
  11237. res.set_content("ok", "text/plain");
  11238. handled = true;
  11239. });
  11240. auto port = svr.bind_to_any_port(HOST);
  11241. auto t = thread([&] { svr.listen_after_bind(); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. t.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. ASSERT_TRUE(handled);
  11247. });
  11248. svr.wait_until_ready();
  11249. UploadFormDataItems items;
  11250. items.reserve(kItemCount);
  11251. for (size_t i = 0; i < kItemCount; i++) {
  11252. items.push_back(
  11253. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11254. }
  11255. Client cli(HOST, port);
  11256. auto res = cli.Post("/upload", items);
  11257. ASSERT_TRUE(res);
  11258. EXPECT_EQ(StatusCode::OK_200, res->status);
  11259. }
  11260. TEST(MultipartFormDataTest, MakeFileProvider) {
  11261. // Verify make_file_provider sends a file's contents correctly.
  11262. const std::string file_content(4096, 'Z');
  11263. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11264. {
  11265. std::ofstream ofs(tmp_path, std::ios::binary);
  11266. ofs.write(file_content.data(),
  11267. static_cast<std::streamsize>(file_content.size()));
  11268. }
  11269. auto handled = false;
  11270. Server svr;
  11271. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11272. const ContentReader &content_reader) {
  11273. ASSERT_TRUE(req.is_multipart_form_data());
  11274. std::vector<FormData> items;
  11275. content_reader(
  11276. [&](const FormData &file) {
  11277. items.push_back(file);
  11278. return true;
  11279. },
  11280. [&](const char *data, size_t data_length) {
  11281. items.back().content.append(data, data_length);
  11282. return true;
  11283. });
  11284. ASSERT_EQ(1u, items.size());
  11285. EXPECT_EQ("myfile", items[0].name);
  11286. EXPECT_EQ("data.bin", items[0].filename);
  11287. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11288. EXPECT_EQ(file_content, items[0].content);
  11289. handled = true;
  11290. });
  11291. auto port = svr.bind_to_any_port(HOST);
  11292. auto t = thread([&] { svr.listen_after_bind(); });
  11293. auto se = detail::scope_exit([&] {
  11294. svr.stop();
  11295. t.join();
  11296. ASSERT_FALSE(svr.is_running());
  11297. ASSERT_TRUE(handled);
  11298. std::remove(tmp_path.c_str());
  11299. });
  11300. svr.wait_until_ready();
  11301. FormDataProviderItems providers;
  11302. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11303. "application/octet-stream"));
  11304. Client cli(HOST, port);
  11305. auto res = cli.Post("/upload", {}, {}, providers);
  11306. ASSERT_TRUE(res);
  11307. EXPECT_EQ(StatusCode::OK_200, res->status);
  11308. }
  11309. TEST(MakeFileBodyTest, Basic) {
  11310. const std::string file_content(4096, 'Z');
  11311. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11312. {
  11313. std::ofstream ofs(tmp_path, std::ios::binary);
  11314. ofs.write(file_content.data(),
  11315. static_cast<std::streamsize>(file_content.size()));
  11316. }
  11317. auto handled = false;
  11318. Server svr;
  11319. svr.Post("/upload", [&](const Request &req, Response &res) {
  11320. EXPECT_EQ(file_content, req.body);
  11321. handled = true;
  11322. res.status = StatusCode::OK_200;
  11323. });
  11324. auto port = svr.bind_to_any_port(HOST);
  11325. auto t = thread([&] { svr.listen_after_bind(); });
  11326. auto se = detail::scope_exit([&] {
  11327. svr.stop();
  11328. t.join();
  11329. ASSERT_FALSE(svr.is_running());
  11330. ASSERT_TRUE(handled);
  11331. std::remove(tmp_path.c_str());
  11332. });
  11333. svr.wait_until_ready();
  11334. auto fb = make_file_body(tmp_path);
  11335. ASSERT_GT(fb.first, 0u);
  11336. Client cli(HOST, port);
  11337. auto res =
  11338. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11339. ASSERT_TRUE(res);
  11340. EXPECT_EQ(StatusCode::OK_200, res->status);
  11341. }
  11342. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11343. static constexpr unsigned int number_of_tasks{1000000};
  11344. std::atomic_uint count{0};
  11345. std::unique_ptr<TaskQueue> task_queue{
  11346. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11347. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11348. auto queued = task_queue->enqueue(
  11349. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11350. EXPECT_TRUE(queued);
  11351. }
  11352. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11353. task_queue->shutdown();
  11354. #else
  11355. EXPECT_NO_THROW(task_queue->shutdown());
  11356. #endif
  11357. EXPECT_EQ(number_of_tasks, count.load());
  11358. }
  11359. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11360. static constexpr unsigned int number_of_tasks{1000000};
  11361. static constexpr unsigned int qlimit{2};
  11362. unsigned int queued_count{0};
  11363. std::atomic_uint count{0};
  11364. std::unique_ptr<TaskQueue> task_queue{
  11365. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11366. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11367. if (task_queue->enqueue(
  11368. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11369. queued_count++;
  11370. }
  11371. }
  11372. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11373. task_queue->shutdown();
  11374. #else
  11375. EXPECT_NO_THROW(task_queue->shutdown());
  11376. #endif
  11377. EXPECT_EQ(queued_count, count.load());
  11378. EXPECT_TRUE(queued_count <= number_of_tasks);
  11379. EXPECT_TRUE(queued_count >= qlimit);
  11380. }
  11381. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11382. // Use a short idle timeout so a dynamic thread spawns, times out and
  11383. // exits during the test, and the pool keeps working afterwards.
  11384. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11385. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11386. /*idle_timeout_sec=*/1}};
  11387. std::atomic_uint count{0};
  11388. std::condition_variable cv;
  11389. std::mutex mtx;
  11390. bool release = false;
  11391. // Block the base thread so the second task spawns a dynamic thread.
  11392. EXPECT_TRUE(task_queue->enqueue([&] {
  11393. std::unique_lock<std::mutex> lock(mtx);
  11394. while (!release) {
  11395. cv.wait(lock);
  11396. }
  11397. count++;
  11398. }));
  11399. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11400. // Let the dynamic thread finish its task and exceed the idle timeout.
  11401. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11402. {
  11403. std::unique_lock<std::mutex> lock(mtx);
  11404. release = true;
  11405. }
  11406. cv.notify_all();
  11407. // The pool must still accept and run tasks after the dynamic thread exited.
  11408. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11409. task_queue->shutdown();
  11410. EXPECT_EQ(3u, count.load());
  11411. }
  11412. TEST(TaskQueueTest, MaxQueuedRequests) {
  11413. static constexpr unsigned int qlimit{3};
  11414. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11415. std::condition_variable sem_cv;
  11416. std::mutex sem_mtx;
  11417. int credits = 0;
  11418. bool queued;
  11419. /* Fill up the queue with tasks that will block until we give them credits to
  11420. * complete. */
  11421. for (unsigned int n = 0; n <= qlimit;) {
  11422. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11423. std::unique_lock<std::mutex> lock(sem_mtx);
  11424. while (credits <= 0) {
  11425. sem_cv.wait(lock);
  11426. }
  11427. /* Consume the credit and signal the test code if they are all gone. */
  11428. if (--credits == 0) { sem_cv.notify_one(); }
  11429. });
  11430. if (n < qlimit) {
  11431. /* The first qlimit enqueues must succeed. */
  11432. EXPECT_TRUE(queued);
  11433. } else {
  11434. /* The last one will succeed only when the worker thread
  11435. * starts and dequeues the first blocking task. Although
  11436. * not necessary for the correctness of this test, we sleep for
  11437. * a short while to avoid busy waiting. */
  11438. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11439. }
  11440. if (queued) { n++; }
  11441. }
  11442. /* Further enqueues must fail since the queue is full. */
  11443. for (auto i = 0; i < 4; i++) {
  11444. queued = task_queue->enqueue([] {});
  11445. EXPECT_FALSE(queued);
  11446. }
  11447. /* Give the credits to allow the previous tasks to complete. */
  11448. {
  11449. std::unique_lock<std::mutex> lock(sem_mtx);
  11450. credits += qlimit + 1;
  11451. }
  11452. sem_cv.notify_all();
  11453. /* Wait for all the credits to be consumed. */
  11454. {
  11455. std::unique_lock<std::mutex> lock(sem_mtx);
  11456. while (credits > 0) {
  11457. sem_cv.wait(lock);
  11458. }
  11459. }
  11460. /* Check that we are able again to enqueue at least qlimit tasks. */
  11461. for (unsigned int i = 0; i < qlimit; i++) {
  11462. queued = task_queue->enqueue([] {});
  11463. EXPECT_TRUE(queued);
  11464. }
  11465. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11466. task_queue->shutdown();
  11467. #else
  11468. EXPECT_NO_THROW(task_queue->shutdown());
  11469. #endif
  11470. }
  11471. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11472. Server svr;
  11473. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11474. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11475. });
  11476. svr.Get("/hello", [](const Request &req, Response &res) {
  11477. res.set_content(req.get_param_value("key"), "text/plain");
  11478. });
  11479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11480. auto se = detail::scope_exit([&] {
  11481. svr.stop();
  11482. thread.join();
  11483. ASSERT_FALSE(svr.is_running());
  11484. });
  11485. svr.wait_until_ready();
  11486. {
  11487. Client cli(HOST, PORT);
  11488. cli.set_follow_location(true);
  11489. auto res = cli.Get("/");
  11490. ASSERT_TRUE(res);
  11491. EXPECT_EQ(StatusCode::OK_200, res->status);
  11492. EXPECT_EQ("val&key2=val2", res->body);
  11493. }
  11494. }
  11495. #endif
  11496. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11497. Server svr;
  11498. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11499. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11500. });
  11501. svr.Get("/hello", [](const Request &req, Response &res) {
  11502. res.set_content(req.get_param_value("key"), "text/plain");
  11503. });
  11504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11505. auto se = detail::scope_exit([&] {
  11506. svr.stop();
  11507. thread.join();
  11508. ASSERT_FALSE(svr.is_running());
  11509. });
  11510. svr.wait_until_ready();
  11511. {
  11512. Client cli(HOST, PORT);
  11513. cli.set_follow_location(true);
  11514. auto res = cli.Get("/");
  11515. ASSERT_TRUE(res);
  11516. EXPECT_EQ(StatusCode::OK_200, res->status);
  11517. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11518. }
  11519. }
  11520. TEST(RedirectTest, RedirectWithPlusInPath) {
  11521. Server svr;
  11522. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11523. res.set_redirect("/a+b");
  11524. });
  11525. // Route pattern uses regex; escape + as \\+
  11526. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11527. res.set_content(req.path, "text/plain");
  11528. });
  11529. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11530. auto se = detail::scope_exit([&] {
  11531. svr.stop();
  11532. thread.join();
  11533. ASSERT_FALSE(svr.is_running());
  11534. });
  11535. svr.wait_until_ready();
  11536. {
  11537. Client cli(HOST, PORT);
  11538. cli.set_follow_location(true);
  11539. auto res = cli.Get("/");
  11540. ASSERT_TRUE(res);
  11541. EXPECT_EQ(StatusCode::OK_200, res->status);
  11542. EXPECT_EQ("/a+b", res->body);
  11543. }
  11544. }
  11545. #ifdef CPPHTTPLIB_SSL_ENABLED
  11546. TEST(RedirectTest, Issue2185_Online) {
  11547. SSLClient client("github.com");
  11548. client.set_follow_location(true);
  11549. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11550. "Coollab-Windows.zip");
  11551. ASSERT_TRUE(res);
  11552. EXPECT_EQ(StatusCode::OK_200, res->status);
  11553. EXPECT_EQ(9920427U, res->body.size());
  11554. }
  11555. #endif
  11556. TEST(VulnerabilityTest, CRLFInjection) {
  11557. Server svr;
  11558. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11559. res.set_content("Hello 1", "text/plain");
  11560. });
  11561. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11562. res.set_content("Hello 2", "text/plain");
  11563. });
  11564. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11565. res.set_content("Hello 3", "text/plain");
  11566. });
  11567. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11568. res.set_content("Hello 4", "text/plain");
  11569. });
  11570. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11571. for (const auto &x : req.headers) {
  11572. auto key = x.first;
  11573. EXPECT_STRNE("evil", key.c_str());
  11574. }
  11575. });
  11576. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11577. auto se = detail::scope_exit([&] {
  11578. svr.stop();
  11579. thread.join();
  11580. ASSERT_FALSE(svr.is_running());
  11581. });
  11582. svr.wait_until_ready();
  11583. {
  11584. Client cli(HOST, PORT);
  11585. cli.Post("/test1", "A=B",
  11586. "application/x-www-form-urlencoded\r\nevil: hello1");
  11587. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11588. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11589. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11590. }
  11591. }
  11592. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11593. auto server_thread = std::thread([] {
  11594. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11595. default_socket_options(srv);
  11596. sockaddr_in addr{};
  11597. addr.sin_family = AF_INET;
  11598. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11599. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11600. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11601. ::listen(srv, 1);
  11602. sockaddr_in cli_addr{};
  11603. socklen_t cli_len = sizeof(cli_addr);
  11604. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11605. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11606. std::string buf_all;
  11607. char buf[2048];
  11608. ssize_t n;
  11609. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11610. buf_all.append(buf, static_cast<size_t>(n));
  11611. size_t pos;
  11612. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11613. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11614. auto e = request_block.find("\r\n");
  11615. if (e != std::string::npos) {
  11616. auto request_line = request_block.substr(0, e);
  11617. std::string msg =
  11618. "CRLF injection detected in request line: '" + request_line + "'";
  11619. EXPECT_FALSE(true) << msg;
  11620. }
  11621. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11622. ::send(cli,
  11623. #ifdef _WIN32
  11624. static_cast<const char *>(resp.c_str()),
  11625. static_cast<int>(resp.size()),
  11626. #else
  11627. resp.c_str(), resp.size(),
  11628. #endif
  11629. 0);
  11630. buf_all.erase(0, pos + 4);
  11631. }
  11632. }
  11633. detail::close_socket(cli);
  11634. detail::close_socket(srv);
  11635. });
  11636. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11637. auto cli = Client("127.0.0.1", PORT + 1);
  11638. auto headers = Headers{
  11639. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11640. {"Connection", "keep-alive"}};
  11641. auto res = cli.Get("/hi", headers);
  11642. EXPECT_FALSE(res);
  11643. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11644. server_thread.join();
  11645. }
  11646. TEST(PathParamsTest, StaticMatch) {
  11647. const auto pattern = "/users/all";
  11648. detail::PathParamsMatcher matcher(pattern);
  11649. Request request;
  11650. request.path = "/users/all";
  11651. ASSERT_TRUE(matcher.match(request));
  11652. std::unordered_map<std::string, std::string> expected_params = {};
  11653. EXPECT_EQ(request.path_params, expected_params);
  11654. }
  11655. TEST(PathParamsTest, StaticMismatch) {
  11656. const auto pattern = "/users/all";
  11657. detail::PathParamsMatcher matcher(pattern);
  11658. Request request;
  11659. request.path = "/users/1";
  11660. ASSERT_FALSE(matcher.match(request));
  11661. }
  11662. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11663. const auto pattern = "/users/:id/subscriptions";
  11664. detail::PathParamsMatcher matcher(pattern);
  11665. Request request;
  11666. request.path = "/users/42/subscriptions";
  11667. ASSERT_TRUE(matcher.match(request));
  11668. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11669. EXPECT_EQ(request.path_params, expected_params);
  11670. }
  11671. TEST(PathParamsTest, SingleParamInTheEnd) {
  11672. const auto pattern = "/users/:id";
  11673. detail::PathParamsMatcher matcher(pattern);
  11674. Request request;
  11675. request.path = "/users/24";
  11676. ASSERT_TRUE(matcher.match(request));
  11677. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11678. EXPECT_EQ(request.path_params, expected_params);
  11679. }
  11680. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11681. const auto pattern = "/users/:id/";
  11682. detail::PathParamsMatcher matcher(pattern);
  11683. Request request;
  11684. request.path = "/users/42/";
  11685. ASSERT_TRUE(matcher.match(request));
  11686. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11687. EXPECT_EQ(request.path_params, expected_params);
  11688. }
  11689. TEST(PathParamsTest, EmptyParam) {
  11690. const auto pattern = "/users/:id/";
  11691. detail::PathParamsMatcher matcher(pattern);
  11692. Request request;
  11693. request.path = "/users//";
  11694. ASSERT_TRUE(matcher.match(request));
  11695. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11696. EXPECT_EQ(request.path_params, expected_params);
  11697. }
  11698. TEST(PathParamsTest, FragmentMismatch) {
  11699. const auto pattern = "/users/:id/";
  11700. detail::PathParamsMatcher matcher(pattern);
  11701. Request request;
  11702. request.path = "/admins/24/";
  11703. ASSERT_FALSE(matcher.match(request));
  11704. }
  11705. TEST(PathParamsTest, ExtraFragments) {
  11706. const auto pattern = "/users/:id";
  11707. detail::PathParamsMatcher matcher(pattern);
  11708. Request request;
  11709. request.path = "/users/42/subscriptions";
  11710. ASSERT_FALSE(matcher.match(request));
  11711. }
  11712. TEST(PathParamsTest, MissingTrailingParam) {
  11713. const auto pattern = "/users/:id";
  11714. detail::PathParamsMatcher matcher(pattern);
  11715. Request request;
  11716. request.path = "/users";
  11717. ASSERT_FALSE(matcher.match(request));
  11718. }
  11719. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11720. const auto pattern = "/users/:id/subscriptions";
  11721. detail::PathParamsMatcher matcher(pattern);
  11722. Request request;
  11723. request.path = "/users/subscriptions";
  11724. ASSERT_FALSE(matcher.match(request));
  11725. }
  11726. TEST(PathParamsTest, MultipleParams) {
  11727. const auto pattern = "/users/:userid/subscriptions/:subid";
  11728. detail::PathParamsMatcher matcher(pattern);
  11729. Request request;
  11730. request.path = "/users/42/subscriptions/2";
  11731. ASSERT_TRUE(matcher.match(request));
  11732. std::unordered_map<std::string, std::string> expected_params = {
  11733. {"userid", "42"}, {"subid", "2"}};
  11734. EXPECT_EQ(request.path_params, expected_params);
  11735. }
  11736. TEST(PathParamsTest, SequenceOfParams) {
  11737. const auto pattern = "/values/:x/:y/:z";
  11738. detail::PathParamsMatcher matcher(pattern);
  11739. Request request;
  11740. request.path = "/values/1/2/3";
  11741. ASSERT_TRUE(matcher.match(request));
  11742. std::unordered_map<std::string, std::string> expected_params = {
  11743. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11744. EXPECT_EQ(request.path_params, expected_params);
  11745. }
  11746. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11747. const auto pattern = "/prefix:suffix";
  11748. detail::PathParamsMatcher matcher(pattern);
  11749. Request request;
  11750. request.path = "/prefix:suffix";
  11751. ASSERT_TRUE(matcher.match(request));
  11752. const std::unordered_map<std::string, std::string> expected_params = {};
  11753. EXPECT_EQ(request.path_params, expected_params);
  11754. }
  11755. TEST(ParseUrlTest, VariousPatterns) {
  11756. {
  11757. detail::UrlComponents uc;
  11758. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11759. EXPECT_EQ("http", uc.scheme);
  11760. EXPECT_EQ("example.com", uc.host);
  11761. EXPECT_EQ("8080", uc.port);
  11762. EXPECT_EQ("/path", uc.path);
  11763. EXPECT_EQ("?q=1", uc.query);
  11764. }
  11765. {
  11766. detail::UrlComponents uc;
  11767. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11768. EXPECT_EQ("https", uc.scheme);
  11769. EXPECT_EQ("example.com", uc.host);
  11770. EXPECT_TRUE(uc.port.empty());
  11771. EXPECT_EQ("/path", uc.path);
  11772. }
  11773. {
  11774. detail::UrlComponents uc;
  11775. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11776. EXPECT_EQ("::1", uc.host);
  11777. EXPECT_EQ("8080", uc.port);
  11778. EXPECT_EQ("/path", uc.path);
  11779. }
  11780. {
  11781. detail::UrlComponents uc;
  11782. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11783. }
  11784. {
  11785. detail::UrlComponents uc;
  11786. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11787. EXPECT_TRUE(uc.scheme.empty());
  11788. EXPECT_EQ("example.com", uc.host);
  11789. EXPECT_EQ("/path", uc.path);
  11790. EXPECT_EQ("?q=1", uc.query);
  11791. }
  11792. {
  11793. detail::UrlComponents uc;
  11794. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11795. EXPECT_TRUE(uc.host.empty());
  11796. EXPECT_EQ("/path", uc.path);
  11797. EXPECT_EQ("?q=1", uc.query);
  11798. }
  11799. {
  11800. detail::UrlComponents uc;
  11801. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11802. EXPECT_EQ("example.com", uc.host);
  11803. EXPECT_EQ("8080", uc.port);
  11804. }
  11805. {
  11806. // Unix socket path — must not be parsed as host
  11807. detail::UrlComponents uc;
  11808. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11809. EXPECT_TRUE(uc.host.empty());
  11810. }
  11811. {
  11812. detail::UrlComponents uc;
  11813. ASSERT_TRUE(detail::parse_url("", uc));
  11814. EXPECT_TRUE(uc.host.empty());
  11815. EXPECT_TRUE(uc.path.empty());
  11816. }
  11817. {
  11818. detail::UrlComponents uc;
  11819. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11820. }
  11821. {
  11822. detail::UrlComponents uc;
  11823. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11824. }
  11825. {
  11826. // Accepted by parse_url; callers restrict to http/https
  11827. detail::UrlComponents uc;
  11828. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11829. EXPECT_EQ("ftp", uc.scheme);
  11830. }
  11831. {
  11832. detail::UrlComponents uc;
  11833. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11834. }
  11835. {
  11836. detail::UrlComponents uc;
  11837. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11838. }
  11839. }
  11840. TEST(ParseUrlTest, FragmentHandling) {
  11841. {
  11842. detail::UrlComponents uc;
  11843. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11844. EXPECT_EQ("/path", uc.path);
  11845. EXPECT_TRUE(uc.query.empty());
  11846. }
  11847. {
  11848. detail::UrlComponents uc;
  11849. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11850. EXPECT_TRUE(uc.path.empty());
  11851. EXPECT_TRUE(uc.query.empty());
  11852. }
  11853. }
  11854. TEST(ParseUrlTest, UserinfoHandling) {
  11855. // Userinfo with @ but no colon — host includes @
  11856. detail::UrlComponents uc;
  11857. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11858. EXPECT_EQ("user@host.com", uc.host);
  11859. EXPECT_EQ("/path", uc.path);
  11860. }
  11861. TEST(ParseUrlTest, IPv6EdgeCases) {
  11862. {
  11863. detail::UrlComponents uc;
  11864. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11865. EXPECT_TRUE(uc.scheme.empty());
  11866. EXPECT_EQ("::1", uc.host);
  11867. EXPECT_EQ("8080", uc.port);
  11868. }
  11869. {
  11870. // Zone ID '%25' is not in [a-fA-F0-9:]
  11871. detail::UrlComponents uc;
  11872. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11873. }
  11874. }
  11875. TEST(ParseUrlTest, SchemeEdgeCases) {
  11876. {
  11877. detail::UrlComponents uc;
  11878. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11879. }
  11880. {
  11881. detail::UrlComponents uc;
  11882. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11883. }
  11884. {
  11885. detail::UrlComponents uc;
  11886. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11887. }
  11888. }
  11889. TEST(ParseUrlTest, PortEdgeCases) {
  11890. {
  11891. detail::UrlComponents uc;
  11892. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11893. EXPECT_TRUE(uc.port.empty());
  11894. EXPECT_EQ("/path", uc.path);
  11895. }
  11896. {
  11897. // parse_url accepts any port string; validation is done by parse_port
  11898. detail::UrlComponents uc;
  11899. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11900. EXPECT_EQ("abc", uc.port);
  11901. }
  11902. }
  11903. TEST(ParseUrlTest, WebSocketPatterns) {
  11904. {
  11905. detail::UrlComponents uc;
  11906. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11907. EXPECT_EQ("ws", uc.scheme);
  11908. EXPECT_EQ("echo.example.com", uc.host);
  11909. EXPECT_EQ("8080", uc.port);
  11910. EXPECT_EQ("/ws", uc.path);
  11911. }
  11912. {
  11913. detail::UrlComponents uc;
  11914. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11915. EXPECT_EQ("wss", uc.scheme);
  11916. EXPECT_EQ("echo.example.com", uc.host);
  11917. EXPECT_TRUE(uc.port.empty());
  11918. EXPECT_EQ("/ws", uc.path);
  11919. }
  11920. }
  11921. TEST(ParseUrlTest, QueryOnly) {
  11922. detail::UrlComponents uc;
  11923. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11924. EXPECT_TRUE(uc.host.empty());
  11925. EXPECT_TRUE(uc.path.empty());
  11926. EXPECT_EQ("?q=1&r=2", uc.query);
  11927. }
  11928. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11929. detail::UrlComponents uc;
  11930. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11931. EXPECT_TRUE(uc.scheme.empty());
  11932. EXPECT_EQ("example.com", uc.host);
  11933. EXPECT_EQ("443", uc.port);
  11934. EXPECT_EQ("/path", uc.path);
  11935. }
  11936. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11937. // If ipv6 regex working, regex match codepath is taken.
  11938. // else port will default to 80 in Client impl
  11939. int clientImplMagicPort = 80;
  11940. int port = 4321;
  11941. // above ports must be different to avoid false negative
  11942. EXPECT_NE(clientImplMagicPort, port);
  11943. std::string ipV6TestURL = "http://[ff06::c3]";
  11944. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11945. CLIENT_PRIVATE_KEY_FILE);
  11946. EXPECT_EQ(cli.port(), port);
  11947. }
  11948. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11949. auto file_path = "./www/dir/index.html";
  11950. auto dir_path = "./www/dir";
  11951. detail::FileStat stat_file(file_path);
  11952. EXPECT_TRUE(stat_file.is_file());
  11953. EXPECT_FALSE(stat_file.is_dir());
  11954. detail::FileStat stat_dir(dir_path);
  11955. EXPECT_FALSE(stat_dir.is_file());
  11956. EXPECT_TRUE(stat_dir.is_dir());
  11957. }
  11958. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11959. // IPv4 with default HTTP port (80)
  11960. EXPECT_EQ("example.com",
  11961. detail::make_host_and_port_string("example.com", 80, false));
  11962. // IPv4 with default HTTPS port (443)
  11963. EXPECT_EQ("example.com",
  11964. detail::make_host_and_port_string("example.com", 443, true));
  11965. // IPv4 with non-default HTTP port
  11966. EXPECT_EQ("example.com:8080",
  11967. detail::make_host_and_port_string("example.com", 8080, false));
  11968. // IPv4 with non-default HTTPS port
  11969. EXPECT_EQ("example.com:8443",
  11970. detail::make_host_and_port_string("example.com", 8443, true));
  11971. // IPv6 with default HTTP port (80)
  11972. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11973. // IPv6 with default HTTPS port (443)
  11974. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11975. // IPv6 with non-default HTTP port
  11976. EXPECT_EQ("[::1]:8080",
  11977. detail::make_host_and_port_string("::1", 8080, false));
  11978. // IPv6 with non-default HTTPS port
  11979. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11980. // IPv6 full address with default port
  11981. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11982. detail::make_host_and_port_string(
  11983. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11984. // IPv6 full address with non-default port
  11985. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11986. detail::make_host_and_port_string(
  11987. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11988. // IPv6 localhost with non-default port
  11989. EXPECT_EQ("[::1]:3000",
  11990. detail::make_host_and_port_string("::1", 3000, false));
  11991. // IPv6 with zone ID (link-local address) with default port
  11992. EXPECT_EQ("[fe80::1%eth0]",
  11993. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11994. // IPv6 with zone ID (link-local address) with non-default port
  11995. EXPECT_EQ("[fe80::1%eth0]:8080",
  11996. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11997. // Edge case: Port 443 with is_ssl=false (should add port)
  11998. EXPECT_EQ("example.com:443",
  11999. detail::make_host_and_port_string("example.com", 443, false));
  12000. // Edge case: Port 80 with is_ssl=true (should add port)
  12001. EXPECT_EQ("example.com:80",
  12002. detail::make_host_and_port_string("example.com", 80, true));
  12003. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12004. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12005. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12006. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12007. // Security fix: Already bracketed IPv6 should not get double brackets
  12008. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12009. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12010. EXPECT_EQ("[::1]:8080",
  12011. detail::make_host_and_port_string("[::1]", 8080, false));
  12012. EXPECT_EQ("[2001:db8::1]:8080",
  12013. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12014. EXPECT_EQ("[fe80::1%eth0]",
  12015. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12016. EXPECT_EQ("[fe80::1%eth0]:8080",
  12017. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12018. // Edge case: Empty host (should return as-is)
  12019. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12020. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12021. // This is a known limitation but shouldn't crash
  12022. EXPECT_EQ("[host:name]",
  12023. detail::make_host_and_port_string("host:name", 80, false));
  12024. // Port number edge cases (no validation, but should not crash)
  12025. EXPECT_EQ("example.com:0",
  12026. detail::make_host_and_port_string("example.com", 0, false));
  12027. EXPECT_EQ("example.com:-1",
  12028. detail::make_host_and_port_string("example.com", -1, false));
  12029. EXPECT_EQ("example.com:65535",
  12030. detail::make_host_and_port_string("example.com", 65535, false));
  12031. EXPECT_EQ("example.com:65536",
  12032. detail::make_host_and_port_string("example.com", 65536, false));
  12033. }
  12034. #ifdef CPPHTTPLIB_SSL_ENABLED
  12035. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12036. httplib::SSLClient cli("roblox.com", 443);
  12037. cli.set_follow_location(true);
  12038. auto res = cli.Get("/");
  12039. ASSERT_TRUE(res);
  12040. EXPECT_EQ(StatusCode::OK_200, res->status);
  12041. }
  12042. #endif
  12043. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12044. Server svr;
  12045. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12046. EXPECT_EQ(res.status, 400);
  12047. });
  12048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12049. auto se = detail::scope_exit([&] {
  12050. svr.stop();
  12051. thread.join();
  12052. ASSERT_FALSE(svr.is_running());
  12053. });
  12054. svr.wait_until_ready();
  12055. Client cli(HOST, PORT);
  12056. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12057. }
  12058. TEST(InvalidHeaderCharsTest, is_field_name) {
  12059. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12060. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12061. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12062. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12063. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12064. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12065. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12066. EXPECT_FALSE(detail::fields::is_field_name(""));
  12067. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12068. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12069. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12070. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12071. }
  12072. TEST(InvalidHeaderCharsTest, is_field_value) {
  12073. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12074. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12075. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12076. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12077. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12078. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12079. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12080. EXPECT_TRUE(detail::fields::is_field_value(""));
  12081. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12082. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12083. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12084. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12085. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12086. }
  12087. TEST(InvalidHeaderCharsTest, OnServer) {
  12088. Server svr;
  12089. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12090. std::string header = "Not Set";
  12091. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12092. res.set_header(header, "value");
  12093. res.set_content("Page Content Page Content", "text/plain");
  12094. });
  12095. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12096. std::string header = "Not Set";
  12097. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12098. res.set_header("X-Test", header);
  12099. res.set_content("Page Content Page Content", "text/plain");
  12100. });
  12101. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12102. auto se = detail::scope_exit([&] {
  12103. svr.stop();
  12104. thread.join();
  12105. ASSERT_FALSE(svr.is_running());
  12106. });
  12107. svr.wait_until_ready();
  12108. Client cli(HOST, PORT);
  12109. {
  12110. auto res = cli.Get(
  12111. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12112. ASSERT_TRUE(res);
  12113. EXPECT_EQ("Page Content Page Content", res->body);
  12114. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12115. }
  12116. {
  12117. auto res = cli.Get(
  12118. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12119. ASSERT_TRUE(res);
  12120. EXPECT_EQ("Page Content Page Content", res->body);
  12121. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12122. }
  12123. }
  12124. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12125. auto handled = false;
  12126. Server svr;
  12127. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12128. thread t = thread([&] { svr.listen(HOST, PORT); });
  12129. auto se = detail::scope_exit([&] {
  12130. svr.stop();
  12131. t.join();
  12132. ASSERT_FALSE(svr.is_running());
  12133. ASSERT_FALSE(handled);
  12134. });
  12135. svr.wait_until_ready();
  12136. auto req = "POST /test HTTP/1.1\r\n"
  12137. "Content-Length: x\r\n"
  12138. "\r\n";
  12139. std::string response;
  12140. ASSERT_TRUE(send_request(1, req, &response));
  12141. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12142. response.substr(0, response.find("\r\n")));
  12143. }
  12144. #ifndef _WIN32
  12145. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12146. static constexpr char reject[] = "Unauthorized";
  12147. static constexpr char accept[] = "Upload accepted";
  12148. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12149. Server svr;
  12150. svr.set_expect_100_continue_handler(
  12151. [](const Request & /*req*/, Response &res) {
  12152. res.status = StatusCode::Unauthorized_401;
  12153. res.set_content(reject, "text/plain");
  12154. return res.status;
  12155. });
  12156. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12157. res.set_content(accept, "text/plain");
  12158. });
  12159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. thread.join();
  12163. ASSERT_FALSE(svr.is_running());
  12164. });
  12165. svr.wait_until_ready();
  12166. {
  12167. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12168. curl_easy_init(), &curl_easy_cleanup};
  12169. ASSERT_NE(curl, nullptr);
  12170. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12171. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12172. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12173. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12174. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12175. &curl_slist_free_all};
  12176. ASSERT_NE(list, nullptr);
  12177. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12178. struct read_data {
  12179. size_t read_size;
  12180. size_t total_size;
  12181. } data = {0, total_size};
  12182. using read_callback_t =
  12183. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12184. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12185. void *userdata) -> size_t {
  12186. read_data *d = (read_data *)userdata;
  12187. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12188. std::fill_n(ptr, size * nmemb, 'A');
  12189. d->read_size += size * nmemb;
  12190. return size * nmemb;
  12191. };
  12192. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12193. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12194. std::vector<char> buffer;
  12195. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12196. using write_callback_t =
  12197. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12198. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12199. void *userdata) -> size_t {
  12200. std::vector<char> *buf = (std::vector<char> *)userdata;
  12201. buf->reserve(buf->size() + size * nmemb + 1);
  12202. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12203. return size * nmemb;
  12204. };
  12205. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12206. {
  12207. const auto res = curl_easy_perform(curl.get());
  12208. ASSERT_EQ(res, CURLE_OK);
  12209. }
  12210. {
  12211. auto response_code = long{};
  12212. const auto res =
  12213. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12214. ASSERT_EQ(res, CURLE_OK);
  12215. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12216. }
  12217. {
  12218. auto dl = curl_off_t{};
  12219. const auto res =
  12220. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12221. ASSERT_EQ(res, CURLE_OK);
  12222. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12223. }
  12224. {
  12225. buffer.push_back('\0');
  12226. ASSERT_STRCASEEQ(buffer.data(), reject);
  12227. }
  12228. }
  12229. }
  12230. #endif
  12231. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12232. // Regression test for #2458.
  12233. //
  12234. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12235. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12236. // ticket can make the client socket spuriously readable during the
  12237. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12238. // the client withholds the body and then blocks reading a response that never
  12239. // comes, failing with `Failed to read connection`.
  12240. //
  12241. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12242. // within the timeout. This raw OpenSSL server deliberately never sends
  12243. // `100 Continue`; the client must still deliver the body and receive 200.
  12244. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12245. signal(SIGPIPE, SIG_IGN);
  12246. const auto port = PORT + 4;
  12247. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12248. ASSERT_NE(srv, INVALID_SOCKET);
  12249. int opt = 1;
  12250. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12251. sockaddr_in addr{};
  12252. addr.sin_family = AF_INET;
  12253. addr.sin_port = htons(static_cast<uint16_t>(port));
  12254. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12255. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12256. ASSERT_EQ(0, ::listen(srv, 1));
  12257. std::atomic<size_t> server_body_bytes{0};
  12258. auto server_thread = std::thread([&] {
  12259. sockaddr_in cli_addr{};
  12260. socklen_t cli_len = sizeof(cli_addr);
  12261. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12262. if (cli == INVALID_SOCKET) { return; }
  12263. // Bound the lifetime of the server side so a buggy client (which never
  12264. // sends the body) cannot make this thread block forever on join.
  12265. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12266. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12267. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12268. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12269. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12270. SSL *ssl = SSL_new(ctx);
  12271. SSL_set_fd(ssl, static_cast<int>(cli));
  12272. if (SSL_accept(ssl) > 0) {
  12273. // Read the request headers. Reading here also flushes the TLS 1.3
  12274. // session tickets to the client. Deliberately do NOT send
  12275. // `100 Continue`.
  12276. std::string buf;
  12277. char tmp[1024];
  12278. while (buf.find("\r\n\r\n") == std::string::npos) {
  12279. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12280. if (n <= 0) { break; }
  12281. buf.append(tmp, static_cast<size_t>(n));
  12282. }
  12283. // A correct client sends the body now; count what arrives.
  12284. auto pos = buf.find("\r\n\r\n");
  12285. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12286. while (body < 4096) {
  12287. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12288. if (n <= 0) { break; }
  12289. body += static_cast<size_t>(n);
  12290. }
  12291. server_body_bytes = body;
  12292. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12293. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12294. SSL_shutdown(ssl);
  12295. }
  12296. SSL_free(ssl);
  12297. detail::close_socket(cli);
  12298. SSL_CTX_free(ctx);
  12299. });
  12300. auto se = detail::scope_exit([&] {
  12301. server_thread.join();
  12302. detail::close_socket(srv);
  12303. });
  12304. SSLClient cli("127.0.0.1", port);
  12305. cli.enable_server_certificate_verification(false);
  12306. cli.set_connection_timeout(5, 0);
  12307. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12308. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12309. std::string body(4096, 'A');
  12310. auto res = cli.Put("/api/test", body, "application/json");
  12311. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12312. EXPECT_EQ(StatusCode::OK_200, res->status);
  12313. EXPECT_EQ(body.size(), server_body_bytes.load());
  12314. }
  12315. #endif
  12316. template <typename S, typename C>
  12317. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12318. svr.Get("/stream", [&](const Request &, Response &res) {
  12319. auto data = new std::string("01234567890123456789");
  12320. res.set_content_provider(
  12321. data->size(), "text/plain",
  12322. [&, data](size_t offset, size_t length, DataSink &sink) {
  12323. const size_t DATA_CHUNK_SIZE = 4;
  12324. const auto &d = *data;
  12325. std::this_thread::sleep_for(std::chrono::seconds(1));
  12326. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12327. return true;
  12328. },
  12329. [data](bool success) {
  12330. EXPECT_FALSE(success);
  12331. delete data;
  12332. });
  12333. });
  12334. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12335. auto i = new size_t(0);
  12336. res.set_content_provider(
  12337. "text/plain",
  12338. [i](size_t, DataSink &sink) {
  12339. if (*i < 5) {
  12340. std::this_thread::sleep_for(std::chrono::seconds(1));
  12341. sink.write("abcd", 4);
  12342. (*i)++;
  12343. } else {
  12344. sink.done();
  12345. }
  12346. return true;
  12347. },
  12348. [i](bool success) {
  12349. EXPECT_FALSE(success);
  12350. delete i;
  12351. });
  12352. });
  12353. svr.Get("/chunked", [&](const Request &, Response &res) {
  12354. auto i = new size_t(0);
  12355. res.set_chunked_content_provider(
  12356. "text/plain",
  12357. [i](size_t, DataSink &sink) {
  12358. if (*i < 5) {
  12359. std::this_thread::sleep_for(std::chrono::seconds(1));
  12360. sink.os << "abcd";
  12361. (*i)++;
  12362. } else {
  12363. sink.done();
  12364. }
  12365. return true;
  12366. },
  12367. [i](bool success) {
  12368. EXPECT_FALSE(success);
  12369. delete i;
  12370. });
  12371. });
  12372. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12373. auto se = detail::scope_exit([&] {
  12374. svr.stop();
  12375. listen_thread.join();
  12376. ASSERT_FALSE(svr.is_running());
  12377. });
  12378. svr.wait_until_ready();
  12379. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12380. {
  12381. auto start = std::chrono::steady_clock::now();
  12382. auto res = cli.Get("/stream");
  12383. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12384. std::chrono::steady_clock::now() - start)
  12385. .count();
  12386. ASSERT_FALSE(res);
  12387. EXPECT_EQ(Error::Read, res.error());
  12388. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12389. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12390. }
  12391. {
  12392. auto start = std::chrono::steady_clock::now();
  12393. auto res = cli.Get("/stream_without_length");
  12394. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12395. std::chrono::steady_clock::now() - start)
  12396. .count();
  12397. ASSERT_FALSE(res);
  12398. EXPECT_EQ(Error::Read, res.error());
  12399. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12400. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12401. }
  12402. {
  12403. auto start = std::chrono::steady_clock::now();
  12404. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12405. EXPECT_EQ("abcd", string(data, data_length));
  12406. return true;
  12407. });
  12408. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12409. std::chrono::steady_clock::now() - start)
  12410. .count();
  12411. ASSERT_FALSE(res);
  12412. EXPECT_EQ(Error::Read, res.error());
  12413. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12414. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12415. }
  12416. }
  12417. TEST(MaxTimeoutTest, ContentStream) {
  12418. time_t timeout = 2000;
  12419. time_t threshold = 200;
  12420. Server svr;
  12421. Client cli("localhost", PORT);
  12422. max_timeout_test(svr, cli, timeout, threshold);
  12423. }
  12424. #ifdef CPPHTTPLIB_SSL_ENABLED
  12425. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12426. time_t timeout = 2000;
  12427. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12428. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12429. SSLClient cli("localhost", PORT);
  12430. cli.enable_server_certificate_verification(false);
  12431. max_timeout_test(svr, cli, timeout, threshold);
  12432. }
  12433. #endif
  12434. class EventDispatcher {
  12435. public:
  12436. EventDispatcher() {}
  12437. bool wait_event(DataSink *sink) {
  12438. unique_lock<mutex> lk(m_);
  12439. int id = id_;
  12440. // Wait with timeout to prevent hanging if client disconnects
  12441. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12442. [&] { return cid_ == id; })) {
  12443. return false; // Timeout occurred
  12444. }
  12445. sink->write(message_.data(), message_.size());
  12446. return true;
  12447. }
  12448. void send_event(const string &message) {
  12449. lock_guard<mutex> lk(m_);
  12450. cid_ = id_++;
  12451. message_ = message;
  12452. cv_.notify_all();
  12453. }
  12454. private:
  12455. mutex m_;
  12456. condition_variable cv_;
  12457. atomic_int id_{0};
  12458. atomic_int cid_{-1};
  12459. string message_;
  12460. };
  12461. TEST(ClientInThreadTest, Issue2068) {
  12462. EventDispatcher ed;
  12463. Server svr;
  12464. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12465. res.set_chunked_content_provider("text/event-stream",
  12466. [&](size_t /*offset*/, DataSink &sink) {
  12467. return ed.wait_event(&sink);
  12468. });
  12469. });
  12470. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12471. svr.wait_until_ready();
  12472. thread event_thread([&] {
  12473. int id = 0;
  12474. while (svr.is_running()) {
  12475. this_thread::sleep_for(chrono::milliseconds(500));
  12476. std::stringstream ss;
  12477. ss << "data: " << id << "\n\n";
  12478. ed.send_event(ss.str());
  12479. id++;
  12480. }
  12481. });
  12482. auto se = detail::scope_exit([&] {
  12483. svr.stop();
  12484. listen_thread.join();
  12485. event_thread.join();
  12486. ASSERT_FALSE(svr.is_running());
  12487. });
  12488. {
  12489. auto client = detail::make_unique<Client>(HOST, PORT);
  12490. client->set_read_timeout(std::chrono::minutes(10));
  12491. std::atomic<bool> stop{false};
  12492. std::thread t([&] {
  12493. client->Get("/event1",
  12494. [&](const char *, size_t) -> bool { return !stop; });
  12495. });
  12496. std::this_thread::sleep_for(std::chrono::seconds(2));
  12497. stop = true;
  12498. client->stop();
  12499. t.join();
  12500. // Reset client after thread has finished
  12501. client.reset();
  12502. }
  12503. }
  12504. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12505. auto handled = false;
  12506. Server svr;
  12507. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12508. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12509. auto se = detail::scope_exit([&] {
  12510. svr.stop();
  12511. t.join();
  12512. ASSERT_FALSE(svr.is_running());
  12513. ASSERT_FALSE(handled);
  12514. });
  12515. svr.wait_until_ready();
  12516. // Two Content-Length headers with different values — must be rejected
  12517. auto req = "POST /test HTTP/1.1\r\n"
  12518. "Content-Length: 5\r\n"
  12519. "Content-Length: 10\r\n"
  12520. "\r\n"
  12521. "hello";
  12522. std::string response;
  12523. ASSERT_TRUE(send_request(1, req, &response));
  12524. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12525. response.substr(0, response.find("\r\n")));
  12526. }
  12527. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12528. auto handled = false;
  12529. Server svr;
  12530. svr.Post("/test", [&](const Request &, Response &res) {
  12531. handled = true;
  12532. res.set_content("ok", "text/plain");
  12533. });
  12534. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12535. auto se = detail::scope_exit([&] {
  12536. svr.stop();
  12537. t.join();
  12538. ASSERT_FALSE(svr.is_running());
  12539. ASSERT_TRUE(handled);
  12540. });
  12541. svr.wait_until_ready();
  12542. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12543. auto req = "POST /test HTTP/1.1\r\n"
  12544. "Content-Length: 5\r\n"
  12545. "Content-Length: 5\r\n"
  12546. "\r\n"
  12547. "hello";
  12548. std::string response;
  12549. ASSERT_TRUE(send_request(1, req, &response));
  12550. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12551. }
  12552. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12553. Server svr;
  12554. svr.Get("/", [](const Request &req, Response &res) {
  12555. EXPECT_EQ(2U, req.trailers.size());
  12556. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12557. // Denied
  12558. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12559. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12560. // Accepted
  12561. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12562. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12563. EXPECT_TRUE(req.has_trailer("X-World"));
  12564. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12565. res.set_content("ok", "text/plain");
  12566. });
  12567. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12568. auto se = detail::scope_exit([&] {
  12569. svr.stop();
  12570. t.join();
  12571. ASSERT_FALSE(svr.is_running());
  12572. });
  12573. svr.wait_until_ready();
  12574. const std::string req = "GET / HTTP/1.1\r\n"
  12575. "Transfer-Encoding: chunked\r\n"
  12576. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12577. "\r\n"
  12578. "0\r\n"
  12579. "Content-Length: 10\r\n"
  12580. "Host: internal.local\r\n"
  12581. "Content-Type: malicious/content\r\n"
  12582. "Cookie: any\r\n"
  12583. "Set-Cookie: any\r\n"
  12584. "X-Forwarded-For: attacker.com\r\n"
  12585. "X-Real-Ip: 1.1.1.1\r\n"
  12586. "X-Hello: hello\r\n"
  12587. "X-World: world\r\n"
  12588. "\r\n";
  12589. std::string res;
  12590. ASSERT_TRUE(send_request(1, req, &res));
  12591. }
  12592. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12593. Server svr;
  12594. std::string observed_remote_addr;
  12595. std::string observed_xff;
  12596. svr.Get("/ip", [&](const Request &req, Response &res) {
  12597. observed_remote_addr = req.remote_addr;
  12598. observed_xff = req.get_header_value("X-Forwarded-For");
  12599. res.set_content("ok", "text/plain");
  12600. });
  12601. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12602. auto se = detail::scope_exit([&] {
  12603. svr.stop();
  12604. t.join();
  12605. ASSERT_FALSE(svr.is_running());
  12606. });
  12607. svr.wait_until_ready();
  12608. Client cli(HOST, PORT);
  12609. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12610. ASSERT_TRUE(res);
  12611. EXPECT_EQ(StatusCode::OK_200, res->status);
  12612. EXPECT_EQ(observed_xff, "203.0.113.66");
  12613. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12614. observed_remote_addr == "127.0.0.1");
  12615. }
  12616. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12617. Server svr;
  12618. svr.set_trusted_proxies({"203.0.113.66"});
  12619. std::string observed_remote_addr;
  12620. std::string observed_xff;
  12621. svr.Get("/ip", [&](const Request &req, Response &res) {
  12622. observed_remote_addr = req.remote_addr;
  12623. observed_xff = req.get_header_value("X-Forwarded-For");
  12624. res.set_content("ok", "text/plain");
  12625. });
  12626. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12627. auto se = detail::scope_exit([&] {
  12628. svr.stop();
  12629. t.join();
  12630. ASSERT_FALSE(svr.is_running());
  12631. });
  12632. svr.wait_until_ready();
  12633. Client cli(HOST, PORT);
  12634. auto res = cli.Get("/ip");
  12635. ASSERT_TRUE(res);
  12636. EXPECT_EQ(StatusCode::OK_200, res->status);
  12637. EXPECT_EQ(observed_xff, "");
  12638. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12639. observed_remote_addr == "127.0.0.1");
  12640. }
  12641. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12642. Server svr;
  12643. svr.set_trusted_proxies({"203.0.113.66"});
  12644. std::string observed_remote_addr;
  12645. std::string observed_xff;
  12646. svr.Get("/ip", [&](const Request &req, Response &res) {
  12647. observed_remote_addr = req.remote_addr;
  12648. observed_xff = req.get_header_value("X-Forwarded-For");
  12649. res.set_content("ok", "text/plain");
  12650. });
  12651. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12652. auto se = detail::scope_exit([&] {
  12653. svr.stop();
  12654. t.join();
  12655. ASSERT_FALSE(svr.is_running());
  12656. });
  12657. svr.wait_until_ready();
  12658. Client cli(HOST, PORT);
  12659. auto res = cli.Get(
  12660. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12661. ASSERT_TRUE(res);
  12662. EXPECT_EQ(StatusCode::OK_200, res->status);
  12663. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12664. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12665. }
  12666. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12667. Server svr;
  12668. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12669. std::string observed_remote_addr;
  12670. std::string observed_xff;
  12671. svr.Get("/ip", [&](const Request &req, Response &res) {
  12672. observed_remote_addr = req.remote_addr;
  12673. observed_xff = req.get_header_value("X-Forwarded-For");
  12674. res.set_content("ok", "text/plain");
  12675. });
  12676. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12677. auto se = detail::scope_exit([&] {
  12678. svr.stop();
  12679. t.join();
  12680. ASSERT_FALSE(svr.is_running());
  12681. });
  12682. svr.wait_until_ready();
  12683. Client cli(HOST, PORT);
  12684. auto res = cli.Get(
  12685. "/ip",
  12686. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12687. ASSERT_TRUE(res);
  12688. EXPECT_EQ(StatusCode::OK_200, res->status);
  12689. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12690. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12691. }
  12692. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12693. Server svr;
  12694. svr.set_trusted_proxies({"192.0.2.45"});
  12695. std::string observed_remote_addr;
  12696. std::string observed_xff;
  12697. svr.Get("/ip", [&](const Request &req, Response &res) {
  12698. observed_remote_addr = req.remote_addr;
  12699. observed_xff = req.get_header_value("X-Forwarded-For");
  12700. res.set_content("ok", "text/plain");
  12701. });
  12702. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12703. auto se = detail::scope_exit([&] {
  12704. svr.stop();
  12705. t.join();
  12706. ASSERT_FALSE(svr.is_running());
  12707. });
  12708. svr.wait_until_ready();
  12709. Client cli(HOST, PORT);
  12710. auto res = cli.Get(
  12711. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12712. ASSERT_TRUE(res);
  12713. EXPECT_EQ(StatusCode::OK_200, res->status);
  12714. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12715. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12716. }
  12717. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12718. Server svr;
  12719. svr.set_trusted_proxies({"192.0.2.45"});
  12720. std::string observed_remote_addr;
  12721. std::string observed_xff;
  12722. svr.Get("/ip", [&](const Request &req, Response &res) {
  12723. observed_remote_addr = req.remote_addr;
  12724. observed_xff = req.get_header_value("X-Forwarded-For");
  12725. res.set_content("ok", "text/plain");
  12726. });
  12727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12728. auto se = detail::scope_exit([&] {
  12729. svr.stop();
  12730. t.join();
  12731. ASSERT_FALSE(svr.is_running());
  12732. });
  12733. svr.wait_until_ready();
  12734. Client cli(HOST, PORT);
  12735. auto res = cli.Get(
  12736. "/ip",
  12737. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12738. ASSERT_TRUE(res);
  12739. EXPECT_EQ(StatusCode::OK_200, res->status);
  12740. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12741. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12742. }
  12743. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12744. Server svr;
  12745. svr.set_trusted_proxies({"192.0.2.45"});
  12746. std::string observed_remote_addr;
  12747. std::string observed_xff;
  12748. svr.Get("/ip", [&](const Request &req, Response &res) {
  12749. observed_remote_addr = req.remote_addr;
  12750. observed_xff = req.get_header_value("X-Forwarded-For");
  12751. res.set_content("ok", "text/plain");
  12752. });
  12753. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12754. auto se = detail::scope_exit([&] {
  12755. svr.stop();
  12756. t.join();
  12757. ASSERT_FALSE(svr.is_running());
  12758. });
  12759. svr.wait_until_ready();
  12760. std::string raw_req =
  12761. "GET /ip HTTP/1.1\r\n"
  12762. "Host: localhost\r\n"
  12763. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12764. "Connection: close\r\n"
  12765. "\r\n";
  12766. std::string out;
  12767. ASSERT_TRUE(send_request(5, raw_req, &out));
  12768. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12769. // Header parser trims surrounding whitespace of the header value
  12770. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12771. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12772. }
  12773. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12774. // crash the server (it used to call front() on an empty vector inside
  12775. // get_client_ip). The connection-level remote address must be retained instead.
  12776. static void run_malformed_xff_test(const std::string &xff_value) {
  12777. Server svr;
  12778. svr.set_trusted_proxies({"192.0.2.45"});
  12779. std::string observed_remote_addr;
  12780. svr.Get("/ip", [&](const Request &req, Response &res) {
  12781. observed_remote_addr = req.remote_addr;
  12782. res.set_content("ok", "text/plain");
  12783. });
  12784. int port = 0;
  12785. thread t = thread([&]() {
  12786. port = svr.bind_to_any_port(HOST);
  12787. svr.listen_after_bind();
  12788. });
  12789. auto se = detail::scope_exit([&] {
  12790. svr.stop();
  12791. t.join();
  12792. ASSERT_FALSE(svr.is_running());
  12793. });
  12794. svr.wait_until_ready();
  12795. Client cli(HOST, port);
  12796. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  12797. ASSERT_TRUE(res);
  12798. EXPECT_EQ(StatusCode::OK_200, res->status);
  12799. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12800. observed_remote_addr == "127.0.0.1");
  12801. }
  12802. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12803. run_malformed_xff_test("");
  12804. }
  12805. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12806. run_malformed_xff_test(",");
  12807. }
  12808. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12809. run_malformed_xff_test(", , ,");
  12810. }
  12811. #ifndef _WIN32
  12812. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12813. Server svr;
  12814. svr.Post("/post", [&](const Request &req, Response &res) {
  12815. res.set_content(req.body, "text/plain");
  12816. });
  12817. svr.Put("/put", [&](const Request &req, Response &res) {
  12818. res.set_content(req.body, "text/plain");
  12819. });
  12820. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12821. res.set_content(req.body, "text/plain");
  12822. });
  12823. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12824. res.set_content(req.body, "text/plain");
  12825. });
  12826. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12827. auto se = detail::scope_exit([&] {
  12828. svr.stop();
  12829. t.join();
  12830. ASSERT_FALSE(svr.is_running());
  12831. });
  12832. svr.wait_until_ready();
  12833. std::string resp;
  12834. // POST without Content-Length
  12835. ASSERT_TRUE(send_request(5,
  12836. "POST /post HTTP/1.1\r\n"
  12837. "Host: localhost\r\n"
  12838. "Connection: close\r\n"
  12839. "\r\n",
  12840. &resp));
  12841. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12842. // PUT without Content-Length
  12843. resp.clear();
  12844. ASSERT_TRUE(send_request(5,
  12845. "PUT /put HTTP/1.1\r\n"
  12846. "Host: localhost\r\n"
  12847. "Connection: close\r\n"
  12848. "\r\n",
  12849. &resp));
  12850. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12851. // PATCH without Content-Length
  12852. resp.clear();
  12853. ASSERT_TRUE(send_request(5,
  12854. "PATCH /patch HTTP/1.1\r\n"
  12855. "Host: localhost\r\n"
  12856. "Connection: close\r\n"
  12857. "\r\n",
  12858. &resp));
  12859. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12860. // DELETE without Content-Length
  12861. resp.clear();
  12862. ASSERT_TRUE(send_request(5,
  12863. "DELETE /delete HTTP/1.1\r\n"
  12864. "Host: localhost\r\n"
  12865. "Connection: close\r\n"
  12866. "\r\n",
  12867. &resp));
  12868. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12869. }
  12870. #endif
  12871. //==============================================================================
  12872. // open_stream() Tests
  12873. //==============================================================================
  12874. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12875. std::string result;
  12876. char buf[8192];
  12877. ssize_t n;
  12878. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12879. result.append(buf, static_cast<size_t>(n));
  12880. }
  12881. return result;
  12882. }
  12883. // Mock stream for unit tests
  12884. class MockStream : public Stream {
  12885. public:
  12886. std::string data;
  12887. size_t pos = 0;
  12888. ssize_t error_after = -1; // -1 = no error
  12889. explicit MockStream(const std::string &d, ssize_t err = -1)
  12890. : data(d), error_after(err) {}
  12891. bool is_readable() const override { return true; }
  12892. bool wait_readable() const override { return true; }
  12893. bool wait_writable() const override { return true; }
  12894. ssize_t read(char *ptr, size_t size) override {
  12895. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12896. if (pos >= data.size()) return 0;
  12897. size_t limit =
  12898. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12899. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12900. std::memcpy(ptr, data.data() + pos, to_read);
  12901. pos += to_read;
  12902. return static_cast<ssize_t>(to_read);
  12903. }
  12904. ssize_t write(const char *, size_t) override { return -1; }
  12905. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12906. ip = "127.0.0.1";
  12907. port = 0;
  12908. }
  12909. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12910. ip = "127.0.0.1";
  12911. port = 0;
  12912. }
  12913. socket_t socket() const override { return INVALID_SOCKET; }
  12914. time_t duration() const override { return 0; }
  12915. };
  12916. TEST(StreamHandleTest, Basic) {
  12917. ClientImpl::StreamHandle handle;
  12918. EXPECT_FALSE(handle.is_valid());
  12919. handle.response = detail::make_unique<Response>();
  12920. handle.error = Error::Connection;
  12921. EXPECT_FALSE(handle.is_valid());
  12922. handle.error = Error::Success;
  12923. EXPECT_TRUE(handle.is_valid());
  12924. }
  12925. TEST(BodyReaderTest, Basic) {
  12926. MockStream stream("Hello, World!");
  12927. detail::BodyReader reader;
  12928. reader.stream = &stream;
  12929. reader.content_length = 13;
  12930. char buf[32];
  12931. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12932. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12933. EXPECT_TRUE(reader.eof);
  12934. }
  12935. TEST(BodyReaderTest, NoStream) {
  12936. detail::BodyReader reader;
  12937. char buf[32];
  12938. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12939. EXPECT_EQ(Error::Connection, reader.last_error);
  12940. }
  12941. TEST(BodyReaderTest, Error) {
  12942. MockStream stream("Hello, World!", 5);
  12943. detail::BodyReader reader;
  12944. reader.stream = &stream;
  12945. reader.content_length = 13;
  12946. char buf[32];
  12947. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12948. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12949. EXPECT_EQ(Error::Read, reader.last_error);
  12950. }
  12951. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12952. // Mock-based StreamHandle tests relying on private internals are removed.
  12953. class OpenStreamTest : public ::testing::Test {
  12954. protected:
  12955. void SetUp() override {
  12956. svr_.Get("/hello", [](const Request &, Response &res) {
  12957. res.set_content("Hello World!", "text/plain");
  12958. });
  12959. svr_.Get("/large", [](const Request &, Response &res) {
  12960. res.set_content(std::string(10000, 'X'), "text/plain");
  12961. });
  12962. svr_.Get("/chunked", [](const Request &, Response &res) {
  12963. res.set_chunked_content_provider("text/plain",
  12964. [](size_t offset, DataSink &sink) {
  12965. if (offset < 15) {
  12966. sink.write("chunk", 5);
  12967. return true;
  12968. }
  12969. sink.done();
  12970. return true;
  12971. });
  12972. });
  12973. svr_.Get("/compressible", [](const Request &, Response &res) {
  12974. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12975. DataSink &sink) {
  12976. if (offset < 100 * 1024) {
  12977. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12978. sink.write(chunk.data(), chunk.size());
  12979. return true;
  12980. }
  12981. sink.done();
  12982. return true;
  12983. });
  12984. });
  12985. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12986. [](const Request & /*req*/, Response &res) {
  12987. auto i = new int(0);
  12988. res.set_header("Trailer", "Content-Length, X-Allowed");
  12989. res.set_chunked_content_provider(
  12990. "text/plain",
  12991. [i](size_t /*offset*/, DataSink &sink) {
  12992. switch (*i) {
  12993. case 0: sink.os << "123"; break;
  12994. case 1: sink.os << "456"; break;
  12995. case 2: sink.os << "789"; break;
  12996. case 3: {
  12997. sink.done_with_trailer(
  12998. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12999. } break;
  13000. }
  13001. (*i)++;
  13002. return true;
  13003. },
  13004. [i](bool success) {
  13005. EXPECT_TRUE(success);
  13006. delete i;
  13007. });
  13008. });
  13009. // Echo headers endpoint for header-related tests
  13010. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13011. std::string body;
  13012. for (const auto &h : req.headers) {
  13013. body.append(h.first);
  13014. body.push_back(':');
  13015. body.append(h.second);
  13016. body.push_back('\n');
  13017. }
  13018. res.set_content(body, "text/plain");
  13019. });
  13020. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13021. std::string body;
  13022. for (const auto &h : req.headers) {
  13023. body.append(h.first);
  13024. body.push_back(':');
  13025. body.append(h.second);
  13026. body.push_back('\n');
  13027. }
  13028. res.set_content(body, "text/plain");
  13029. });
  13030. port_ = svr_.bind_to_any_port("127.0.0.1");
  13031. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13032. svr_.wait_until_ready();
  13033. }
  13034. void TearDown() override {
  13035. svr_.stop();
  13036. if (thread_.joinable()) thread_.join();
  13037. }
  13038. Server svr_;
  13039. std::thread thread_;
  13040. int port_ = 0;
  13041. };
  13042. TEST_F(OpenStreamTest, Basic) {
  13043. Client cli("127.0.0.1", port_);
  13044. auto handle = cli.open_stream("GET", "/hello");
  13045. EXPECT_TRUE(handle.is_valid());
  13046. EXPECT_EQ("Hello World!", read_all(handle));
  13047. }
  13048. TEST_F(OpenStreamTest, SmallBuffer) {
  13049. Client cli("127.0.0.1", port_);
  13050. auto handle = cli.open_stream("GET", "/hello");
  13051. std::string result;
  13052. char buf[4];
  13053. ssize_t n;
  13054. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13055. result.append(buf, static_cast<size_t>(n));
  13056. EXPECT_EQ("Hello World!", result);
  13057. }
  13058. TEST_F(OpenStreamTest, DefaultHeaders) {
  13059. Client cli("127.0.0.1", port_);
  13060. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13061. {
  13062. auto handle = cli.open_stream("GET", "/echo-headers");
  13063. ASSERT_TRUE(handle.is_valid());
  13064. auto body = read_all(handle);
  13065. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13066. std::string::npos);
  13067. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13068. std::string::npos);
  13069. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13070. }
  13071. // open_stream POST with body and no explicit content_type should NOT add
  13072. // text/plain Content-Type (behavior differs from non-streaming path), but
  13073. // should include Content-Length
  13074. {
  13075. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13076. ASSERT_TRUE(handle.is_valid());
  13077. auto body = read_all(handle);
  13078. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13079. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13080. }
  13081. // open_stream POST with explicit Content-Type should preserve it
  13082. {
  13083. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13084. {{"Content-Type", "application/custom"}},
  13085. "{}", "application/custom");
  13086. ASSERT_TRUE(handle.is_valid());
  13087. auto body = read_all(handle);
  13088. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13089. }
  13090. // User-specified User-Agent must not be overwritten for stream API
  13091. {
  13092. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13093. {{"User-Agent", "MyAgent/1.2"}});
  13094. ASSERT_TRUE(handle.is_valid());
  13095. auto body = read_all(handle);
  13096. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13097. }
  13098. }
  13099. TEST_F(OpenStreamTest, Large) {
  13100. Client cli("127.0.0.1", port_);
  13101. auto handle = cli.open_stream("GET", "/large");
  13102. EXPECT_EQ(10000u, read_all(handle).size());
  13103. }
  13104. TEST_F(OpenStreamTest, ConnectionError) {
  13105. Client cli("127.0.0.1", 9999);
  13106. auto handle = cli.open_stream("GET", "/hello");
  13107. EXPECT_FALSE(handle.is_valid());
  13108. }
  13109. TEST_F(OpenStreamTest, Chunked) {
  13110. Client cli("127.0.0.1", port_);
  13111. auto handle = cli.open_stream("GET", "/chunked");
  13112. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13113. "Transfer-Encoding") == "chunked");
  13114. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13115. }
  13116. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13117. Client cli("127.0.0.1", port_);
  13118. auto handle =
  13119. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13120. ASSERT_TRUE(handle.is_valid());
  13121. // Consume body to allow trailers to be received/parsed
  13122. auto body = read_all(handle);
  13123. // Explicitly parse trailers (ensure trailers are available for assertion)
  13124. handle.parse_trailers_if_needed();
  13125. EXPECT_EQ(std::string("123456789"), body);
  13126. // The response should include a Trailer header declaring both names
  13127. ASSERT_TRUE(handle.response);
  13128. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13129. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13130. handle.response->get_header_value("Trailer"));
  13131. // Prohibited trailer must not be present
  13132. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13133. // Allowed trailer should be present
  13134. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13135. EXPECT_EQ(std::string("yes"),
  13136. handle.response->get_trailer_value("X-Allowed"));
  13137. // Verify trailers are NOT present as regular headers
  13138. EXPECT_EQ(std::string(""),
  13139. handle.response->get_header_value("Content-Length"));
  13140. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13141. }
  13142. static std::thread serve_single_response(std::promise<int> &port_promise,
  13143. const std::string &response) {
  13144. return std::thread([&port_promise, response] {
  13145. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13146. default_socket_options(srv);
  13147. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13148. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13149. sockaddr_in addr{};
  13150. addr.sin_family = AF_INET;
  13151. addr.sin_port = htons(0); // Let OS assign a free port
  13152. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13153. int opt = 1;
  13154. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13155. #ifdef _WIN32
  13156. reinterpret_cast<const char *>(&opt),
  13157. #else
  13158. &opt,
  13159. #endif
  13160. sizeof(opt));
  13161. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13162. ::listen(srv, 1) != 0) {
  13163. port_promise.set_value(-1);
  13164. detail::close_socket(srv);
  13165. return;
  13166. }
  13167. socklen_t addr_len = sizeof(addr);
  13168. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13169. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13170. sockaddr_in cli_addr{};
  13171. socklen_t cli_len = sizeof(cli_addr);
  13172. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13173. if (cli != INVALID_SOCKET) {
  13174. // Read the complete HTTP request (until the blank line that terminates
  13175. // headers) before sending the response. If the server closes the socket
  13176. // while the client's request data is still unread in the kernel receive
  13177. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13178. // connection on both sides: it discards the client's receive buffer
  13179. // (which already holds our response) and causes any in-progress write on
  13180. // the client to fail with ECONNRESET. Reading all request data first
  13181. // ensures close() emits a graceful FIN.
  13182. {
  13183. char rbuf[256];
  13184. std::string req;
  13185. while (req.find("\r\n\r\n") == std::string::npos) {
  13186. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13187. if (n <= 0) { break; }
  13188. req.append(rbuf, static_cast<size_t>(n));
  13189. }
  13190. }
  13191. ::send(cli,
  13192. #ifdef _WIN32
  13193. static_cast<const char *>(response.c_str()),
  13194. static_cast<int>(response.size()),
  13195. #else
  13196. response.c_str(), response.size(),
  13197. #endif
  13198. 0);
  13199. detail::close_socket(cli);
  13200. }
  13201. detail::close_socket(srv);
  13202. });
  13203. }
  13204. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13205. #ifndef _WIN32
  13206. signal(SIGPIPE, SIG_IGN);
  13207. #endif
  13208. std::promise<int> port_promise;
  13209. auto port_future = port_promise.get_future();
  13210. auto server_thread =
  13211. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13212. "Content-Type: text/plain\r\n"
  13213. "Content-Length: not-a-number\r\n"
  13214. "Connection: close\r\n"
  13215. "\r\n"
  13216. "hello");
  13217. auto port = port_future.get();
  13218. ASSERT_GT(port, 0);
  13219. Client cli("127.0.0.1", port);
  13220. auto handle = cli.open_stream("GET", "/");
  13221. EXPECT_FALSE(handle.is_valid());
  13222. server_thread.join();
  13223. }
  13224. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13225. #ifndef _WIN32
  13226. signal(SIGPIPE, SIG_IGN);
  13227. #endif
  13228. std::promise<int> port_promise;
  13229. auto port_future = port_promise.get_future();
  13230. auto server_thread = serve_single_response(
  13231. port_promise, "HTTP/1.1 200 OK\r\n"
  13232. "Content-Type: text/plain\r\n"
  13233. "Content-Length: 99999999999999999999999999\r\n"
  13234. "Connection: close\r\n"
  13235. "\r\n"
  13236. "hello");
  13237. auto port = port_future.get();
  13238. ASSERT_GT(port, 0);
  13239. // Before the fix, std::stoull would throw std::out_of_range here and
  13240. // crash the process. After the fix, strtoull silently clamps to
  13241. // ULLONG_MAX so the stream opens without crashing. The important thing
  13242. // is that the process does NOT terminate.
  13243. Client cli("127.0.0.1", port);
  13244. auto handle = cli.open_stream("GET", "/");
  13245. EXPECT_TRUE(handle.is_valid());
  13246. server_thread.join();
  13247. }
  13248. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13249. TEST_F(OpenStreamTest, Gzip) {
  13250. Client cli("127.0.0.1", port_);
  13251. auto handle = cli.open_stream("GET", "/compressible", {},
  13252. {{"Accept-Encoding", "gzip"}});
  13253. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13254. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13255. }
  13256. #endif
  13257. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13258. TEST_F(OpenStreamTest, Brotli) {
  13259. Client cli("127.0.0.1", port_);
  13260. auto handle =
  13261. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13262. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13263. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13264. }
  13265. #endif
  13266. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13267. TEST_F(OpenStreamTest, Zstd) {
  13268. Client cli("127.0.0.1", port_);
  13269. auto handle = cli.open_stream("GET", "/compressible", {},
  13270. {{"Accept-Encoding", "zstd"}});
  13271. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13272. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13273. }
  13274. #endif
  13275. #ifdef CPPHTTPLIB_SSL_ENABLED
  13276. class SSLOpenStreamTest : public ::testing::Test {
  13277. protected:
  13278. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13279. void SetUp() override {
  13280. svr_.Get("/hello", [](const Request &, Response &res) {
  13281. res.set_content("Hello SSL World!", "text/plain");
  13282. });
  13283. svr_.Get("/chunked", [](const Request &, Response &res) {
  13284. res.set_chunked_content_provider("text/plain",
  13285. [](size_t offset, DataSink &sink) {
  13286. if (offset < 15) {
  13287. sink.write("chunk", 5);
  13288. return true;
  13289. }
  13290. sink.done();
  13291. return true;
  13292. });
  13293. });
  13294. svr_.Post("/echo", [](const Request &req, Response &res) {
  13295. res.set_content(req.body, req.get_header_value("Content-Type"));
  13296. });
  13297. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13298. std::string body = req.body;
  13299. res.set_chunked_content_provider(
  13300. "text/plain", [body](size_t offset, DataSink &sink) {
  13301. if (offset < body.size()) {
  13302. sink.write(body.data() + offset, body.size() - offset);
  13303. }
  13304. sink.done();
  13305. return true;
  13306. });
  13307. });
  13308. port_ = svr_.bind_to_any_port("127.0.0.1");
  13309. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13310. svr_.wait_until_ready();
  13311. }
  13312. void TearDown() override {
  13313. svr_.stop();
  13314. if (thread_.joinable()) thread_.join();
  13315. }
  13316. SSLServer svr_;
  13317. std::thread thread_;
  13318. int port_ = 0;
  13319. };
  13320. TEST_F(SSLOpenStreamTest, Basic) {
  13321. SSLClient cli("127.0.0.1", port_);
  13322. cli.enable_server_certificate_verification(false);
  13323. auto handle = cli.open_stream("GET", "/hello");
  13324. ASSERT_TRUE(handle.is_valid());
  13325. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13326. }
  13327. TEST_F(SSLOpenStreamTest, Chunked) {
  13328. SSLClient cli("127.0.0.1", port_);
  13329. cli.enable_server_certificate_verification(false);
  13330. auto handle = cli.open_stream("GET", "/chunked");
  13331. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13332. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13333. "Transfer-Encoding") == "chunked");
  13334. auto body = read_all(handle);
  13335. EXPECT_EQ("chunkchunkchunk", body);
  13336. }
  13337. TEST_F(SSLOpenStreamTest, Post) {
  13338. SSLClient cli("127.0.0.1", port_);
  13339. cli.enable_server_certificate_verification(false);
  13340. auto handle =
  13341. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13342. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13343. EXPECT_EQ(200, handle.response->status);
  13344. auto body = read_all(handle);
  13345. EXPECT_EQ("Hello SSL POST", body);
  13346. }
  13347. TEST_F(SSLOpenStreamTest, PostChunked) {
  13348. SSLClient cli("127.0.0.1", port_);
  13349. cli.enable_server_certificate_verification(false);
  13350. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13351. "Chunked SSL Data", "text/plain");
  13352. ASSERT_TRUE(handle.is_valid());
  13353. EXPECT_EQ(200, handle.response->status);
  13354. auto body = read_all(handle);
  13355. EXPECT_EQ("Chunked SSL Data", body);
  13356. }
  13357. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13358. // Content-Length is terminated by the server closing the connection. When the
  13359. // SSL peer sends a close_notify after the body, the client must treat it as a
  13360. // clean EOF and return a successful response rather than an error.
  13361. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13362. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13363. ASSERT_TRUE(svr.is_valid());
  13364. svr.set_keep_alive_max_count(1);
  13365. const std::string expected_body = "Hello from connection-close response!";
  13366. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13367. res.set_content_provider("text/plain",
  13368. [&](size_t offset, DataSink &sink) -> bool {
  13369. if (offset < expected_body.size()) {
  13370. sink.write(expected_body.data() + offset,
  13371. expected_body.size() - offset);
  13372. }
  13373. sink.done();
  13374. return true;
  13375. });
  13376. });
  13377. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13378. auto se = detail::scope_exit([&] {
  13379. svr.stop();
  13380. listen_thread.join();
  13381. ASSERT_FALSE(svr.is_running());
  13382. });
  13383. svr.wait_until_ready();
  13384. SSLClient cli(HOST, PORT);
  13385. cli.enable_server_certificate_verification(false);
  13386. auto res = cli.Get("/no-content-length");
  13387. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13388. EXPECT_EQ(StatusCode::OK_200, res->status);
  13389. EXPECT_EQ(expected_body, res->body);
  13390. }
  13391. #endif // CPPHTTPLIB_SSL_ENABLED
  13392. //==============================================================================
  13393. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13394. // results for various scenarios.
  13395. //==============================================================================
  13396. TEST(ParityTest, GetVsOpenStream) {
  13397. Server svr;
  13398. const std::string path = "/parity";
  13399. const std::string content = "Parity test content: hello world";
  13400. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13401. res.set_content(content, "text/plain");
  13402. });
  13403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13404. auto se = detail::scope_exit([&] {
  13405. svr.stop();
  13406. t.join();
  13407. ASSERT_FALSE(svr.is_running());
  13408. });
  13409. svr.wait_until_ready();
  13410. Client cli(HOST, PORT);
  13411. // Non-stream path
  13412. auto r1 = cli.Get(path);
  13413. ASSERT_TRUE(r1);
  13414. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13415. // Stream path
  13416. auto h = cli.open_stream("GET", path);
  13417. ASSERT_TRUE(h.is_valid());
  13418. EXPECT_EQ(r1->body, read_all(h));
  13419. }
  13420. // Helper to compress data with provided compressor type T
  13421. template <typename Compressor>
  13422. static std::string compress_payload_for_parity(const std::string &in) {
  13423. std::string out;
  13424. Compressor compressor;
  13425. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13426. [&](const char *data, size_t n) {
  13427. out.append(data, n);
  13428. return true;
  13429. });
  13430. EXPECT_TRUE(ok);
  13431. return out;
  13432. }
  13433. // Helper function for compression parity tests
  13434. template <typename Compressor>
  13435. static void test_compression_parity(const std::string &original,
  13436. const std::string &path,
  13437. const std::string &encoding) {
  13438. const std::string compressed =
  13439. compress_payload_for_parity<Compressor>(original);
  13440. Server svr;
  13441. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13442. res.set_content(compressed, "application/octet-stream");
  13443. res.set_header("Content-Encoding", encoding);
  13444. });
  13445. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13446. auto se = detail::scope_exit([&] {
  13447. svr.stop();
  13448. t.join();
  13449. ASSERT_FALSE(svr.is_running());
  13450. });
  13451. svr.wait_until_ready();
  13452. Client cli(HOST, PORT);
  13453. // Non-streaming
  13454. {
  13455. auto res = cli.Get(path);
  13456. ASSERT_TRUE(res);
  13457. EXPECT_EQ(StatusCode::OK_200, res->status);
  13458. EXPECT_EQ(original, res->body);
  13459. }
  13460. // Streaming
  13461. {
  13462. auto h = cli.open_stream("GET", path);
  13463. ASSERT_TRUE(h.is_valid());
  13464. EXPECT_EQ(original, read_all(h));
  13465. }
  13466. }
  13467. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13468. TEST(ParityTest, Gzip) {
  13469. test_compression_parity<detail::gzip_compressor>(
  13470. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13471. }
  13472. #endif
  13473. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13474. TEST(ParityTest, Brotli) {
  13475. test_compression_parity<detail::brotli_compressor>(
  13476. "Hello, brotli parity test payload", "/parity-br", "br");
  13477. }
  13478. #endif
  13479. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13480. TEST(ParityTest, Zstd) {
  13481. test_compression_parity<detail::zstd_compressor>(
  13482. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13483. }
  13484. #endif
  13485. //==============================================================================
  13486. // New Stream API Tests
  13487. //==============================================================================
  13488. inline std::string read_body(httplib::stream::Result &result) {
  13489. std::string body;
  13490. while (result.next()) {
  13491. body.append(result.data(), result.size());
  13492. }
  13493. return body;
  13494. }
  13495. TEST(ClientConnectionTest, Basic) {
  13496. httplib::ClientConnection conn;
  13497. EXPECT_FALSE(conn.is_open());
  13498. conn.sock = 1;
  13499. EXPECT_TRUE(conn.is_open());
  13500. httplib::ClientConnection conn2(std::move(conn));
  13501. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13502. conn2.sock = INVALID_SOCKET;
  13503. }
  13504. // Unified test server for all stream::* tests
  13505. class StreamApiTest : public ::testing::Test {
  13506. protected:
  13507. void SetUp() override {
  13508. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13509. res.set_content("Hello World!", "text/plain");
  13510. });
  13511. svr_.Get("/echo-params",
  13512. [](const httplib::Request &req, httplib::Response &res) {
  13513. std::string r;
  13514. for (const auto &p : req.params) {
  13515. if (!r.empty()) r += "&";
  13516. r += p.first + "=" + p.second;
  13517. }
  13518. res.set_content(r, "text/plain");
  13519. });
  13520. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13521. res.set_content(req.body, req.get_header_value("Content-Type"));
  13522. });
  13523. svr_.Post("/echo-headers",
  13524. [](const httplib::Request &req, httplib::Response &res) {
  13525. std::string r;
  13526. for (const auto &h : req.headers)
  13527. r += h.first + ": " + h.second + "\n";
  13528. res.set_content(r, "text/plain");
  13529. });
  13530. svr_.Post("/echo-params",
  13531. [](const httplib::Request &req, httplib::Response &res) {
  13532. std::string r = "params:";
  13533. for (const auto &p : req.params)
  13534. r += p.first + "=" + p.second + ";";
  13535. res.set_content(r + " body:" + req.body, "text/plain");
  13536. });
  13537. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13538. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13539. });
  13540. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13541. res.set_content("PUT:" + req.body, "text/plain");
  13542. });
  13543. svr_.Patch("/echo",
  13544. [](const httplib::Request &req, httplib::Response &res) {
  13545. res.set_content("PATCH:" + req.body, "text/plain");
  13546. });
  13547. svr_.Delete(
  13548. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13549. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13550. "text/plain");
  13551. });
  13552. svr_.Get("/head-test",
  13553. [](const httplib::Request &, httplib::Response &res) {
  13554. res.set_content("body for HEAD", "text/plain");
  13555. });
  13556. svr_.Options("/options",
  13557. [](const httplib::Request &, httplib::Response &res) {
  13558. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13559. });
  13560. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13561. svr_.wait_until_ready();
  13562. }
  13563. void TearDown() override {
  13564. svr_.stop();
  13565. if (thread_.joinable()) thread_.join();
  13566. }
  13567. httplib::Server svr_;
  13568. std::thread thread_;
  13569. };
  13570. // stream::Get tests
  13571. TEST_F(StreamApiTest, GetBasic) {
  13572. httplib::Client cli(HOST, PORT);
  13573. auto result = httplib::stream::Get(cli, "/hello");
  13574. ASSERT_TRUE(result.is_valid());
  13575. EXPECT_EQ(200, result.status());
  13576. EXPECT_EQ("Hello World!", read_body(result));
  13577. }
  13578. TEST_F(StreamApiTest, GetWithParams) {
  13579. httplib::Client cli(HOST, PORT);
  13580. httplib::Params params{{"foo", "bar"}};
  13581. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13582. ASSERT_TRUE(result.is_valid());
  13583. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13584. }
  13585. TEST_F(StreamApiTest, GetConnectionError) {
  13586. httplib::Client cli(HOST, 9999);
  13587. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13588. }
  13589. TEST_F(StreamApiTest, Get404) {
  13590. httplib::Client cli(HOST, PORT);
  13591. auto result = httplib::stream::Get(cli, "/nonexistent");
  13592. EXPECT_TRUE(result.is_valid());
  13593. EXPECT_EQ(404, result.status());
  13594. }
  13595. // stream::Post tests
  13596. TEST_F(StreamApiTest, PostBasic) {
  13597. httplib::Client cli(HOST, PORT);
  13598. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13599. "application/json");
  13600. ASSERT_TRUE(result.is_valid());
  13601. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13602. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13603. }
  13604. TEST_F(StreamApiTest, PostWithHeaders) {
  13605. httplib::Client cli(HOST, PORT);
  13606. httplib::Headers headers{{"X-Custom", "value"}};
  13607. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13608. "text/plain");
  13609. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13610. }
  13611. TEST_F(StreamApiTest, PostWithParams) {
  13612. httplib::Client cli(HOST, PORT);
  13613. httplib::Params params{{"k", "v"}};
  13614. auto result =
  13615. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13616. auto body = read_body(result);
  13617. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13618. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13619. }
  13620. TEST_F(StreamApiTest, PostLarge) {
  13621. httplib::Client cli(HOST, PORT);
  13622. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13623. size_t total = 0;
  13624. while (result.next()) {
  13625. total += result.size();
  13626. }
  13627. EXPECT_EQ(100u * 1024u, total);
  13628. }
  13629. // stream::Put/Patch tests
  13630. TEST_F(StreamApiTest, PutAndPatch) {
  13631. httplib::Client cli(HOST, PORT);
  13632. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13633. EXPECT_EQ("PUT:test", read_body(put));
  13634. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13635. EXPECT_EQ("PATCH:test", read_body(patch));
  13636. }
  13637. // stream::Delete tests
  13638. TEST_F(StreamApiTest, Delete) {
  13639. httplib::Client cli(HOST, PORT);
  13640. auto del1 = httplib::stream::Delete(cli, "/resource");
  13641. EXPECT_EQ("Deleted", read_body(del1));
  13642. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13643. EXPECT_EQ("Deleted:data", read_body(del2));
  13644. }
  13645. // stream::Head/Options tests
  13646. TEST_F(StreamApiTest, HeadAndOptions) {
  13647. httplib::Client cli(HOST, PORT);
  13648. auto head = httplib::stream::Head(cli, "/head-test");
  13649. EXPECT_TRUE(head.is_valid());
  13650. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13651. auto opts = httplib::stream::Options(cli, "/options");
  13652. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13653. }
  13654. // SSL stream::* tests
  13655. #ifdef CPPHTTPLIB_SSL_ENABLED
  13656. class SSLStreamApiTest : public ::testing::Test {
  13657. protected:
  13658. void SetUp() override {
  13659. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13660. res.set_content("Hello SSL!", "text/plain");
  13661. });
  13662. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13663. res.set_content(req.body, "text/plain");
  13664. });
  13665. port_ = svr_.bind_to_any_port("127.0.0.1");
  13666. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13667. svr_.wait_until_ready();
  13668. }
  13669. void TearDown() override {
  13670. svr_.stop();
  13671. if (thread_.joinable()) thread_.join();
  13672. }
  13673. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13674. std::thread thread_;
  13675. int port_ = 0;
  13676. };
  13677. TEST_F(SSLStreamApiTest, GetAndPost) {
  13678. httplib::SSLClient cli("127.0.0.1", port_);
  13679. cli.enable_server_certificate_verification(false);
  13680. auto get = httplib::stream::Get(cli, "/hello");
  13681. EXPECT_EQ("Hello SSL!", read_body(get));
  13682. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13683. EXPECT_EQ("test", read_body(post));
  13684. }
  13685. #endif
  13686. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13687. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13688. // BodyReader
  13689. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13690. // Test that read timeout during streaming is detected
  13691. // Use a large content-length response where server delays mid-stream
  13692. Server svr;
  13693. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13694. // Send a large response with delay in the middle
  13695. res.set_content_provider(
  13696. 1000, // content_length
  13697. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13698. if (offset < 100) {
  13699. // Send first 100 bytes immediately
  13700. std::string data(100, 'A');
  13701. sink.write(data.c_str(), data.size());
  13702. return true;
  13703. }
  13704. // Then delay longer than client timeout
  13705. std::this_thread::sleep_for(std::chrono::seconds(3));
  13706. std::string data(900, 'B');
  13707. sink.write(data.c_str(), data.size());
  13708. return true;
  13709. });
  13710. });
  13711. auto port = 8091;
  13712. std::thread t([&]() { svr.listen("localhost", port); });
  13713. svr.wait_until_ready();
  13714. Client cli("localhost", port);
  13715. cli.set_read_timeout(1, 0); // 1 second timeout
  13716. auto handle = cli.open_stream("GET", "/slow-stream");
  13717. ASSERT_TRUE(handle.is_valid());
  13718. char buf[256];
  13719. ssize_t total = 0;
  13720. ssize_t n;
  13721. bool got_error = false;
  13722. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13723. total += n;
  13724. }
  13725. if (n < 0) {
  13726. got_error = true;
  13727. // Should be timeout or read error
  13728. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13729. handle.get_read_error() == Error::Read)
  13730. << "Actual error: " << to_string(handle.get_read_error());
  13731. }
  13732. // Either we got an error, or we got less data than expected
  13733. EXPECT_TRUE(got_error || total < 1000)
  13734. << "Expected timeout but got all " << total << " bytes";
  13735. svr.stop();
  13736. t.join();
  13737. }
  13738. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13739. // Test connection closed detection via BodyReader
  13740. Server svr;
  13741. std::atomic<bool> close_now{false};
  13742. svr.Get("/will-close", [&](const Request &, Response &res) {
  13743. res.set_content_provider(
  13744. 10000, // Large content_length that we won't fully send
  13745. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13746. if (offset < 100) {
  13747. std::string data(100, 'X');
  13748. sink.write(data.c_str(), data.size());
  13749. return true;
  13750. }
  13751. // Wait for signal then abort
  13752. while (!close_now) {
  13753. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13754. }
  13755. return false; // Abort - server will close connection
  13756. });
  13757. });
  13758. auto port = 8092;
  13759. std::thread t([&]() { svr.listen("localhost", port); });
  13760. svr.wait_until_ready();
  13761. Client cli("localhost", port);
  13762. auto handle = cli.open_stream("GET", "/will-close");
  13763. ASSERT_TRUE(handle.is_valid());
  13764. char buf[256];
  13765. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13766. EXPECT_GT(n, 0) << "First read should succeed";
  13767. // Signal server to close
  13768. close_now = true;
  13769. // Keep reading until error or EOF
  13770. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13771. // Keep reading
  13772. }
  13773. // Should get an error since content_length wasn't satisfied
  13774. if (n < 0) {
  13775. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13776. handle.get_read_error() == Error::Read)
  13777. << "Actual error: " << to_string(handle.get_read_error());
  13778. }
  13779. svr.stop();
  13780. t.join();
  13781. }
  13782. #ifdef CPPHTTPLIB_SSL_ENABLED
  13783. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13784. // Test that read timeout during SSL streaming is detected
  13785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13786. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13787. res.set_content_provider(
  13788. 1000, "text/plain",
  13789. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13790. if (offset < 100) {
  13791. std::string data(100, 'A');
  13792. sink.write(data.c_str(), data.size());
  13793. return true;
  13794. }
  13795. std::this_thread::sleep_for(std::chrono::seconds(3));
  13796. std::string data(900, 'B');
  13797. sink.write(data.c_str(), data.size());
  13798. return true;
  13799. });
  13800. });
  13801. auto port = 8093;
  13802. std::thread t([&]() { svr.listen("localhost", port); });
  13803. svr.wait_until_ready();
  13804. SSLClient cli("localhost", port);
  13805. cli.enable_server_certificate_verification(false);
  13806. cli.set_read_timeout(1, 0); // 1 second timeout
  13807. auto handle = cli.open_stream("GET", "/slow-stream");
  13808. ASSERT_TRUE(handle.is_valid());
  13809. char buf[256];
  13810. ssize_t total = 0;
  13811. ssize_t n;
  13812. bool got_error = false;
  13813. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13814. total += n;
  13815. }
  13816. if (n < 0) {
  13817. got_error = true;
  13818. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13819. handle.get_read_error() == Error::Read)
  13820. << "Actual error: " << to_string(handle.get_read_error());
  13821. }
  13822. EXPECT_TRUE(got_error || total < 1000)
  13823. << "Expected timeout but got all " << total << " bytes";
  13824. svr.stop();
  13825. t.join();
  13826. }
  13827. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13828. // Test SSL connection closed detection
  13829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13830. std::atomic<bool> close_now{false};
  13831. svr.Get("/will-close", [&](const Request &, Response &res) {
  13832. res.set_content_provider(
  13833. 10000, "text/plain",
  13834. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13835. if (offset < 100) {
  13836. std::string data(100, 'X');
  13837. sink.write(data.c_str(), data.size());
  13838. return true;
  13839. }
  13840. while (!close_now) {
  13841. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13842. }
  13843. return false;
  13844. });
  13845. });
  13846. auto port = 8094;
  13847. std::thread t([&]() { svr.listen("localhost", port); });
  13848. svr.wait_until_ready();
  13849. SSLClient cli("localhost", port);
  13850. cli.enable_server_certificate_verification(false);
  13851. auto handle = cli.open_stream("GET", "/will-close");
  13852. ASSERT_TRUE(handle.is_valid());
  13853. char buf[256];
  13854. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13855. EXPECT_GT(n, 0);
  13856. // Signal server to close
  13857. close_now = true;
  13858. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13859. // Keep reading
  13860. }
  13861. if (n < 0) {
  13862. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13863. handle.get_read_error() == Error::Read)
  13864. << "Actual error: " << to_string(handle.get_read_error());
  13865. }
  13866. svr.stop();
  13867. t.join();
  13868. }
  13869. #endif
  13870. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13871. using namespace httplib;
  13872. // Create a test file
  13873. const char *fname = "etag_testfile.txt";
  13874. const char *content = "etag-content";
  13875. {
  13876. std::ofstream ofs(fname);
  13877. ofs << content;
  13878. ASSERT_TRUE(ofs.good());
  13879. }
  13880. Server svr;
  13881. svr.set_mount_point("/static", ".");
  13882. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13883. svr.wait_until_ready();
  13884. Client cli(HOST, PORT);
  13885. // First request: should get 200 with ETag header
  13886. auto res1 = cli.Get("/static/etag_testfile.txt");
  13887. ASSERT_TRUE(res1);
  13888. ASSERT_EQ(200, res1->status);
  13889. ASSERT_TRUE(res1->has_header("ETag"));
  13890. std::string etag = res1->get_header_value("ETag");
  13891. EXPECT_FALSE(etag.empty());
  13892. // Verify ETag format: W/"hex-hex"
  13893. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13894. EXPECT_EQ('W', etag[0]);
  13895. EXPECT_EQ('/', etag[1]);
  13896. EXPECT_EQ('"', etag[2]);
  13897. EXPECT_EQ('"', etag.back());
  13898. // Exact match: expect 304 Not Modified
  13899. Headers h2 = {{"If-None-Match", etag}};
  13900. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13901. ASSERT_TRUE(res2);
  13902. EXPECT_EQ(304, res2->status);
  13903. // Wildcard match: expect 304 Not Modified
  13904. Headers h3 = {{"If-None-Match", "*"}};
  13905. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13906. ASSERT_TRUE(res3);
  13907. EXPECT_EQ(304, res3->status);
  13908. // Non-matching ETag: expect 200
  13909. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13910. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13911. ASSERT_TRUE(res4);
  13912. EXPECT_EQ(200, res4->status);
  13913. // Multiple ETags with one matching: expect 304
  13914. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13915. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13916. ASSERT_TRUE(res5);
  13917. EXPECT_EQ(304, res5->status);
  13918. svr.stop();
  13919. t.join();
  13920. std::remove(fname);
  13921. }
  13922. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13923. using namespace httplib;
  13924. Server svr;
  13925. svr.set_mount_point("/static", ".");
  13926. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13927. svr.wait_until_ready();
  13928. Client cli(HOST, PORT);
  13929. // Send If-None-Match: * to a non-existent file
  13930. Headers h = {{"If-None-Match", "*"}};
  13931. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13932. ASSERT_TRUE(res);
  13933. EXPECT_EQ(404, res->status);
  13934. svr.stop();
  13935. t.join();
  13936. }
  13937. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13938. using namespace httplib;
  13939. // Create a test file
  13940. const char *fname = "etag_boundary_testfile.txt";
  13941. const char *content = "boundary-test";
  13942. {
  13943. std::ofstream ofs(fname);
  13944. ofs << content;
  13945. ASSERT_TRUE(ofs.good());
  13946. }
  13947. Server svr;
  13948. svr.set_mount_point("/static", ".");
  13949. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13950. svr.wait_until_ready();
  13951. Client cli(HOST, PORT);
  13952. // Get the actual ETag
  13953. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13954. ASSERT_TRUE(res1);
  13955. ASSERT_EQ(200, res1->status);
  13956. ASSERT_TRUE(res1->has_header("ETag"));
  13957. std::string etag = res1->get_header_value("ETag");
  13958. // Test 1: Very long ETag value (longer than actual ETag)
  13959. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13960. Headers h1 = {{"If-None-Match", "W/"
  13961. "\"very-long-etag-value-that-is-much-longer-"
  13962. "than-the-actual-etag-value\""}};
  13963. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13964. ASSERT_TRUE(res2);
  13965. EXPECT_EQ(200, res2->status); // Should not match
  13966. // Test 2: Long string followed by wildcard
  13967. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13968. // string)
  13969. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13970. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13971. ASSERT_TRUE(res3);
  13972. EXPECT_EQ(304, res3->status); // Should match on "*"
  13973. // Test 3: Wildcard followed by long string
  13974. // Should match on "*" immediately and return 304
  13975. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13976. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13977. ASSERT_TRUE(res4);
  13978. EXPECT_EQ(304, res4->status); // Should match on "*"
  13979. // Test 4: Multiple long non-matching values
  13980. // Should NOT match and return 200 (test that all comparisons are safe)
  13981. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13982. "W/\"second-long-non-matching-value\", "
  13983. "W/\"third-long-non-matching-value\""}};
  13984. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13985. ASSERT_TRUE(res5);
  13986. EXPECT_EQ(200, res5->status); // Should not match
  13987. // Test 5: Single character that is not "*" (edge case)
  13988. Headers h5 = {{"If-None-Match", "X"}};
  13989. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13990. ASSERT_TRUE(res6);
  13991. EXPECT_EQ(200, res6->status); // Should not match
  13992. svr.stop();
  13993. t.join();
  13994. std::remove(fname);
  13995. }
  13996. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13997. using namespace httplib;
  13998. // Create a test file
  13999. const char *fname = "ims_testfile.txt";
  14000. const char *content = "if-modified-since-test";
  14001. {
  14002. std::ofstream ofs(fname);
  14003. ofs << content;
  14004. ASSERT_TRUE(ofs.good());
  14005. }
  14006. Server svr;
  14007. svr.set_mount_point("/static", ".");
  14008. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14009. svr.wait_until_ready();
  14010. Client cli(HOST, PORT);
  14011. // First request: should get 200 with Last-Modified header
  14012. auto res1 = cli.Get("/static/ims_testfile.txt");
  14013. ASSERT_TRUE(res1);
  14014. ASSERT_EQ(200, res1->status);
  14015. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14016. std::string last_modified = res1->get_header_value("Last-Modified");
  14017. EXPECT_FALSE(last_modified.empty());
  14018. // If-Modified-Since with same time: expect 304
  14019. Headers h2 = {{"If-Modified-Since", last_modified}};
  14020. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14021. ASSERT_TRUE(res2);
  14022. EXPECT_EQ(304, res2->status);
  14023. // If-Modified-Since with future time: expect 304
  14024. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14025. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14026. ASSERT_TRUE(res3);
  14027. EXPECT_EQ(304, res3->status);
  14028. // If-Modified-Since with past time: expect 200
  14029. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14030. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14031. ASSERT_TRUE(res4);
  14032. EXPECT_EQ(200, res4->status);
  14033. // If-None-Match takes precedence over If-Modified-Since
  14034. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14035. ASSERT_TRUE(res1->has_header("ETag"));
  14036. std::string etag = res1->get_header_value("ETag");
  14037. Headers h5 = {{"If-None-Match", etag},
  14038. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14039. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14040. ASSERT_TRUE(res5);
  14041. EXPECT_EQ(304, res5->status);
  14042. svr.stop();
  14043. t.join();
  14044. std::remove(fname);
  14045. }
  14046. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14047. using namespace httplib;
  14048. Server svr;
  14049. // Endpoint that returns compressible content
  14050. svr.Get("/compressible", [](const Request &, Response &res) {
  14051. // Return a large enough body to trigger compression
  14052. std::string body(1000, 'a');
  14053. res.set_content(body, "text/plain");
  14054. });
  14055. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14056. svr.wait_until_ready();
  14057. Client cli(HOST, PORT);
  14058. // Request with gzip support: should get Vary header when compressed
  14059. cli.set_compress(true);
  14060. auto res1 = cli.Get("/compressible");
  14061. ASSERT_TRUE(res1);
  14062. EXPECT_EQ(200, res1->status);
  14063. // If Content-Encoding is set, Vary should also be set
  14064. if (res1->has_header("Content-Encoding")) {
  14065. EXPECT_TRUE(res1->has_header("Vary"));
  14066. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14067. }
  14068. // Request without Accept-Encoding header: should not have compression
  14069. Headers h_no_compress;
  14070. auto res2 = cli.Get("/compressible", h_no_compress);
  14071. ASSERT_TRUE(res2);
  14072. EXPECT_EQ(200, res2->status);
  14073. // Verify Vary header is present when compression is applied
  14074. // (the exact behavior depends on server configuration)
  14075. svr.stop();
  14076. t.join();
  14077. }
  14078. TEST(ETagTest, IfRangeWithETag) {
  14079. using namespace httplib;
  14080. // Create a test file with known content
  14081. const char *fname = "if_range_testfile.txt";
  14082. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14083. {
  14084. std::ofstream ofs(fname);
  14085. ofs << content;
  14086. ASSERT_TRUE(ofs.good());
  14087. }
  14088. Server svr;
  14089. svr.set_mount_point("/static", ".");
  14090. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14091. svr.wait_until_ready();
  14092. Client cli(HOST, PORT);
  14093. // First request: get ETag
  14094. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14095. ASSERT_TRUE(res1);
  14096. ASSERT_EQ(200, res1->status);
  14097. ASSERT_TRUE(res1->has_header("ETag"));
  14098. std::string etag = res1->get_header_value("ETag");
  14099. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14100. // Since our server generates weak ETags (W/"..."), If-Range with our
  14101. // ETag should NOT result in partial content - it should return full content.
  14102. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14103. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14104. ASSERT_TRUE(res2);
  14105. // Weak ETag in If-Range -> full content (200), not partial (206)
  14106. EXPECT_EQ(200, res2->status);
  14107. EXPECT_EQ(content, res2->body);
  14108. EXPECT_FALSE(res2->has_header("Content-Range"));
  14109. // Range request with non-matching If-Range (ETag): should get 200 (full
  14110. // content)
  14111. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14112. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14113. ASSERT_TRUE(res3);
  14114. EXPECT_EQ(200, res3->status);
  14115. EXPECT_EQ(content, res3->body);
  14116. EXPECT_FALSE(res3->has_header("Content-Range"));
  14117. // Range request with strong ETag (hypothetical - our server doesn't generate
  14118. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14119. // should return full content)
  14120. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14121. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14122. ASSERT_TRUE(res4);
  14123. EXPECT_EQ(200, res4->status);
  14124. EXPECT_EQ(content, res4->body);
  14125. EXPECT_FALSE(res4->has_header("Content-Range"));
  14126. svr.stop();
  14127. t.join();
  14128. std::remove(fname);
  14129. }
  14130. TEST(ETagTest, IfRangeWithDate) {
  14131. using namespace httplib;
  14132. // Create a test file
  14133. const char *fname = "if_range_date_testfile.txt";
  14134. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14135. {
  14136. std::ofstream ofs(fname);
  14137. ofs << content;
  14138. ASSERT_TRUE(ofs.good());
  14139. }
  14140. Server svr;
  14141. svr.set_mount_point("/static", ".");
  14142. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14143. svr.wait_until_ready();
  14144. Client cli(HOST, PORT);
  14145. // First request: get Last-Modified
  14146. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14147. ASSERT_TRUE(res1);
  14148. ASSERT_EQ(200, res1->status);
  14149. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14150. std::string last_modified = res1->get_header_value("Last-Modified");
  14151. // Range request with matching If-Range (date): should get 206
  14152. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14153. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14154. ASSERT_TRUE(res2);
  14155. EXPECT_EQ(206, res2->status);
  14156. EXPECT_EQ("FGHIJ", res2->body);
  14157. // Range request with old If-Range date: should get 200 (full content)
  14158. Headers h3 = {{"Range", "bytes=5-9"},
  14159. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14160. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14161. ASSERT_TRUE(res3);
  14162. EXPECT_EQ(200, res3->status);
  14163. EXPECT_EQ(content, res3->body);
  14164. // Range request with future If-Range date: should get 206
  14165. Headers h4 = {{"Range", "bytes=0-4"},
  14166. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14167. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14168. ASSERT_TRUE(res4);
  14169. EXPECT_EQ(206, res4->status);
  14170. EXPECT_EQ("ABCDE", res4->body);
  14171. svr.stop();
  14172. t.join();
  14173. std::remove(fname);
  14174. }
  14175. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14176. using namespace httplib;
  14177. const char *fname = "etag_malformed.txt";
  14178. const char *content = "malformed-etag";
  14179. {
  14180. std::ofstream ofs(fname);
  14181. ofs << content;
  14182. ASSERT_TRUE(ofs.good());
  14183. }
  14184. Server svr;
  14185. svr.set_mount_point("/static", ".");
  14186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14187. svr.wait_until_ready();
  14188. Client cli(HOST, PORT);
  14189. // baseline: should get 200 and an ETag
  14190. auto res1 = cli.Get("/static/etag_malformed.txt");
  14191. ASSERT_TRUE(res1);
  14192. ASSERT_EQ(200, res1->status);
  14193. ASSERT_TRUE(res1->has_header("ETag"));
  14194. // Malformed ETag value (missing quotes) should be treated as non-matching
  14195. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14196. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14197. ASSERT_TRUE(res_bad);
  14198. EXPECT_EQ(200, res_bad->status);
  14199. // Whitespace-only header value should be considered invalid / non-matching
  14200. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14201. "Host: localhost\r\n"
  14202. "If-None-Match: \r\n"
  14203. "Connection: close\r\n"
  14204. "\r\n";
  14205. std::string out;
  14206. ASSERT_TRUE(send_request(5, raw_req, &out));
  14207. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14208. svr.stop();
  14209. t.join();
  14210. std::remove(fname);
  14211. }
  14212. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14213. using namespace httplib;
  14214. const char *fname = "ims_invalid_format.txt";
  14215. const char *content = "ims-bad-format";
  14216. {
  14217. std::ofstream ofs(fname);
  14218. ofs << content;
  14219. ASSERT_TRUE(ofs.good());
  14220. }
  14221. Server svr;
  14222. svr.set_mount_point("/static", ".");
  14223. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14224. svr.wait_until_ready();
  14225. Client cli(HOST, PORT);
  14226. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14227. ASSERT_TRUE(res1);
  14228. ASSERT_EQ(200, res1->status);
  14229. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14230. // If-Modified-Since with invalid format should not result in 304
  14231. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14232. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14233. ASSERT_TRUE(res_bad);
  14234. EXPECT_EQ(200, res_bad->status);
  14235. // If-Range with invalid date format should be treated as mismatch -> full
  14236. // content (200)
  14237. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14238. {"If-Range", "invalid-date"}};
  14239. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14240. ASSERT_TRUE(res_ifrange);
  14241. EXPECT_EQ(200, res_ifrange->status);
  14242. svr.stop();
  14243. t.join();
  14244. std::remove(fname);
  14245. }
  14246. TEST(ETagTest, IfRangeWithMalformedETag) {
  14247. using namespace httplib;
  14248. const char *fname = "ifrange_malformed.txt";
  14249. const std::string content = "0123456789";
  14250. {
  14251. std::ofstream ofs(fname);
  14252. ofs << content;
  14253. ASSERT_TRUE(ofs.good());
  14254. }
  14255. Server svr;
  14256. svr.set_mount_point("/static", ".");
  14257. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14258. svr.wait_until_ready();
  14259. Client cli(HOST, PORT);
  14260. // First request: get ETag
  14261. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14262. ASSERT_TRUE(res1);
  14263. ASSERT_EQ(200, res1->status);
  14264. ASSERT_TRUE(res1->has_header("ETag"));
  14265. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14266. // full content (200)
  14267. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14268. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14269. ASSERT_TRUE(res2);
  14270. EXPECT_EQ(200, res2->status);
  14271. EXPECT_EQ(content, res2->body);
  14272. svr.stop();
  14273. t.join();
  14274. std::remove(fname);
  14275. }
  14276. TEST(ETagTest, ExtremeLargeDateValues) {
  14277. using namespace httplib;
  14278. const char *fname = "ims_extreme_date.txt";
  14279. const char *content = "ims-extreme-date";
  14280. {
  14281. std::ofstream ofs(fname);
  14282. ofs << content;
  14283. ASSERT_TRUE(ofs.good());
  14284. }
  14285. Server svr;
  14286. svr.set_mount_point("/static", ".");
  14287. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14288. svr.wait_until_ready();
  14289. Client cli(HOST, PORT);
  14290. auto res1 = cli.Get(std::string("/static/") + fname);
  14291. ASSERT_TRUE(res1);
  14292. ASSERT_EQ(200, res1->status);
  14293. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14294. // Extremely large year that may overflow date parsing routines.
  14295. Headers h_large_date = {
  14296. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14297. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14298. ASSERT_TRUE(res_bad);
  14299. // Expect server to treat this as invalid/mismatch and return full content
  14300. EXPECT_EQ(200, res_bad->status);
  14301. // If-Range with extremely large date should be treated as mismatch -> full
  14302. // content (200)
  14303. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14304. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14305. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14306. ASSERT_TRUE(res_ifrange);
  14307. EXPECT_EQ(200, res_ifrange->status);
  14308. svr.stop();
  14309. t.join();
  14310. std::remove(fname);
  14311. }
  14312. TEST(ETagTest, NegativeFileModificationTime) {
  14313. using namespace httplib;
  14314. const char *fname = "ims_negative_mtime.txt";
  14315. const std::string content = "negative-mtime";
  14316. {
  14317. std::ofstream ofs(fname);
  14318. ofs << content;
  14319. ASSERT_TRUE(ofs.good());
  14320. }
  14321. // Try to set file mtime to a negative value. This may fail on some
  14322. // platforms/filesystems; if it fails, the test will still verify server
  14323. // behaves safely by performing a regular conditional request.
  14324. #if defined(__APPLE__) || defined(__linux__)
  14325. bool set_negative = false;
  14326. do {
  14327. struct timeval times[2];
  14328. // access time: now
  14329. times[0].tv_sec = time(nullptr);
  14330. times[0].tv_usec = 0;
  14331. // modification time: negative (e.g., -1)
  14332. times[1].tv_sec = -1;
  14333. times[1].tv_usec = 0;
  14334. if (utimes(fname, times) == 0) { set_negative = true; }
  14335. } while (0);
  14336. #else
  14337. bool set_negative = false;
  14338. #endif
  14339. Server svr;
  14340. svr.set_mount_point("/static", ".");
  14341. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14342. svr.wait_until_ready();
  14343. Client cli(HOST, PORT);
  14344. auto res1 = cli.Get(std::string("/static/") + fname);
  14345. ASSERT_TRUE(res1);
  14346. ASSERT_EQ(200, res1->status);
  14347. bool has_last_modified = res1->has_header("Last-Modified");
  14348. std::string last_modified;
  14349. if (has_last_modified) {
  14350. last_modified = res1->get_header_value("Last-Modified");
  14351. }
  14352. if (set_negative) {
  14353. // If we successfully set a negative mtime, ensure server returns a
  14354. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14355. // with an old date and ensure server handles it without crash.
  14356. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14357. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14358. ASSERT_TRUE(res2);
  14359. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14360. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14361. } else {
  14362. // Could not set negative mtime on this platform; fall back to verifying
  14363. // that normal invalid/malformed dates are treated safely (non-304).
  14364. Headers h_bad_date = {
  14365. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14366. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14367. ASSERT_TRUE(res_bad);
  14368. EXPECT_EQ(200, res_bad->status);
  14369. }
  14370. svr.stop();
  14371. t.join();
  14372. std::remove(fname);
  14373. }
  14374. //==============================================================================
  14375. // SSE Parsing Tests
  14376. //==============================================================================
  14377. class SSEParsingTest : public ::testing::Test {
  14378. protected:
  14379. // Test helper that mimics SSE parsing behavior
  14380. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14381. int &retry_ms) {
  14382. // Blank line signals end of event
  14383. if (line.empty() || line == "\r") { return true; }
  14384. // Lines starting with ':' are comments (ignored)
  14385. if (!line.empty() && line[0] == ':') { return false; }
  14386. // Find the colon separator
  14387. auto colon_pos = line.find(':');
  14388. if (colon_pos == std::string::npos) {
  14389. // Line with no colon is treated as field name with empty value
  14390. return false;
  14391. }
  14392. std::string field = line.substr(0, colon_pos);
  14393. std::string value;
  14394. // Value starts after colon, skip optional single space
  14395. if (colon_pos + 1 < line.size()) {
  14396. size_t value_start = colon_pos + 1;
  14397. if (line[value_start] == ' ') { value_start++; }
  14398. value = line.substr(value_start);
  14399. // Remove trailing \r if present
  14400. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14401. }
  14402. // Handle known fields
  14403. if (field == "event") {
  14404. msg.event = value;
  14405. } else if (field == "data") {
  14406. // Multiple data lines are concatenated with newlines
  14407. if (!msg.data.empty()) { msg.data += "\n"; }
  14408. msg.data += value;
  14409. } else if (field == "id") {
  14410. // Empty id is valid (clears the last event ID)
  14411. msg.id = value;
  14412. } else if (field == "retry") {
  14413. // Parse retry interval in milliseconds
  14414. {
  14415. int v = 0;
  14416. auto res =
  14417. detail::from_chars(value.data(), value.data() + value.size(), v);
  14418. if (res.ec == std::errc{}) { retry_ms = v; }
  14419. }
  14420. }
  14421. // Unknown fields are ignored per SSE spec
  14422. return false;
  14423. }
  14424. };
  14425. // Test: Single-line data
  14426. TEST_F(SSEParsingTest, SingleLineData) {
  14427. sse::SSEMessage msg;
  14428. int retry_ms = 3000;
  14429. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14430. EXPECT_EQ(msg.data, "hello");
  14431. EXPECT_EQ(msg.event, "message");
  14432. // Blank line ends event
  14433. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14434. }
  14435. // Test: Multi-line data
  14436. TEST_F(SSEParsingTest, MultiLineData) {
  14437. sse::SSEMessage msg;
  14438. int retry_ms = 3000;
  14439. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14440. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14441. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14442. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14443. }
  14444. // Test: Custom event types
  14445. TEST_F(SSEParsingTest, CustomEventType) {
  14446. sse::SSEMessage msg;
  14447. int retry_ms = 3000;
  14448. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14449. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14450. EXPECT_EQ(msg.event, "update");
  14451. EXPECT_EQ(msg.data, "payload");
  14452. }
  14453. // Test: Event ID handling
  14454. TEST_F(SSEParsingTest, EventIdHandling) {
  14455. sse::SSEMessage msg;
  14456. int retry_ms = 3000;
  14457. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14458. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14459. EXPECT_EQ(msg.id, "12345");
  14460. }
  14461. // Test: Empty event ID (clears last event ID)
  14462. TEST_F(SSEParsingTest, EmptyEventId) {
  14463. sse::SSEMessage msg;
  14464. msg.id = "previous";
  14465. int retry_ms = 3000;
  14466. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14467. EXPECT_EQ(msg.id, "");
  14468. }
  14469. // Test: Retry field parsing
  14470. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14471. sse::SSEMessage msg;
  14472. int retry_ms = 3000;
  14473. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14474. EXPECT_EQ(retry_ms, 5000);
  14475. }
  14476. // Test: Invalid retry value
  14477. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14478. sse::SSEMessage msg;
  14479. int retry_ms = 3000;
  14480. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14481. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14482. }
  14483. // Test: Comments (lines starting with :)
  14484. TEST_F(SSEParsingTest, CommentsIgnored) {
  14485. sse::SSEMessage msg;
  14486. int retry_ms = 3000;
  14487. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14488. EXPECT_EQ(msg.data, "");
  14489. EXPECT_EQ(msg.event, "message");
  14490. }
  14491. // Test: Colon in value
  14492. TEST_F(SSEParsingTest, ColonInValue) {
  14493. sse::SSEMessage msg;
  14494. int retry_ms = 3000;
  14495. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14496. EXPECT_EQ(msg.data, "hello:world:test");
  14497. }
  14498. // Test: Line with no colon (field name only)
  14499. TEST_F(SSEParsingTest, FieldNameOnly) {
  14500. sse::SSEMessage msg;
  14501. int retry_ms = 3000;
  14502. // According to SSE spec, this is treated as field name with empty value
  14503. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14504. // Since we don't recognize "data" without colon, data should be empty
  14505. EXPECT_EQ(msg.data, "");
  14506. }
  14507. // Test: Trailing \r handling
  14508. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14509. sse::SSEMessage msg;
  14510. int retry_ms = 3000;
  14511. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14512. EXPECT_EQ(msg.data, "hello");
  14513. }
  14514. // Test: Unknown fields ignored
  14515. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14516. sse::SSEMessage msg;
  14517. int retry_ms = 3000;
  14518. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14519. EXPECT_EQ(msg.data, "");
  14520. EXPECT_EQ(msg.event, "message");
  14521. }
  14522. // Test: Space after colon is optional
  14523. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14524. sse::SSEMessage msg1, msg2;
  14525. int retry_ms = 3000;
  14526. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14527. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14528. EXPECT_EQ(msg1.data, "hello");
  14529. EXPECT_EQ(msg2.data, "hello");
  14530. }
  14531. // Test: SSEMessage clear
  14532. TEST_F(SSEParsingTest, MessageClear) {
  14533. sse::SSEMessage msg;
  14534. msg.event = "custom";
  14535. msg.data = "some data";
  14536. msg.id = "123";
  14537. msg.clear();
  14538. EXPECT_EQ(msg.event, "message");
  14539. EXPECT_EQ(msg.data, "");
  14540. EXPECT_EQ(msg.id, "");
  14541. }
  14542. // Test: Complete event parsing
  14543. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14544. sse::SSEMessage msg;
  14545. int retry_ms = 3000;
  14546. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14547. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14548. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14549. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14550. // Blank line ends event
  14551. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14552. EXPECT_EQ(msg.event, "notification");
  14553. EXPECT_EQ(msg.id, "evt-42");
  14554. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14555. EXPECT_EQ(retry_ms, 1000);
  14556. }
  14557. //==============================================================================
  14558. // Integration Tests with Server
  14559. //==============================================================================
  14560. class SSEIntegrationTest : public ::testing::Test {
  14561. protected:
  14562. void SetUp() override {
  14563. stop_server_.store(false);
  14564. events_.clear();
  14565. server_ = httplib::detail::make_unique<Server>();
  14566. setup_server();
  14567. start_server();
  14568. }
  14569. void TearDown() override {
  14570. stop_server_.store(true);
  14571. event_cv_.notify_all();
  14572. server_->stop();
  14573. if (server_thread_.joinable()) { server_thread_.join(); }
  14574. }
  14575. void setup_server() {
  14576. // Simple SSE endpoint
  14577. server_->Get("/events", [this](const Request &req, Response &res) {
  14578. auto last_id = req.get_header_value("Last-Event-ID");
  14579. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14580. res.set_chunked_content_provider(
  14581. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14582. std::unique_lock<std::mutex> lock(event_mutex_);
  14583. if (event_cv_.wait_for(
  14584. lock, std::chrono::milliseconds(200), [this] {
  14585. return !events_.empty() || stop_server_.load();
  14586. })) {
  14587. if (stop_server_.load()) { return false; }
  14588. if (!events_.empty()) {
  14589. std::string event = events_.front();
  14590. events_.erase(events_.begin());
  14591. sink.write(event.data(), event.size());
  14592. return true;
  14593. }
  14594. }
  14595. return !stop_server_.load();
  14596. });
  14597. });
  14598. // Endpoint that returns error
  14599. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14600. res.status = 500;
  14601. res.set_content("Internal Server Error", "text/plain");
  14602. });
  14603. // Endpoint for custom event types
  14604. server_->Get("/custom-events", [](const Request &, Response &res) {
  14605. res.set_chunked_content_provider(
  14606. "text/event-stream", [](size_t offset, DataSink &sink) {
  14607. if (offset == 0) {
  14608. std::string event = "event: update\ndata: updated\n\n"
  14609. "event: delete\ndata: deleted\n\n";
  14610. sink.write(event.data(), event.size());
  14611. }
  14612. return false; // End stream after sending
  14613. });
  14614. });
  14615. }
  14616. void start_server() {
  14617. port_ = server_->bind_to_any_port(HOST);
  14618. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14619. // Wait for server to start
  14620. while (!server_->is_running()) {
  14621. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14622. }
  14623. }
  14624. int get_port() const { return port_; }
  14625. void send_event(const std::string &event) {
  14626. std::lock_guard<std::mutex> lock(event_mutex_);
  14627. events_.push_back(event);
  14628. event_cv_.notify_all();
  14629. }
  14630. std::unique_ptr<Server> server_;
  14631. std::thread server_thread_;
  14632. std::mutex event_mutex_;
  14633. std::condition_variable event_cv_;
  14634. std::vector<std::string> events_;
  14635. std::atomic<bool> stop_server_{false};
  14636. std::string last_received_event_id_;
  14637. int port_ = 0;
  14638. };
  14639. // Test: Successful connection and on_open callback
  14640. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14641. // Add a simple endpoint that sends one event and closes
  14642. server_->Get("/simple-event", [](const Request &, Response &res) {
  14643. res.set_chunked_content_provider(
  14644. "text/event-stream", [](size_t offset, DataSink &sink) {
  14645. if (offset == 0) {
  14646. std::string event = "data: hello\n\n";
  14647. sink.write(event.data(), event.size());
  14648. }
  14649. return false; // Close stream after sending
  14650. });
  14651. });
  14652. Client client("localhost", get_port());
  14653. sse::SSEClient sse(client, "/simple-event");
  14654. std::atomic<bool> open_called{false};
  14655. std::atomic<bool> message_received{false};
  14656. sse.on_open([&open_called]() { open_called.store(true); });
  14657. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14658. if (msg.data == "hello") { message_received.store(true); }
  14659. });
  14660. sse.set_reconnect_interval(100);
  14661. sse.set_max_reconnect_attempts(1);
  14662. // Start async
  14663. sse.start_async();
  14664. // Wait for message to be processed
  14665. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14666. sse.stop();
  14667. EXPECT_TRUE(open_called.load());
  14668. EXPECT_TRUE(message_received.load());
  14669. }
  14670. // Test: on_message callback
  14671. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14672. // Endpoint that sends multiple events then closes
  14673. server_->Get("/multi-event", [](const Request &, Response &res) {
  14674. res.set_chunked_content_provider(
  14675. "text/event-stream", [](size_t offset, DataSink &sink) {
  14676. if (offset == 0) {
  14677. std::string events = "data: message1\n\ndata: message2\n\n";
  14678. sink.write(events.data(), events.size());
  14679. }
  14680. return false;
  14681. });
  14682. });
  14683. Client client("localhost", get_port());
  14684. sse::SSEClient sse(client, "/multi-event");
  14685. std::vector<std::string> received_messages;
  14686. std::mutex messages_mutex;
  14687. sse.on_message([&](const sse::SSEMessage &msg) {
  14688. std::lock_guard<std::mutex> lock(messages_mutex);
  14689. received_messages.push_back(msg.data);
  14690. });
  14691. sse.set_reconnect_interval(100);
  14692. sse.set_max_reconnect_attempts(1);
  14693. sse.start_async();
  14694. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14695. sse.stop();
  14696. std::lock_guard<std::mutex> lock(messages_mutex);
  14697. EXPECT_GE(received_messages.size(), 2u);
  14698. if (received_messages.size() >= 2) {
  14699. EXPECT_EQ(received_messages[0], "message1");
  14700. EXPECT_EQ(received_messages[1], "message2");
  14701. }
  14702. }
  14703. // Test: on_event for specific types
  14704. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14705. Client client("localhost", get_port());
  14706. sse::SSEClient sse(client, "/custom-events");
  14707. std::atomic<bool> update_received{false};
  14708. std::atomic<bool> delete_received{false};
  14709. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14710. if (msg.data == "updated") { update_received.store(true); }
  14711. });
  14712. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14713. if (msg.data == "deleted") { delete_received.store(true); }
  14714. });
  14715. sse.set_max_reconnect_attempts(1);
  14716. sse.start_async();
  14717. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14718. sse.stop();
  14719. EXPECT_TRUE(update_received.load());
  14720. EXPECT_TRUE(delete_received.load());
  14721. }
  14722. // Test: on_error callback on connection failure
  14723. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14724. // Connect to a non-existent port
  14725. Client client("localhost", 59999);
  14726. sse::SSEClient sse(client, "/events");
  14727. std::atomic<bool> error_called{false};
  14728. Error received_error = Error::Success;
  14729. sse.on_error([&](Error err) {
  14730. error_called.store(true);
  14731. received_error = err;
  14732. });
  14733. sse.set_reconnect_interval(50);
  14734. sse.set_max_reconnect_attempts(1);
  14735. sse.start_async();
  14736. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14737. sse.stop();
  14738. EXPECT_TRUE(error_called.load());
  14739. EXPECT_NE(received_error, Error::Success);
  14740. }
  14741. // Test: Last-Event-ID header sent on reconnect
  14742. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14743. // Endpoint that sends event with ID
  14744. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14745. res.set_chunked_content_provider(
  14746. "text/event-stream", [](size_t offset, DataSink &sink) {
  14747. if (offset == 0) {
  14748. std::string event = "id: evt-123\ndata: test\n\n";
  14749. sink.write(event.data(), event.size());
  14750. }
  14751. return false;
  14752. });
  14753. });
  14754. Client client("localhost", get_port());
  14755. sse::SSEClient sse(client, "/event-with-id");
  14756. std::atomic<bool> id_received{false};
  14757. sse.on_message([&](const sse::SSEMessage &msg) {
  14758. if (!msg.id.empty()) { id_received.store(true); }
  14759. });
  14760. sse.set_reconnect_interval(100);
  14761. sse.set_max_reconnect_attempts(1);
  14762. sse.start_async();
  14763. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14764. sse.stop();
  14765. EXPECT_TRUE(id_received.load());
  14766. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14767. }
  14768. // Test: Manual stop
  14769. TEST_F(SSEIntegrationTest, ManualStop) {
  14770. // Endpoint that sends one event and stays open briefly
  14771. std::atomic<bool> handler_running{true};
  14772. server_->Get("/stay-open", [&handler_running](const Request &,
  14773. Response &res) {
  14774. res.set_chunked_content_provider(
  14775. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14776. if (offset == 0) {
  14777. std::string event = "data: connected\n\n";
  14778. sink.write(event.data(), event.size());
  14779. }
  14780. // Keep connection open while handler_running is true
  14781. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14782. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14783. }
  14784. return false;
  14785. });
  14786. });
  14787. Client client("localhost", get_port());
  14788. sse::SSEClient sse(client, "/stay-open");
  14789. std::atomic<bool> connected{false};
  14790. sse.on_open([&connected]() { connected.store(true); });
  14791. sse.set_reconnect_interval(100);
  14792. sse.set_max_reconnect_attempts(1);
  14793. sse.start_async();
  14794. // Wait for connection to establish
  14795. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14796. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14797. }
  14798. EXPECT_TRUE(connected.load());
  14799. EXPECT_TRUE(sse.is_connected());
  14800. // Signal handler to stop
  14801. handler_running.store(false);
  14802. // Stop SSE client
  14803. sse.stop();
  14804. EXPECT_FALSE(sse.is_connected());
  14805. }
  14806. // Test: SSEClient with custom headers
  14807. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14808. // Setup a server endpoint that checks for custom header
  14809. std::atomic<bool> header_received{false};
  14810. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14811. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14812. header_received.store(true);
  14813. }
  14814. res.set_chunked_content_provider("text/event-stream",
  14815. [](size_t, DataSink &) { return false; });
  14816. });
  14817. Client client("localhost", get_port());
  14818. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14819. sse::SSEClient sse(client, "/header-check", headers);
  14820. sse.set_max_reconnect_attempts(1);
  14821. sse.start_async();
  14822. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14823. sse.stop();
  14824. EXPECT_TRUE(header_received.load());
  14825. }
  14826. // Test: Reconnect interval configuration
  14827. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14828. Client client("localhost", get_port());
  14829. sse::SSEClient sse(client, "/events");
  14830. auto &result = sse.set_reconnect_interval(500);
  14831. // Builder pattern should return reference to self
  14832. EXPECT_EQ(&result, &sse);
  14833. }
  14834. // Test: Max reconnect attempts
  14835. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14836. // Connect to non-existent port to force reconnects
  14837. Client client("localhost", 59998);
  14838. sse::SSEClient sse(client, "/events");
  14839. std::atomic<int> error_count{0};
  14840. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14841. sse.set_reconnect_interval(50);
  14842. sse.set_max_reconnect_attempts(2);
  14843. auto start = std::chrono::steady_clock::now();
  14844. sse.start(); // Blocking call
  14845. auto end = std::chrono::steady_clock::now();
  14846. // Should have stopped after 2 failed attempts
  14847. EXPECT_GE(error_count.load(), 2);
  14848. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14849. auto duration =
  14850. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14851. #ifdef _WIN32
  14852. // Windows is much slower for socket connection failures
  14853. EXPECT_LT(duration.count(), 7000);
  14854. #else
  14855. EXPECT_LT(duration.count(), 1000);
  14856. #endif
  14857. }
  14858. // Test: Multi-line data in integration
  14859. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14860. // Endpoint with multi-line data
  14861. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14862. res.set_chunked_content_provider(
  14863. "text/event-stream", [](size_t offset, DataSink &sink) {
  14864. if (offset == 0) {
  14865. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14866. sink.write(event.data(), event.size());
  14867. }
  14868. return false;
  14869. });
  14870. });
  14871. Client client("localhost", get_port());
  14872. sse::SSEClient sse(client, "/multiline-data");
  14873. std::string received_data;
  14874. std::mutex data_mutex;
  14875. sse.on_message([&](const sse::SSEMessage &msg) {
  14876. std::lock_guard<std::mutex> lock(data_mutex);
  14877. received_data = msg.data;
  14878. });
  14879. sse.set_reconnect_interval(100);
  14880. sse.set_max_reconnect_attempts(1);
  14881. sse.start_async();
  14882. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14883. sse.stop();
  14884. std::lock_guard<std::mutex> lock(data_mutex);
  14885. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14886. }
  14887. // Test: Auto-reconnect after server disconnection
  14888. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14889. std::atomic<int> connection_count{0};
  14890. std::atomic<int> message_count{0};
  14891. // Endpoint that sends one event and closes, forcing reconnect
  14892. server_->Get("/reconnect-test",
  14893. [&connection_count](const Request &, Response &res) {
  14894. connection_count.fetch_add(1);
  14895. res.set_chunked_content_provider(
  14896. "text/event-stream", [](size_t offset, DataSink &sink) {
  14897. if (offset == 0) {
  14898. std::string event = "data: hello\n\n";
  14899. sink.write(event.data(), event.size());
  14900. }
  14901. return false; // Close connection after sending
  14902. });
  14903. });
  14904. Client client("localhost", get_port());
  14905. sse::SSEClient sse(client, "/reconnect-test");
  14906. sse.on_message([&message_count](const sse::SSEMessage &) {
  14907. message_count.fetch_add(1);
  14908. });
  14909. sse.set_reconnect_interval(100);
  14910. sse.set_max_reconnect_attempts(3);
  14911. sse.start_async();
  14912. // Wait long enough for multiple reconnects
  14913. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14914. sse.stop();
  14915. // Should have connected multiple times (initial + reconnects)
  14916. EXPECT_GE(connection_count.load(), 2);
  14917. // Should have received messages from multiple connections
  14918. EXPECT_GE(message_count.load(), 2);
  14919. }
  14920. // Test: Last-Event-ID sent on reconnect
  14921. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14922. std::atomic<int> connection_count{0};
  14923. std::vector<std::string> received_last_event_ids;
  14924. std::mutex id_mutex;
  14925. // Endpoint that checks Last-Event-ID header and sends event with ID
  14926. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14927. int conn = connection_count.fetch_add(1);
  14928. // Capture the Last-Event-ID header from each connection
  14929. {
  14930. std::lock_guard<std::mutex> lock(id_mutex);
  14931. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14932. }
  14933. res.set_chunked_content_provider(
  14934. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14935. if (offset == 0) {
  14936. std::string event =
  14937. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14938. sink.write(event.data(), event.size());
  14939. }
  14940. return false;
  14941. });
  14942. });
  14943. Client client("localhost", get_port());
  14944. sse::SSEClient sse(client, "/reconnect-with-id");
  14945. sse.set_reconnect_interval(100);
  14946. sse.set_max_reconnect_attempts(3);
  14947. sse.start_async();
  14948. // Wait for at least 2 connections
  14949. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14950. sse.stop();
  14951. // Verify behavior
  14952. std::lock_guard<std::mutex> lock(id_mutex);
  14953. EXPECT_GE(received_last_event_ids.size(), 2u);
  14954. // First connection should have no Last-Event-ID
  14955. if (!received_last_event_ids.empty()) {
  14956. EXPECT_EQ(received_last_event_ids[0], "");
  14957. }
  14958. // Second connection should have Last-Event-ID from first connection
  14959. if (received_last_event_ids.size() >= 2) {
  14960. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14961. }
  14962. }
  14963. // Test: set_headers updates headers used on reconnect
  14964. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14965. std::vector<std::string> received_tokens;
  14966. std::mutex token_mutex;
  14967. // Endpoint that captures Authorization header
  14968. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14969. {
  14970. std::lock_guard<std::mutex> lock(token_mutex);
  14971. received_tokens.push_back(req.get_header_value("Authorization"));
  14972. }
  14973. res.set_chunked_content_provider(
  14974. "text/event-stream", [](size_t offset, DataSink &sink) {
  14975. if (offset == 0) {
  14976. std::string event = "data: hello\n\n";
  14977. sink.write(event.data(), event.size());
  14978. }
  14979. return false; // Close connection to trigger reconnect
  14980. });
  14981. });
  14982. Client client("localhost", get_port());
  14983. Headers headers = {{"Authorization", "Bearer old-token"}};
  14984. sse::SSEClient sse(client, "/auth-check", headers);
  14985. // Update headers on each successful connection
  14986. sse.on_open(
  14987. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14988. sse.set_reconnect_interval(100);
  14989. sse.set_max_reconnect_attempts(3);
  14990. sse.start_async();
  14991. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14992. sse.stop();
  14993. std::lock_guard<std::mutex> lock(token_mutex);
  14994. ASSERT_GE(received_tokens.size(), 2u);
  14995. // First connection uses original header
  14996. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14997. // Second connection uses updated header from set_headers
  14998. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14999. }
  15000. // Test: 401 allows reconnection (so on_error can refresh headers)
  15001. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15002. std::atomic<int> connection_count{0};
  15003. // Endpoint: returns 401 on first attempt, 200 on second
  15004. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15005. int conn = connection_count.fetch_add(1);
  15006. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15007. res.status = StatusCode::Unauthorized_401;
  15008. res.set_content("Unauthorized", "text/plain");
  15009. return;
  15010. }
  15011. res.set_chunked_content_provider(
  15012. "text/event-stream", [](size_t offset, DataSink &sink) {
  15013. if (offset == 0) {
  15014. std::string event = "data: authenticated\n\n";
  15015. sink.write(event.data(), event.size());
  15016. }
  15017. return false;
  15018. });
  15019. });
  15020. Client client("localhost", get_port());
  15021. Headers headers = {{"Authorization", "Bearer expired"}};
  15022. sse::SSEClient sse(client, "/auth-retry", headers);
  15023. std::atomic<bool> message_received{false};
  15024. // Refresh token on error
  15025. sse.on_error(
  15026. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15027. sse.on_message([&](const sse::SSEMessage &msg) {
  15028. if (msg.data == "authenticated") { message_received.store(true); }
  15029. });
  15030. sse.set_reconnect_interval(100);
  15031. sse.set_max_reconnect_attempts(3);
  15032. sse.start_async();
  15033. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15034. sse.stop();
  15035. // Should have reconnected after 401 and succeeded with new token
  15036. EXPECT_GE(connection_count.load(), 2);
  15037. EXPECT_TRUE(message_received.load());
  15038. }
  15039. TEST(Issue2318Test, EmptyHostString) {
  15040. {
  15041. httplib::Client cli_empty("", PORT);
  15042. auto res = cli_empty.Get("/");
  15043. ASSERT_FALSE(res);
  15044. EXPECT_EQ(httplib::Error::Connection, res.error());
  15045. }
  15046. {
  15047. httplib::Client cli(" ", PORT);
  15048. auto res = cli.Get("/");
  15049. ASSERT_FALSE(res);
  15050. EXPECT_EQ(httplib::Error::Connection, res.error());
  15051. }
  15052. }
  15053. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15054. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15055. Server svr;
  15056. // Set a small payload limit (1KB)
  15057. svr.set_payload_max_length(1024);
  15058. svr.Post("/test", [&](const Request &req, Response &res) {
  15059. res.set_content("Body size: " + std::to_string(req.body.size()),
  15060. "text/plain");
  15061. });
  15062. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15063. auto se = detail::scope_exit([&] {
  15064. svr.stop();
  15065. listen_thread.join();
  15066. });
  15067. svr.wait_until_ready();
  15068. // Create data that compresses well but exceeds limit when decompressed
  15069. // 8KB of repeated null bytes compresses to a very small size
  15070. std::string original_data(8 * 1024, '\0');
  15071. // Compress the data using gzip
  15072. std::string compressed_data;
  15073. detail::gzip_compressor compressor;
  15074. compressor.compress(original_data.data(), original_data.size(), true,
  15075. [&](const char *data, size_t size) {
  15076. compressed_data.append(data, size);
  15077. return true;
  15078. });
  15079. // Verify compression worked (compressed should be much smaller)
  15080. ASSERT_LT(compressed_data.size(), original_data.size());
  15081. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15082. // Send compressed data with Content-Encoding: gzip
  15083. Client cli(HOST, PORT);
  15084. Headers headers = {{"Content-Encoding", "gzip"}};
  15085. auto res =
  15086. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15087. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15088. ASSERT_TRUE(res);
  15089. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15090. }
  15091. #endif
  15092. // ============================================================================
  15093. // OpenSSL-Specific Tests
  15094. // ============================================================================
  15095. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15096. X509 *readCertificate(const std::string &strFileName) {
  15097. std::ifstream inStream(strFileName);
  15098. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15099. std::istreambuf_iterator<char>());
  15100. if (strCertPEM.empty()) return (nullptr);
  15101. BIO *pbCert = BIO_new(BIO_s_mem());
  15102. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15103. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15104. BIO_free(pbCert);
  15105. return (pCert);
  15106. }
  15107. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15108. std::ifstream inStream(strFileName);
  15109. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15110. std::istreambuf_iterator<char>());
  15111. if (strPrivateKeyPEM.empty()) return (nullptr);
  15112. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15113. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15114. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15115. BIO_free(pbPrivKey);
  15116. return (pPrivateKey);
  15117. }
  15118. TEST(BindServerTest, UpdateCerts) {
  15119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15120. int port = svr.bind_to_any_port("0.0.0.0");
  15121. ASSERT_TRUE(svr.is_valid());
  15122. ASSERT_TRUE(port > 0);
  15123. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15124. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15125. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15126. ASSERT_TRUE(cert != nullptr);
  15127. ASSERT_TRUE(ca_cert != nullptr);
  15128. ASSERT_TRUE(key != nullptr);
  15129. X509_STORE *cert_store = X509_STORE_new();
  15130. X509_STORE_add_cert(cert_store, ca_cert);
  15131. // svr.update_certs(cert, key, cert_store); // deprecated
  15132. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15133. CLIENT_CA_CERT_FILE);
  15134. ASSERT_TRUE(svr.is_valid());
  15135. svr.stop();
  15136. X509_STORE_free(cert_store);
  15137. X509_free(cert);
  15138. X509_free(ca_cert);
  15139. EVP_PKEY_free(key);
  15140. }
  15141. // Test that update_certs() updates client CA list correctly
  15142. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15143. // Start with file-based constructor
  15144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15145. ASSERT_TRUE(svr.is_valid());
  15146. // Initially no client CA list should be set
  15147. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15148. ASSERT_TRUE(ssl_ctx != nullptr);
  15149. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15150. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15151. EXPECT_EQ(0, count_before);
  15152. // Now update with client CA (PEM string)
  15153. std::string cert_pem, key_pem, ca_pem;
  15154. read_file(SERVER_CERT_FILE, cert_pem);
  15155. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15156. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15157. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15158. ASSERT_TRUE(svr.is_valid());
  15159. // Now client CA list should be set
  15160. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15161. ASSERT_TRUE(ca_list_after != nullptr);
  15162. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15163. }
  15164. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15165. // Test that the file-path SSLServer constructor properly sets the client CA
  15166. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15167. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15168. ASSERT_TRUE(svr.is_valid());
  15169. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15170. ASSERT_TRUE(ssl_ctx != nullptr);
  15171. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15172. ASSERT_TRUE(ca_list != nullptr);
  15173. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15174. }
  15175. #endif
  15176. // ============================================================================
  15177. // MbedTLS-Specific Tests
  15178. // ============================================================================
  15179. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15180. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15181. using namespace httplib::tls;
  15182. // Track if callback was invoked
  15183. bool callback_invoked = false;
  15184. // The callback receives void* ctx which is actually MbedTlsContext*
  15185. // We can access the mbedtls_ssl_config via the context
  15186. auto setup_callback = [&callback_invoked](void *ctx) {
  15187. callback_invoked = true;
  15188. // Cast to MbedTlsContext* to access the ssl config
  15189. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15190. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15191. // Use static variables to hold certificate data (simplified for test)
  15192. static mbedtls_x509_crt own_cert;
  15193. static mbedtls_pk_context own_key;
  15194. static mbedtls_x509_crt ca_chain;
  15195. static bool initialized = false;
  15196. if (!initialized) {
  15197. mbedtls_x509_crt_init(&own_cert);
  15198. mbedtls_pk_init(&own_key);
  15199. mbedtls_x509_crt_init(&ca_chain);
  15200. // Load server certificate
  15201. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15202. return false;
  15203. }
  15204. // Load server private key
  15205. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15206. #if MBEDTLS_VERSION_MAJOR >= 3
  15207. ,
  15208. mbedtls_ctr_drbg_random, nullptr
  15209. #endif
  15210. ) != 0) {
  15211. return false;
  15212. }
  15213. // Load CA chain for client verification
  15214. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15215. return false;
  15216. }
  15217. initialized = true;
  15218. }
  15219. // Configure the SSL config
  15220. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15221. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15222. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15223. // Set minimum TLS version using mbedTLS native API
  15224. #if MBEDTLS_VERSION_MAJOR >= 3
  15225. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15226. #else
  15227. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15228. MBEDTLS_SSL_MINOR_VERSION_3);
  15229. #endif
  15230. return true;
  15231. };
  15232. SSLServer svr(setup_callback);
  15233. ASSERT_TRUE(svr.is_valid());
  15234. ASSERT_TRUE(callback_invoked);
  15235. svr.Get("/test", [&](const Request &req, Response &res) {
  15236. res.set_content("test", "text/plain");
  15237. auto cert = req.peer_cert();
  15238. ASSERT_TRUE(static_cast<bool>(cert));
  15239. auto common_name = cert.subject_cn();
  15240. EXPECT_EQ("Common Name", common_name);
  15241. });
  15242. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15243. auto se = detail::scope_exit([&] {
  15244. svr.stop();
  15245. t.join();
  15246. ASSERT_FALSE(svr.is_running());
  15247. });
  15248. svr.wait_until_ready();
  15249. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15250. cli.enable_server_certificate_verification(false);
  15251. cli.set_connection_timeout(30);
  15252. auto res = cli.Get("/test");
  15253. ASSERT_TRUE(res);
  15254. ASSERT_EQ(StatusCode::OK_200, res->status);
  15255. }
  15256. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15257. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15258. // keep-alive SSL session, which reads through that config in
  15259. // mbedtls_ssl_close_notify.
  15260. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15262. ASSERT_TRUE(svr.is_valid());
  15263. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15264. res.set_content("test", "text/plain");
  15265. });
  15266. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15267. auto se = detail::scope_exit([&] {
  15268. svr.stop();
  15269. t.join();
  15270. ASSERT_FALSE(svr.is_running());
  15271. });
  15272. svr.wait_until_ready();
  15273. {
  15274. SSLClient cli(HOST, PORT);
  15275. cli.enable_server_certificate_verification(false);
  15276. cli.set_keep_alive(true);
  15277. auto res = cli.Get("/test");
  15278. ASSERT_TRUE(res);
  15279. ASSERT_EQ(StatusCode::OK_200, res->status);
  15280. // cli is destructed here with the keep-alive SSL session still open.
  15281. }
  15282. }
  15283. #endif
  15284. // WebSocket Tests
  15285. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15286. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15287. // defining the meaning of these bits has been negotiated.
  15288. auto make_frame = [](uint8_t first_byte) {
  15289. std::string frame;
  15290. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15291. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15292. frame += "Hello";
  15293. return frame;
  15294. };
  15295. // RSV1 set (0x40)
  15296. {
  15297. detail::BufferStream strm;
  15298. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15299. ws::Opcode opcode;
  15300. std::string payload;
  15301. bool fin;
  15302. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15303. false, 1024));
  15304. }
  15305. // RSV2 set (0x20)
  15306. {
  15307. detail::BufferStream strm;
  15308. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15309. ws::Opcode opcode;
  15310. std::string payload;
  15311. bool fin;
  15312. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15313. false, 1024));
  15314. }
  15315. // RSV3 set (0x10)
  15316. {
  15317. detail::BufferStream strm;
  15318. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15319. ws::Opcode opcode;
  15320. std::string payload;
  15321. bool fin;
  15322. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15323. false, 1024));
  15324. }
  15325. // No RSV bits set - should succeed
  15326. {
  15327. detail::BufferStream strm;
  15328. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15329. ws::Opcode opcode;
  15330. std::string payload;
  15331. bool fin;
  15332. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15333. false, 1024));
  15334. EXPECT_EQ(ws::Opcode::Text, opcode);
  15335. EXPECT_EQ("Hello", payload);
  15336. EXPECT_TRUE(fin);
  15337. }
  15338. }
  15339. TEST(WebSocketTest, ControlFrameValidation) {
  15340. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15341. // payload length <= 125.
  15342. // Ping with FIN=0 - must be rejected
  15343. {
  15344. detail::BufferStream strm;
  15345. std::string frame;
  15346. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15347. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15348. strm.write(frame.data(), frame.size());
  15349. ws::Opcode opcode;
  15350. std::string payload;
  15351. bool fin;
  15352. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15353. false, 1024));
  15354. }
  15355. // Close with FIN=0 - must be rejected
  15356. {
  15357. detail::BufferStream strm;
  15358. std::string frame;
  15359. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15360. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15361. strm.write(frame.data(), frame.size());
  15362. ws::Opcode opcode;
  15363. std::string payload;
  15364. bool fin;
  15365. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15366. false, 1024));
  15367. }
  15368. // Ping with payload_len=126 (extended length) - must be rejected
  15369. {
  15370. detail::BufferStream strm;
  15371. std::string frame;
  15372. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15373. frame += static_cast<char>(126); // payload_len=126 (>125)
  15374. frame += static_cast<char>(0x00); // extended length high byte
  15375. frame += static_cast<char>(126); // extended length low byte
  15376. frame += std::string(126, 'x');
  15377. strm.write(frame.data(), frame.size());
  15378. ws::Opcode opcode;
  15379. std::string payload;
  15380. bool fin;
  15381. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15382. false, 1024));
  15383. }
  15384. // Ping with FIN=1 and payload_len=125 - should succeed
  15385. {
  15386. detail::BufferStream strm;
  15387. std::string frame;
  15388. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15389. frame += static_cast<char>(125); // payload_len=125
  15390. frame += std::string(125, 'x');
  15391. strm.write(frame.data(), frame.size());
  15392. ws::Opcode opcode;
  15393. std::string payload;
  15394. bool fin;
  15395. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15396. false, 1024));
  15397. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15398. EXPECT_EQ(125u, payload.size());
  15399. EXPECT_TRUE(fin);
  15400. }
  15401. }
  15402. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15403. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15404. // length MUST be 0.
  15405. // MSB set - must be rejected
  15406. {
  15407. detail::BufferStream strm;
  15408. std::string frame;
  15409. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15410. frame += static_cast<char>(127); // 64-bit extended length
  15411. frame += static_cast<char>(0x80); // MSB set (invalid)
  15412. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15413. strm.write(frame.data(), frame.size());
  15414. ws::Opcode opcode;
  15415. std::string payload;
  15416. bool fin;
  15417. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15418. false, 1024));
  15419. }
  15420. // MSB clear - should pass length parsing (will be rejected by max_len,
  15421. // but that's a different check; use a small length to verify)
  15422. {
  15423. detail::BufferStream strm;
  15424. std::string frame;
  15425. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15426. frame += static_cast<char>(127); // 64-bit extended length
  15427. frame += std::string(7, '\0'); // high bytes = 0
  15428. frame += static_cast<char>(0x03); // length = 3
  15429. frame += "abc";
  15430. strm.write(frame.data(), frame.size());
  15431. ws::Opcode opcode;
  15432. std::string payload;
  15433. bool fin;
  15434. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15435. false, 1024));
  15436. EXPECT_EQ(ws::Opcode::Text, opcode);
  15437. EXPECT_EQ("abc", payload);
  15438. }
  15439. }
  15440. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15441. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15442. // Valid UTF-8
  15443. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15444. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15445. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15446. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15447. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15448. // Invalid UTF-8
  15449. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15450. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15451. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15452. EXPECT_FALSE(
  15453. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15454. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15455. }
  15456. TEST(WebSocketTest, ConnectAndDisconnect) {
  15457. Server svr;
  15458. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15459. std::string msg;
  15460. while (ws.read(msg)) {}
  15461. });
  15462. auto port = svr.bind_to_any_port(HOST);
  15463. std::thread t([&]() { svr.listen_after_bind(); });
  15464. svr.wait_until_ready();
  15465. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15466. ASSERT_TRUE(client.connect());
  15467. EXPECT_TRUE(client.is_open());
  15468. client.close();
  15469. EXPECT_FALSE(client.is_open());
  15470. svr.stop();
  15471. t.join();
  15472. }
  15473. TEST(WebSocketTest, ValidURL) {
  15474. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15475. EXPECT_TRUE(ws1.is_valid());
  15476. ws::WebSocketClient ws2("ws://example.com/path");
  15477. EXPECT_TRUE(ws2.is_valid());
  15478. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15479. EXPECT_TRUE(ws3.is_valid());
  15480. #ifdef CPPHTTPLIB_SSL_ENABLED
  15481. ws::WebSocketClient wss1("wss://example.com/path");
  15482. EXPECT_TRUE(wss1.is_valid());
  15483. ws::WebSocketClient wss2("wss://example.com:443/path");
  15484. EXPECT_TRUE(wss2.is_valid());
  15485. #endif
  15486. }
  15487. TEST(WebSocketTest, InvalidURL) {
  15488. // No scheme
  15489. ws::WebSocketClient ws1("localhost:8080/path");
  15490. EXPECT_FALSE(ws1.is_valid());
  15491. // No path
  15492. ws::WebSocketClient ws2("ws://localhost:8080");
  15493. EXPECT_FALSE(ws2.is_valid());
  15494. // Empty string
  15495. ws::WebSocketClient ws3("");
  15496. EXPECT_FALSE(ws3.is_valid());
  15497. // Missing host
  15498. ws::WebSocketClient ws4("ws://:8080/path");
  15499. EXPECT_FALSE(ws4.is_valid());
  15500. // Port number overflow — should not crash
  15501. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15502. EXPECT_FALSE(ws5.is_valid());
  15503. // Port out of range
  15504. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15505. EXPECT_FALSE(ws6.is_valid());
  15506. }
  15507. TEST(WebSocketTest, UnsupportedScheme) {
  15508. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15509. ws::WebSocketClient ws1("http://localhost:8080/path");
  15510. EXPECT_FALSE(ws1.is_valid());
  15511. ws::WebSocketClient ws2("https://localhost:8080/path");
  15512. EXPECT_FALSE(ws2.is_valid());
  15513. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15514. EXPECT_FALSE(ws3.is_valid());
  15515. #else
  15516. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15517. std::invalid_argument);
  15518. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15519. std::invalid_argument);
  15520. #endif
  15521. }
  15522. TEST(WebSocketTest, ConnectWhenInvalid) {
  15523. ws::WebSocketClient ws("not a valid url");
  15524. EXPECT_FALSE(ws.is_valid());
  15525. EXPECT_FALSE(ws.connect());
  15526. }
  15527. TEST(WebSocketTest, DefaultPort) {
  15528. ws::WebSocketClient ws1("ws://example.com/path");
  15529. EXPECT_TRUE(ws1.is_valid());
  15530. // ws:// defaults to port 80 (verified by successful parse)
  15531. #ifdef CPPHTTPLIB_SSL_ENABLED
  15532. ws::WebSocketClient ws2("wss://example.com/path");
  15533. EXPECT_TRUE(ws2.is_valid());
  15534. // wss:// defaults to port 443 (verified by successful parse)
  15535. #endif
  15536. }
  15537. TEST(WebSocketTest, IPv6LiteralAddress) {
  15538. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15539. EXPECT_TRUE(ws1.is_valid());
  15540. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15541. EXPECT_TRUE(ws2.is_valid());
  15542. }
  15543. TEST(WebSocketTest, ComplexPath) {
  15544. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15545. EXPECT_TRUE(ws1.is_valid());
  15546. ws::WebSocketClient ws2("ws://localhost:8080/");
  15547. EXPECT_TRUE(ws2.is_valid());
  15548. }
  15549. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15550. Server svr;
  15551. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15552. std::string msg;
  15553. while (ws.read(msg)) {}
  15554. });
  15555. auto port = svr.bind_to_any_port(HOST);
  15556. std::thread t([&]() { svr.listen_after_bind(); });
  15557. svr.wait_until_ready();
  15558. auto another_host = "example.com";
  15559. auto wrong_ip = "192.0.2.1";
  15560. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15561. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15562. ASSERT_TRUE(client.connect());
  15563. EXPECT_TRUE(client.is_open());
  15564. client.close();
  15565. svr.stop();
  15566. t.join();
  15567. }
  15568. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15569. Server svr;
  15570. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15571. std::string msg;
  15572. while (ws.read(msg)) {}
  15573. });
  15574. auto port = svr.bind_to_any_port(HOST);
  15575. std::thread t([&]() { svr.listen_after_bind(); });
  15576. svr.wait_until_ready();
  15577. auto wrong_ip = "192.0.2.1";
  15578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15579. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15580. client.set_connection_timeout(1);
  15581. client.set_read_timeout(1);
  15582. client.set_write_timeout(1);
  15583. EXPECT_FALSE(client.connect());
  15584. EXPECT_FALSE(client.is_open());
  15585. svr.stop();
  15586. t.join();
  15587. }
  15588. class WebSocketIntegrationTest : public ::testing::Test {
  15589. protected:
  15590. void SetUp() override {
  15591. server_ = httplib::detail::make_unique<Server>();
  15592. setup_server();
  15593. start_server();
  15594. }
  15595. void TearDown() override {
  15596. server_->stop();
  15597. if (server_thread_.joinable()) { server_thread_.join(); }
  15598. }
  15599. void setup_server() {
  15600. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15601. std::string msg;
  15602. ws::ReadResult ret;
  15603. while ((ret = ws.read(msg))) {
  15604. if (ret == ws::Binary) {
  15605. ws.send(msg.data(), msg.size());
  15606. } else {
  15607. ws.send(msg);
  15608. }
  15609. }
  15610. });
  15611. server_->WebSocket("/ws-echo-string",
  15612. [](const Request &, ws::WebSocket &ws) {
  15613. std::string msg;
  15614. while (ws.read(msg)) {
  15615. ws.send("echo: " + msg);
  15616. }
  15617. });
  15618. server_->WebSocket(
  15619. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15620. // Echo back request metadata
  15621. ws.send("path:" + req.path);
  15622. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15623. std::string msg;
  15624. while (ws.read(msg)) {}
  15625. });
  15626. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15627. std::string msg;
  15628. ws.read(msg); // wait for a message
  15629. ws.close();
  15630. });
  15631. server_->WebSocket("/ws-close-status",
  15632. [](const Request &, ws::WebSocket &ws) {
  15633. std::string msg;
  15634. ws.read(msg); // wait for a message
  15635. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15636. });
  15637. server_->WebSocket(
  15638. "/ws-subprotocol",
  15639. [](const Request &, ws::WebSocket &ws) {
  15640. std::string msg;
  15641. while (ws.read(msg)) {
  15642. ws.send(msg);
  15643. }
  15644. },
  15645. [](const std::vector<std::string> &protocols) -> std::string {
  15646. for (const auto &p : protocols) {
  15647. if (p == "graphql-ws") { return p; }
  15648. }
  15649. return "";
  15650. });
  15651. }
  15652. void start_server() {
  15653. port_ = server_->bind_to_any_port(HOST);
  15654. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15655. server_->wait_until_ready();
  15656. }
  15657. std::unique_ptr<Server> server_;
  15658. std::thread server_thread_;
  15659. int port_ = 0;
  15660. };
  15661. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15662. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15663. "/ws-echo");
  15664. ASSERT_TRUE(client.connect());
  15665. ASSERT_TRUE(client.is_open());
  15666. ASSERT_TRUE(client.send("Hello WebSocket"));
  15667. std::string msg;
  15668. EXPECT_EQ(ws::Text, client.read(msg));
  15669. EXPECT_EQ("Hello WebSocket", msg);
  15670. client.close();
  15671. }
  15672. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15674. "/ws-echo");
  15675. ASSERT_TRUE(client.connect());
  15676. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15677. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15678. std::string msg;
  15679. EXPECT_EQ(ws::Binary, client.read(msg));
  15680. EXPECT_EQ(binary_data, msg);
  15681. client.close();
  15682. }
  15683. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15685. "/ws-echo");
  15686. ASSERT_TRUE(client.connect());
  15687. for (int i = 0; i < 10; i++) {
  15688. auto text = "message " + std::to_string(i);
  15689. ASSERT_TRUE(client.send(text));
  15690. std::string msg;
  15691. ASSERT_TRUE(client.read(msg));
  15692. EXPECT_EQ(text, msg);
  15693. }
  15694. client.close();
  15695. }
  15696. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15697. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15698. "/ws-close");
  15699. ASSERT_TRUE(client.connect());
  15700. // Send a message to trigger the server to close
  15701. ASSERT_TRUE(client.send("trigger close"));
  15702. // The server will close, so read should return false
  15703. std::string msg;
  15704. EXPECT_FALSE(client.read(msg));
  15705. EXPECT_FALSE(client.is_open());
  15706. }
  15707. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15708. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15709. "/ws-echo");
  15710. ASSERT_TRUE(client.connect());
  15711. // 128KB message
  15712. std::string large_data(128 * 1024, 'X');
  15713. ASSERT_TRUE(client.send(large_data));
  15714. std::string msg;
  15715. ASSERT_TRUE(client.read(msg));
  15716. EXPECT_EQ(large_data, msg);
  15717. client.close();
  15718. }
  15719. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15721. "/ws-echo");
  15722. ASSERT_TRUE(client.connect());
  15723. const int num_threads = 4;
  15724. std::vector<std::thread> threads;
  15725. std::atomic<int> send_count{0};
  15726. for (int t = 0; t < num_threads; t++) {
  15727. threads.emplace_back([&client, &send_count, t]() {
  15728. for (int i = 0; i < 5; i++) {
  15729. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15730. if (client.send(text)) { send_count++; }
  15731. }
  15732. });
  15733. }
  15734. for (auto &th : threads) {
  15735. th.join();
  15736. }
  15737. int received = 0;
  15738. std::string msg;
  15739. while (received < send_count.load()) {
  15740. if (!client.read(msg)) { break; }
  15741. received++;
  15742. }
  15743. EXPECT_EQ(send_count.load(), received);
  15744. client.close();
  15745. }
  15746. TEST_F(WebSocketIntegrationTest, ReadString) {
  15747. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15748. "/ws-echo-string");
  15749. ASSERT_TRUE(client.connect());
  15750. ASSERT_TRUE(client.send("hello"));
  15751. std::string msg;
  15752. ASSERT_TRUE(client.read(msg));
  15753. EXPECT_EQ("echo: hello", msg);
  15754. ASSERT_TRUE(client.send("world"));
  15755. ASSERT_TRUE(client.read(msg));
  15756. EXPECT_EQ("echo: world", msg);
  15757. client.close();
  15758. }
  15759. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15760. Headers headers = {{"X-Test-Header", "test-value"}};
  15761. ws::WebSocketClient client(
  15762. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15763. ASSERT_TRUE(client.connect());
  15764. std::string msg;
  15765. ASSERT_TRUE(client.read(msg));
  15766. EXPECT_EQ("path:/ws-request-info", msg);
  15767. ASSERT_TRUE(client.read(msg));
  15768. EXPECT_EQ("header:test-value", msg);
  15769. client.close();
  15770. }
  15771. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15772. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15773. "/ws-echo");
  15774. client.set_read_timeout(1, 0); // 1 second
  15775. ASSERT_TRUE(client.connect());
  15776. // Don't send anything — server echo handler waits for a message,
  15777. // so read() should time out and return false.
  15778. std::string msg;
  15779. EXPECT_FALSE(client.read(msg));
  15780. }
  15781. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15782. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15783. "/ws-echo");
  15784. client.set_read_timeout(5, 0);
  15785. ASSERT_TRUE(client.connect());
  15786. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15787. // The server should reject it and close the connection.
  15788. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15789. client.send(oversized);
  15790. // The server's read() should have failed due to payload limit,
  15791. // so our read() should return false (connection closed).
  15792. std::string msg;
  15793. EXPECT_FALSE(client.read(msg));
  15794. }
  15795. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15796. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15797. "/ws-echo");
  15798. client.set_read_timeout(10, 0);
  15799. ASSERT_TRUE(client.connect());
  15800. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15801. // This should succeed.
  15802. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15803. ASSERT_TRUE(client.send(at_limit));
  15804. std::string msg;
  15805. ASSERT_TRUE(client.read(msg));
  15806. EXPECT_EQ(at_limit.size(), msg.size());
  15807. client.close();
  15808. }
  15809. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15810. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15811. "/nonexistent");
  15812. EXPECT_FALSE(client.connect());
  15813. EXPECT_FALSE(client.is_open());
  15814. }
  15815. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15817. "/ws-echo");
  15818. ASSERT_TRUE(client.connect());
  15819. ASSERT_TRUE(client.send(""));
  15820. std::string msg;
  15821. EXPECT_EQ(ws::Text, client.read(msg));
  15822. EXPECT_EQ("", msg);
  15823. client.close();
  15824. }
  15825. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15826. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15827. "/ws-echo");
  15828. // First connection
  15829. ASSERT_TRUE(client.connect());
  15830. ASSERT_TRUE(client.send("first"));
  15831. std::string msg;
  15832. ASSERT_TRUE(client.read(msg));
  15833. EXPECT_EQ("first", msg);
  15834. client.close();
  15835. EXPECT_FALSE(client.is_open());
  15836. // Reconnect using the same client object
  15837. ASSERT_TRUE(client.connect());
  15838. ASSERT_TRUE(client.is_open());
  15839. ASSERT_TRUE(client.send("second"));
  15840. ASSERT_TRUE(client.read(msg));
  15841. EXPECT_EQ("second", msg);
  15842. client.close();
  15843. }
  15844. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15845. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15846. "/ws-close-status");
  15847. ASSERT_TRUE(client.connect());
  15848. // Trigger the server to close with GoingAway status
  15849. ASSERT_TRUE(client.send("trigger"));
  15850. // read() should return false after receiving the close frame
  15851. std::string msg;
  15852. EXPECT_FALSE(client.read(msg));
  15853. EXPECT_FALSE(client.is_open());
  15854. }
  15855. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15857. "/ws-echo");
  15858. ASSERT_TRUE(client.connect());
  15859. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15860. EXPECT_FALSE(client.is_open());
  15861. }
  15862. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15863. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15864. ws::WebSocketClient client(
  15865. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15866. ASSERT_TRUE(client.connect());
  15867. // Server should have selected graphql-ws
  15868. EXPECT_EQ("graphql-ws", client.subprotocol());
  15869. client.close();
  15870. }
  15871. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15872. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15873. ws::WebSocketClient client(
  15874. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15875. ASSERT_TRUE(client.connect());
  15876. // Server should not have selected any subprotocol
  15877. EXPECT_TRUE(client.subprotocol().empty());
  15878. client.close();
  15879. }
  15880. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15881. // Connect without requesting any subprotocol
  15882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15883. "/ws-subprotocol");
  15884. ASSERT_TRUE(client.connect());
  15885. EXPECT_TRUE(client.subprotocol().empty());
  15886. client.close();
  15887. }
  15888. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15890. "/ws-echo");
  15891. client.set_tcp_nodelay(true);
  15892. client.set_connection_timeout(3, 0);
  15893. bool socket_options_called = false;
  15894. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15895. ASSERT_TRUE(client.connect());
  15896. ASSERT_TRUE(client.is_open());
  15897. EXPECT_TRUE(socket_options_called);
  15898. ASSERT_TRUE(client.send("hello"));
  15899. std::string msg;
  15900. auto result = client.read(msg);
  15901. EXPECT_EQ(result, ws::ReadResult::Text);
  15902. EXPECT_EQ(msg, "hello");
  15903. client.close();
  15904. }
  15905. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15906. Server svr;
  15907. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15908. if (!req.has_header("Authorization")) {
  15909. res.status = StatusCode::Unauthorized_401;
  15910. res.set_content("Unauthorized", "text/plain");
  15911. return Server::HandlerResponse::Handled;
  15912. }
  15913. return Server::HandlerResponse::Unhandled;
  15914. });
  15915. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15916. std::string msg;
  15917. while (ws.read(msg)) {
  15918. ws.send(msg);
  15919. }
  15920. });
  15921. auto port = svr.bind_to_any_port("localhost");
  15922. std::thread t([&]() { svr.listen_after_bind(); });
  15923. svr.wait_until_ready();
  15924. // Without Authorization header - should be rejected before upgrade
  15925. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15926. EXPECT_FALSE(client1.connect());
  15927. // With Authorization header - should succeed
  15928. Headers headers = {{"Authorization", "Bearer token123"}};
  15929. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15930. headers);
  15931. ASSERT_TRUE(client2.connect());
  15932. ASSERT_TRUE(client2.send("hello"));
  15933. std::string msg;
  15934. ASSERT_TRUE(client2.read(msg));
  15935. EXPECT_EQ("hello", msg);
  15936. client2.close();
  15937. svr.stop();
  15938. t.join();
  15939. }
  15940. TEST(WebSocketTest, QueryStringInHandshake) {
  15941. Server svr;
  15942. std::mutex mtx;
  15943. std::string received_target;
  15944. std::string received_token;
  15945. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15946. {
  15947. std::lock_guard<std::mutex> lock(mtx);
  15948. received_target = req.target;
  15949. if (req.has_param("token")) {
  15950. received_token = req.get_param_value("token");
  15951. }
  15952. }
  15953. std::string msg;
  15954. while (ws.read(msg)) {
  15955. ws.send(msg);
  15956. }
  15957. });
  15958. auto port = svr.bind_to_any_port("localhost");
  15959. std::thread t([&]() { svr.listen_after_bind(); });
  15960. svr.wait_until_ready();
  15961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15962. "/ws?token=ABC&session=123");
  15963. ASSERT_TRUE(client.connect());
  15964. // Round-trip ensures the handler has run and captured the request.
  15965. ASSERT_TRUE(client.send("hello"));
  15966. std::string msg;
  15967. ASSERT_TRUE(client.read(msg));
  15968. EXPECT_EQ("hello", msg);
  15969. client.close();
  15970. {
  15971. std::lock_guard<std::mutex> lock(mtx);
  15972. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15973. EXPECT_EQ("ABC", received_token);
  15974. }
  15975. svr.stop();
  15976. t.join();
  15977. }
  15978. TEST(WebSocketTest, HostHeaderInHandshake) {
  15979. Server svr;
  15980. std::mutex mtx;
  15981. std::string received_host;
  15982. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15983. {
  15984. std::lock_guard<std::mutex> lock(mtx);
  15985. received_host = req.get_header_value("Host");
  15986. }
  15987. std::string msg;
  15988. while (ws.read(msg)) {
  15989. ws.send(msg);
  15990. }
  15991. });
  15992. auto port = svr.bind_to_any_port("localhost");
  15993. std::thread t([&]() { svr.listen_after_bind(); });
  15994. svr.wait_until_ready();
  15995. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15996. ASSERT_TRUE(client.connect());
  15997. // Round-trip ensures the handler has run and captured the request.
  15998. ASSERT_TRUE(client.send("hello"));
  15999. std::string msg;
  16000. ASSERT_TRUE(client.read(msg));
  16001. client.close();
  16002. {
  16003. std::lock_guard<std::mutex> lock(mtx);
  16004. // Non-default port must be present in the Host header. Default ports
  16005. // (80/443) are omitted; that logic is covered by
  16006. // MakeHostAndPortStringTest.
  16007. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16008. }
  16009. svr.stop();
  16010. t.join();
  16011. }
  16012. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16013. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16014. protected:
  16015. void SetUp() override {
  16016. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16017. SERVER_PRIVATE_KEY_FILE);
  16018. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16019. std::string msg;
  16020. ws::ReadResult ret;
  16021. while ((ret = ws.read(msg))) {
  16022. if (ret == ws::Binary) {
  16023. ws.send(msg.data(), msg.size());
  16024. } else {
  16025. ws.send(msg);
  16026. }
  16027. }
  16028. });
  16029. port_ = server_->bind_to_any_port(HOST);
  16030. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16031. server_->wait_until_ready();
  16032. }
  16033. void TearDown() override {
  16034. server_->stop();
  16035. if (server_thread_.joinable()) { server_thread_.join(); }
  16036. }
  16037. std::unique_ptr<SSLServer> server_;
  16038. std::thread server_thread_;
  16039. int port_ = 0;
  16040. };
  16041. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16042. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16043. "/ws-echo");
  16044. client.enable_server_certificate_verification(false);
  16045. ASSERT_TRUE(client.connect());
  16046. ASSERT_TRUE(client.is_open());
  16047. ASSERT_TRUE(client.send("Hello WSS"));
  16048. std::string msg;
  16049. EXPECT_EQ(ws::Text, client.read(msg));
  16050. EXPECT_EQ("Hello WSS", msg);
  16051. client.close();
  16052. }
  16053. #endif
  16054. #ifdef CPPHTTPLIB_SSL_ENABLED
  16055. class WebSocketSSLCATest : public ::testing::Test {
  16056. protected:
  16057. void SetUp() override {
  16058. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16059. SERVER_PRIVATE_KEY_FILE);
  16060. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16061. std::string msg;
  16062. while (ws.read(msg)) {
  16063. ws.send(msg);
  16064. }
  16065. });
  16066. port_ = server_->bind_to_any_port("127.0.0.1");
  16067. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16068. server_->wait_until_ready();
  16069. }
  16070. void TearDown() override {
  16071. server_->stop();
  16072. if (server_thread_.joinable()) { server_thread_.join(); }
  16073. }
  16074. std::string url() const {
  16075. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16076. }
  16077. std::unique_ptr<SSLServer> server_;
  16078. std::thread server_thread_;
  16079. int port_ = 0;
  16080. };
  16081. // A custom CA loaded as PEM verifies the server with full certificate
  16082. // verification enabled
  16083. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16084. ws::WebSocketClient client(url());
  16085. std::string cert;
  16086. read_file(SERVER_CERT2_FILE, cert);
  16087. client.load_ca_cert_store(cert.c_str(), cert.size());
  16088. ASSERT_TRUE(client.connect());
  16089. ASSERT_TRUE(client.send("hello"));
  16090. std::string msg;
  16091. EXPECT_EQ(ws::Text, client.read(msg));
  16092. EXPECT_EQ("hello", msg);
  16093. client.close();
  16094. }
  16095. // A custom CA that does not cover the server must fail verification (the
  16096. // custom CA is exclusive; system certs are not loaded alongside it)
  16097. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16098. ws::WebSocketClient client(url());
  16099. std::string cert;
  16100. read_file(CLIENT_CA_CERT_FILE, cert);
  16101. client.load_ca_cert_store(cert.c_str(), cert.size());
  16102. ASSERT_FALSE(client.connect());
  16103. }
  16104. // Regression test: reconnecting with a native custom CA store used to reuse
  16105. // a store handle the previous TLS context had already freed (use-after-free
  16106. // under the OpenSSL backend). The context now lives as long as the client.
  16107. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16108. ws::WebSocketClient client(url());
  16109. std::string cert;
  16110. read_file(SERVER_CERT2_FILE, cert);
  16111. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16112. ASSERT_TRUE(client.connect());
  16113. client.close();
  16114. ASSERT_TRUE(client.connect());
  16115. ASSERT_TRUE(client.send("again"));
  16116. std::string msg;
  16117. EXPECT_EQ(ws::Text, client.read(msg));
  16118. EXPECT_EQ("again", msg);
  16119. client.close();
  16120. }
  16121. // Regression test: a certificate with a trusted chain but no identity match
  16122. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16123. // verification entirely for IP hosts, so this connection succeeded there.
  16124. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16125. // chain verification while the identity check must still fail.
  16126. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16128. ASSERT_TRUE(svr.is_valid());
  16129. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16130. std::string msg;
  16131. while (ws.read(msg)) {
  16132. ws.send(msg);
  16133. }
  16134. });
  16135. auto port = svr.bind_to_any_port("127.0.0.1");
  16136. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16137. auto se = detail::scope_exit([&] {
  16138. svr.stop();
  16139. t.join();
  16140. });
  16141. svr.wait_until_ready();
  16142. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16143. "/echo");
  16144. std::string cert;
  16145. read_file(SERVER_CERT_FILE, cert);
  16146. client.load_ca_cert_store(cert.c_str(), cert.size());
  16147. ASSERT_FALSE(client.connect());
  16148. }
  16149. #endif
  16150. #if !defined(_WIN32)
  16151. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16152. auto secret_dir = std::string("./symlink_test_secret");
  16153. auto served_dir = std::string("./symlink_test_served");
  16154. auto secret_file = secret_dir + "/secret.txt";
  16155. auto symlink_path = served_dir + "/escape";
  16156. // Setup: create directories and files
  16157. mkdir(secret_dir.c_str(), 0755);
  16158. mkdir(served_dir.c_str(), 0755);
  16159. {
  16160. std::ofstream ofs(secret_file);
  16161. ofs << "SECRET_DATA";
  16162. }
  16163. // Create symlink using absolute path so it resolves correctly
  16164. #ifdef PATH_MAX
  16165. char abs_secret[PATH_MAX];
  16166. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16167. #else
  16168. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16169. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16170. ASSERT_NE(nullptr, abs_secret);
  16171. #endif
  16172. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16173. auto se = detail::scope_exit([&] {
  16174. unlink(symlink_path.c_str());
  16175. unlink(secret_file.c_str());
  16176. rmdir(served_dir.c_str());
  16177. rmdir(secret_dir.c_str());
  16178. });
  16179. Server svr;
  16180. svr.set_mount_point("/", served_dir);
  16181. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16182. auto se2 = detail::scope_exit([&] {
  16183. svr.stop();
  16184. listen_thread.join();
  16185. });
  16186. svr.wait_until_ready();
  16187. Client cli("localhost", PORT);
  16188. // Symlink pointing outside base dir should be blocked
  16189. auto res = cli.Get("/escape/secret.txt");
  16190. ASSERT_TRUE(res);
  16191. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16192. }
  16193. #endif
  16194. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16195. // A GET request with Content-Length to a static file handler must have its
  16196. // body drained before the keep-alive connection is reused. Otherwise the
  16197. // unread body bytes are interpreted as the next HTTP request.
  16198. //
  16199. // The body is sent AFTER receiving the first response (as in the original
  16200. // PoC) so that the stream_line_reader cannot buffer it together with the
  16201. // headers of the first request.
  16202. Server svr;
  16203. svr.set_mount_point("/", "./www");
  16204. std::atomic<int> smuggled_count(0);
  16205. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16206. smuggled_count++;
  16207. res.set_content("oops", "text/plain");
  16208. });
  16209. auto port = svr.bind_to_any_port("localhost");
  16210. thread t = thread([&] { svr.listen_after_bind(); });
  16211. auto se = detail::scope_exit([&] {
  16212. svr.stop();
  16213. t.join();
  16214. });
  16215. svr.wait_until_ready();
  16216. auto error = Error::Success;
  16217. auto sock = detail::create_client_socket(
  16218. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16219. /*connection_timeout_sec=*/2, 0,
  16220. /*read_timeout_sec=*/2, 0,
  16221. /*write_timeout_sec=*/2, 0, std::string(), error);
  16222. ASSERT_NE(INVALID_SOCKET, sock);
  16223. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16224. // The "smuggled" request will be sent as the body of the outer GET
  16225. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16226. "Host: localhost\r\n"
  16227. "Connection: close\r\n"
  16228. "\r\n";
  16229. // Step 1: Send only the outer request headers (no body yet)
  16230. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16231. "Host: localhost\r\n"
  16232. "Content-Length: " +
  16233. std::to_string(smuggled.size()) +
  16234. "\r\n"
  16235. "\r\n";
  16236. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16237. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16238. // Step 2: Read the first response (server serves file without reading body)
  16239. std::string first_response;
  16240. char buf[4096];
  16241. for (;;) {
  16242. auto n = recv(sock, buf, sizeof(buf), 0);
  16243. if (n <= 0) break;
  16244. first_response.append(buf, static_cast<size_t>(n));
  16245. // Stop once we have a complete response (headers + body)
  16246. auto hdr_end = first_response.find("\r\n\r\n");
  16247. if (hdr_end != std::string::npos) {
  16248. // Check for Content-Length to know when the body is complete
  16249. auto cl_pos = first_response.find("Content-Length:");
  16250. if (cl_pos != std::string::npos) {
  16251. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16252. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16253. auto cl = std::stoul(
  16254. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16255. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16256. } else {
  16257. break; // No Content-Length, assume headers-only response
  16258. }
  16259. }
  16260. }
  16261. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16262. // Step 3: Now send the body, which looks like a new HTTP request.
  16263. // On a vulnerable server the keep-alive loop reads this as a second request.
  16264. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16265. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16266. // Step 4: Try to read a second response (should NOT exist after fix)
  16267. std::string second_response;
  16268. for (;;) {
  16269. auto n = recv(sock, buf, sizeof(buf), 0);
  16270. if (n <= 0) break;
  16271. second_response.append(buf, static_cast<size_t>(n));
  16272. }
  16273. // The smuggled request must NOT have been processed
  16274. EXPECT_EQ(0, smuggled_count.load());
  16275. }
  16276. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16277. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16278. // must be rejected with 400 Bad Request.
  16279. Server svr;
  16280. svr.Post("/test", [&](const Request &, Response &res) {
  16281. res.set_content("ok", "text/plain");
  16282. });
  16283. thread t = thread([&] { svr.listen(HOST, PORT); });
  16284. auto se = detail::scope_exit([&] {
  16285. svr.stop();
  16286. t.join();
  16287. ASSERT_FALSE(svr.is_running());
  16288. });
  16289. svr.wait_until_ready();
  16290. // Exact "chunked"
  16291. {
  16292. auto req = "POST /test HTTP/1.1\r\n"
  16293. "Host: localhost\r\n"
  16294. "Content-Length: 5\r\n"
  16295. "Transfer-Encoding: chunked\r\n"
  16296. "Connection: close\r\n"
  16297. "\r\n"
  16298. "hello";
  16299. std::string response;
  16300. ASSERT_TRUE(send_request(1, req, &response));
  16301. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16302. response.substr(0, response.find("\r\n")));
  16303. }
  16304. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16305. {
  16306. auto req = "POST /test HTTP/1.1\r\n"
  16307. "Host: localhost\r\n"
  16308. "Content-Length: 5\r\n"
  16309. "Transfer-Encoding: gzip, chunked\r\n"
  16310. "Connection: close\r\n"
  16311. "\r\n"
  16312. "hello";
  16313. std::string response;
  16314. ASSERT_TRUE(send_request(1, req, &response));
  16315. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16316. response.substr(0, response.find("\r\n")));
  16317. }
  16318. }
  16319. // Regression for issue #2450: a DELETE without Content-Length on a
  16320. // keep-alive connection must not let the post-response drain consume the
  16321. // next request's bytes.
  16322. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16323. Server svr;
  16324. std::atomic<int> delete_count(0);
  16325. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16326. delete_count++;
  16327. res.status = StatusCode::NoContent_204;
  16328. });
  16329. auto port = svr.bind_to_any_port(HOST);
  16330. thread t = thread([&] { svr.listen_after_bind(); });
  16331. auto se = detail::scope_exit([&] {
  16332. svr.stop();
  16333. t.join();
  16334. });
  16335. svr.wait_until_ready();
  16336. auto error = Error::Success;
  16337. auto sock = detail::create_client_socket(
  16338. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16339. /*connection_timeout_sec=*/2, 0,
  16340. /*read_timeout_sec=*/2, 0,
  16341. /*write_timeout_sec=*/2, 0, std::string(), error);
  16342. ASSERT_NE(INVALID_SOCKET, sock);
  16343. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16344. auto send_request_and_read_response = [&](const std::string &req,
  16345. std::string &out) -> bool {
  16346. auto sent = send(sock, req.data(), req.size(), 0);
  16347. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16348. char buf[4096];
  16349. for (;;) {
  16350. auto n = recv(sock, buf, sizeof(buf), 0);
  16351. if (n <= 0) { return !out.empty(); }
  16352. out.append(buf, static_cast<size_t>(n));
  16353. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16354. }
  16355. };
  16356. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16357. "Host: localhost\r\n"
  16358. "\r\n";
  16359. std::string resp1;
  16360. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16361. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16362. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16363. "Host: localhost\r\n"
  16364. "Connection: close\r\n"
  16365. "\r\n";
  16366. std::string resp2;
  16367. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16368. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16369. EXPECT_EQ(2, delete_count.load());
  16370. }
  16371. namespace no_proxy_test {
  16372. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16373. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16374. // calling listen().
  16375. class ScopedServer {
  16376. public:
  16377. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16378. ~ScopedServer() {
  16379. svr_.stop();
  16380. if (th_.joinable()) { th_.join(); }
  16381. }
  16382. Server &svr() { return svr_; }
  16383. int port() const { return port_; }
  16384. void listen() {
  16385. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16386. svr_.wait_until_ready();
  16387. }
  16388. private:
  16389. Server svr_;
  16390. std::thread th_;
  16391. int port_ = 0;
  16392. };
  16393. class ProxyAndTargetServers {
  16394. public:
  16395. ProxyAndTargetServers() {
  16396. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16397. proxy_hits_++;
  16398. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16399. res.set_content("via-proxy", "text/plain");
  16400. });
  16401. target_.Get(".*", [this](const Request &req, Response &res) {
  16402. target_hits_++;
  16403. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16404. res.set_content("direct", "text/plain");
  16405. });
  16406. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16407. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16408. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16409. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16410. proxy_mock_.wait_until_ready();
  16411. target_.wait_until_ready();
  16412. }
  16413. ~ProxyAndTargetServers() {
  16414. proxy_mock_.stop();
  16415. target_.stop();
  16416. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16417. if (target_thread_.joinable()) { target_thread_.join(); }
  16418. }
  16419. Server &proxy_mock() { return proxy_mock_; }
  16420. Server &target() { return target_; }
  16421. int proxy_port() const { return proxy_port_; }
  16422. int target_port() const { return target_port_; }
  16423. int proxy_hits() const { return proxy_hits_.load(); }
  16424. int target_hits() const { return target_hits_.load(); }
  16425. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16426. void reset_counters() {
  16427. proxy_hits_ = 0;
  16428. target_hits_ = 0;
  16429. last_had_proxy_authz_ = false;
  16430. }
  16431. private:
  16432. Server proxy_mock_;
  16433. Server target_;
  16434. std::thread proxy_thread_;
  16435. std::thread target_thread_;
  16436. int proxy_port_ = 0;
  16437. int target_port_ = 0;
  16438. std::atomic<int> proxy_hits_{0};
  16439. std::atomic<int> target_hits_{0};
  16440. std::atomic<bool> last_had_proxy_authz_{false};
  16441. };
  16442. inline std::unique_ptr<Client> make_client(const std::string &host,
  16443. ProxyAndTargetServers &s) {
  16444. auto cli = detail::make_unique<Client>(host, s.target_port());
  16445. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16446. cli->set_proxy("127.0.0.1", s.proxy_port());
  16447. return cli;
  16448. }
  16449. } // namespace no_proxy_test
  16450. using no_proxy_test::make_client;
  16451. using no_proxy_test::ProxyAndTargetServers;
  16452. TEST(NoProxyTest, ExactHostnameBypasses) {
  16453. ProxyAndTargetServers s;
  16454. auto cli = make_client("example.com", s);
  16455. cli->set_no_proxy({"example.com"});
  16456. auto res = cli->Get("/");
  16457. ASSERT_TRUE(res);
  16458. EXPECT_EQ(0, s.proxy_hits());
  16459. EXPECT_EQ(1, s.target_hits());
  16460. }
  16461. TEST(NoProxyTest, SubdomainBypasses) {
  16462. ProxyAndTargetServers s;
  16463. auto cli = make_client("foo.example.com", s);
  16464. cli->set_no_proxy({"example.com"});
  16465. auto res = cli->Get("/");
  16466. ASSERT_TRUE(res);
  16467. EXPECT_EQ(0, s.proxy_hits());
  16468. EXPECT_EQ(1, s.target_hits());
  16469. }
  16470. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16471. // Regression guard: "evilexample.com" must not be considered a subdomain
  16472. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16473. // check would let traffic bypass the proxy and leak credentials direct
  16474. // to the attacker host.
  16475. ProxyAndTargetServers s;
  16476. auto cli = make_client("evilexample.com", s);
  16477. cli->set_no_proxy({"example.com"});
  16478. auto res = cli->Get("/");
  16479. ASSERT_TRUE(res);
  16480. EXPECT_GE(s.proxy_hits(), 1);
  16481. EXPECT_EQ(0, s.target_hits());
  16482. }
  16483. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16484. ProxyAndTargetServers s;
  16485. auto cli = make_client("example.com.evil.com", s);
  16486. cli->set_no_proxy({"example.com"});
  16487. auto res = cli->Get("/");
  16488. ASSERT_TRUE(res);
  16489. EXPECT_GE(s.proxy_hits(), 1);
  16490. EXPECT_EQ(0, s.target_hits());
  16491. }
  16492. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16493. ProxyAndTargetServers s;
  16494. auto cli = make_client("example.com", s);
  16495. cli->set_no_proxy({".example.com"});
  16496. auto res = cli->Get("/");
  16497. ASSERT_TRUE(res);
  16498. EXPECT_EQ(0, s.proxy_hits());
  16499. EXPECT_EQ(1, s.target_hits());
  16500. }
  16501. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16502. ProxyAndTargetServers s;
  16503. auto cli = make_client("Example.COM", s);
  16504. cli->set_no_proxy({"EXAMPLE.com"});
  16505. auto res = cli->Get("/");
  16506. ASSERT_TRUE(res);
  16507. EXPECT_EQ(0, s.proxy_hits());
  16508. EXPECT_EQ(1, s.target_hits());
  16509. }
  16510. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16511. ProxyAndTargetServers s;
  16512. auto cli = make_client("example.com.", s);
  16513. cli->set_no_proxy({"example.com"});
  16514. auto res = cli->Get("/");
  16515. ASSERT_TRUE(res);
  16516. EXPECT_EQ(0, s.proxy_hits());
  16517. EXPECT_EQ(1, s.target_hits());
  16518. }
  16519. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16520. // Trailing dots must be normalized on BOTH sides — host and entry.
  16521. // An implementation that only strips the host-side trailing dot would
  16522. // fail to match host "example.com" against entry "example.com." because
  16523. // a literal substring search would compare 11 chars against 12.
  16524. ProxyAndTargetServers s;
  16525. auto cli = make_client("example.com", s);
  16526. cli->set_no_proxy({"example.com."});
  16527. auto res = cli->Get("/");
  16528. ASSERT_TRUE(res);
  16529. EXPECT_EQ(0, s.proxy_hits());
  16530. EXPECT_EQ(1, s.target_hits());
  16531. }
  16532. TEST(NoProxyTest, WildcardBypassesEverything) {
  16533. ProxyAndTargetServers s;
  16534. auto cli = make_client("anything.invalid.test", s);
  16535. cli->set_no_proxy({"*"});
  16536. auto res = cli->Get("/");
  16537. ASSERT_TRUE(res);
  16538. EXPECT_EQ(0, s.proxy_hits());
  16539. EXPECT_EQ(1, s.target_hits());
  16540. }
  16541. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16542. ProxyAndTargetServers s;
  16543. Client cli("127.0.0.1", s.target_port());
  16544. cli.set_proxy("127.0.0.1", s.proxy_port());
  16545. cli.set_no_proxy({"127.0.0.1"});
  16546. auto res = cli.Get("/");
  16547. ASSERT_TRUE(res);
  16548. EXPECT_EQ(0, s.proxy_hits());
  16549. EXPECT_EQ(1, s.target_hits());
  16550. }
  16551. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16552. ProxyAndTargetServers s;
  16553. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16554. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16555. cli.set_proxy("127.0.0.1", s.proxy_port());
  16556. cli.set_no_proxy({"::1"});
  16557. auto res = cli.Get("/");
  16558. ASSERT_TRUE(res);
  16559. EXPECT_EQ(0, s.proxy_hits());
  16560. EXPECT_EQ(1, s.target_hits());
  16561. }
  16562. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16563. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16564. // must still be recognized as IPv6 for CIDR matching. Implementations
  16565. // that detect IPv6 only when the host begins with '[' would parse the
  16566. // host as a hostname and miss the match.
  16567. ProxyAndTargetServers s;
  16568. Client cli("fe80::1", s.target_port());
  16569. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16570. cli.set_proxy("127.0.0.1", s.proxy_port());
  16571. cli.set_no_proxy({"fe80::/10"});
  16572. auto res = cli.Get("/");
  16573. ASSERT_TRUE(res);
  16574. EXPECT_EQ(0, s.proxy_hits());
  16575. EXPECT_EQ(1, s.target_hits());
  16576. }
  16577. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16578. ProxyAndTargetServers s;
  16579. Client cli("::1", s.target_port());
  16580. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16581. cli.set_proxy("127.0.0.1", s.proxy_port());
  16582. cli.set_no_proxy({"[::1]"});
  16583. auto res = cli.Get("/");
  16584. ASSERT_TRUE(res);
  16585. EXPECT_EQ(0, s.proxy_hits());
  16586. EXPECT_EQ(1, s.target_hits());
  16587. }
  16588. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16589. ProxyAndTargetServers s;
  16590. Client cli("fe80::1", s.target_port());
  16591. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16592. cli.set_proxy("127.0.0.1", s.proxy_port());
  16593. cli.set_no_proxy({"[fe80::]/10"});
  16594. auto res = cli.Get("/");
  16595. ASSERT_TRUE(res);
  16596. EXPECT_EQ(0, s.proxy_hits());
  16597. EXPECT_EQ(1, s.target_hits());
  16598. }
  16599. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16600. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16601. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16602. // tricks via address-family conversion.
  16603. ProxyAndTargetServers s;
  16604. Client cli("::ffff:127.0.0.1", s.target_port());
  16605. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16606. cli.set_proxy("127.0.0.1", s.proxy_port());
  16607. cli.set_no_proxy({"127.0.0.1"});
  16608. auto res = cli.Get("/");
  16609. ASSERT_TRUE(res);
  16610. EXPECT_GE(s.proxy_hits(), 1);
  16611. EXPECT_EQ(0, s.target_hits());
  16612. }
  16613. TEST(NoProxyTest, IPv4CidrMatch) {
  16614. ProxyAndTargetServers s;
  16615. Client cli("127.0.0.1", s.target_port());
  16616. cli.set_proxy("127.0.0.1", s.proxy_port());
  16617. cli.set_no_proxy({"127.0.0.0/8"});
  16618. auto res = cli.Get("/");
  16619. ASSERT_TRUE(res);
  16620. EXPECT_EQ(0, s.proxy_hits());
  16621. EXPECT_EQ(1, s.target_hits());
  16622. }
  16623. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16624. ProxyAndTargetServers s;
  16625. Client cli("127.0.0.1", s.target_port());
  16626. cli.set_proxy("127.0.0.1", s.proxy_port());
  16627. cli.set_no_proxy({"10.0.0.0/8"});
  16628. auto res = cli.Get("/");
  16629. ASSERT_TRUE(res);
  16630. EXPECT_GE(s.proxy_hits(), 1);
  16631. EXPECT_EQ(0, s.target_hits());
  16632. }
  16633. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16634. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16635. // IPv4 target matches.
  16636. ProxyAndTargetServers s;
  16637. Client cli("127.0.0.1", s.target_port());
  16638. cli.set_proxy("127.0.0.1", s.proxy_port());
  16639. cli.set_no_proxy({"0.0.0.0/0"});
  16640. auto res = cli.Get("/");
  16641. ASSERT_TRUE(res);
  16642. EXPECT_EQ(0, s.proxy_hits());
  16643. EXPECT_EQ(1, s.target_hits());
  16644. }
  16645. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16646. ProxyAndTargetServers s;
  16647. Client cli("127.0.0.1", s.target_port());
  16648. cli.set_proxy("127.0.0.1", s.proxy_port());
  16649. cli.set_no_proxy({"127.0.0.1"});
  16650. auto res = cli.Get("/");
  16651. ASSERT_TRUE(res);
  16652. EXPECT_EQ(0, s.proxy_hits());
  16653. EXPECT_EQ(1, s.target_hits());
  16654. }
  16655. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16656. ProxyAndTargetServers s;
  16657. Client cli("127.0.0.1", s.target_port());
  16658. cli.set_proxy("127.0.0.1", s.proxy_port());
  16659. cli.set_no_proxy({"127.0.0.0/33"});
  16660. auto res = cli.Get("/");
  16661. ASSERT_TRUE(res);
  16662. EXPECT_GE(s.proxy_hits(), 1);
  16663. EXPECT_EQ(0, s.target_hits());
  16664. }
  16665. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16666. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16667. ProxyAndTargetServers s;
  16668. Client cli("127.0.0.1", s.target_port());
  16669. cli.set_proxy("127.0.0.1", s.proxy_port());
  16670. cli.set_no_proxy({"127.0.0.1/"});
  16671. auto res = cli.Get("/");
  16672. ASSERT_TRUE(res);
  16673. EXPECT_GE(s.proxy_hits(), 1);
  16674. EXPECT_EQ(0, s.target_hits());
  16675. }
  16676. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16677. ProxyAndTargetServers s;
  16678. auto cli = make_client("internal.corp", s);
  16679. cli->set_proxy_basic_auth("u", "p");
  16680. cli->set_no_proxy({"internal.corp"});
  16681. auto res = cli->Get("/");
  16682. ASSERT_TRUE(res);
  16683. EXPECT_EQ(1, s.target_hits());
  16684. EXPECT_EQ(0, s.proxy_hits());
  16685. EXPECT_FALSE(s.last_had_proxy_authz())
  16686. << "Proxy-Authorization must not be sent direct to the target";
  16687. }
  16688. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16689. ProxyAndTargetServers s;
  16690. auto cli = make_client("public.example", s);
  16691. cli->set_proxy_basic_auth("u", "p");
  16692. cli->set_no_proxy({"internal.corp"}); // does not match
  16693. auto res = cli->Get("/");
  16694. ASSERT_TRUE(res);
  16695. EXPECT_GE(s.proxy_hits(), 1);
  16696. EXPECT_TRUE(s.last_had_proxy_authz());
  16697. }
  16698. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16699. ProxyAndTargetServers s;
  16700. auto cli = make_client("anything.test", s);
  16701. auto res = cli->Get("/");
  16702. ASSERT_TRUE(res);
  16703. EXPECT_GE(s.proxy_hits(), 1);
  16704. EXPECT_EQ(0, s.target_hits());
  16705. }
  16706. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16707. ProxyAndTargetServers s;
  16708. auto cli = make_client("example.com", s);
  16709. cli->set_no_proxy({"example.com:8080"});
  16710. auto res = cli->Get("/");
  16711. ASSERT_TRUE(res);
  16712. EXPECT_GE(s.proxy_hits(), 1);
  16713. EXPECT_EQ(0, s.target_hits());
  16714. }
  16715. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16716. ProxyAndTargetServers s;
  16717. auto cli = make_client("anything.test", s);
  16718. cli->set_no_proxy({"", " ", "\t"});
  16719. auto res = cli->Get("/");
  16720. ASSERT_TRUE(res);
  16721. EXPECT_GE(s.proxy_hits(), 1);
  16722. EXPECT_EQ(0, s.target_hits());
  16723. }
  16724. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16725. // An entry with leading/trailing whitespace must still match — env-style
  16726. // values are commonly pasted with stray spaces and an implementation
  16727. // that feeds the raw token directly to inet_pton would fail to match
  16728. // valid CIDRs because of the spaces.
  16729. ProxyAndTargetServers s;
  16730. Client cli("127.0.0.1", s.target_port());
  16731. cli.set_proxy("127.0.0.1", s.proxy_port());
  16732. cli.set_no_proxy({" 127.0.0.0/8 "});
  16733. auto res = cli.Get("/");
  16734. ASSERT_TRUE(res);
  16735. EXPECT_EQ(0, s.proxy_hits());
  16736. EXPECT_EQ(1, s.target_hits());
  16737. }
  16738. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16739. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16740. // go direct and must NOT carry Proxy-Authorization.
  16741. std::atomic<int> proxy_hits{0};
  16742. std::atomic<int> target_hits{0};
  16743. std::atomic<bool> target_saw_authz{false};
  16744. no_proxy_test::ScopedServer proxy_mock, target;
  16745. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16746. proxy_hits++;
  16747. res.status = 302;
  16748. res.set_header("Location", "http://127.0.0.1:" +
  16749. std::to_string(target.port()) + "/landed");
  16750. });
  16751. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16752. target_hits++;
  16753. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16754. res.set_content("direct", "text/plain");
  16755. });
  16756. proxy_mock.listen();
  16757. target.listen();
  16758. Client cli("public.example", target.port());
  16759. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16760. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16761. cli.set_proxy_basic_auth("u", "p");
  16762. cli.set_no_proxy({"127.0.0.1"});
  16763. cli.set_follow_location(true);
  16764. auto res = cli.Get("/redir");
  16765. ASSERT_TRUE(res);
  16766. EXPECT_GE(proxy_hits.load(), 1);
  16767. EXPECT_GE(target_hits.load(), 1);
  16768. EXPECT_FALSE(target_saw_authz.load());
  16769. }
  16770. #ifdef CPPHTTPLIB_SSL_ENABLED
  16771. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16772. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16773. // proxy creds would be sent to the (possibly hostile) origin.
  16774. std::atomic<int> target_hits{0};
  16775. std::atomic<bool> target_saw_proxy_authz{false};
  16776. no_proxy_test::ScopedServer target;
  16777. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16778. target_hits++;
  16779. if (req.has_header("Proxy-Authorization")) {
  16780. target_saw_proxy_authz = true;
  16781. }
  16782. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16783. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16784. "nonce=\"abc\", algorithm=MD5");
  16785. });
  16786. target.listen();
  16787. // The proxy address is set to the target's port: the bypass MUST kick in;
  16788. // if it doesn't, the test still routes "via proxy" to the same server and
  16789. // the Proxy-Authorization assertion below catches the leak.
  16790. Client cli("evil.example", target.port());
  16791. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16792. cli.set_proxy("127.0.0.1", target.port());
  16793. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16794. cli.set_no_proxy({"evil.example"});
  16795. auto res = cli.Get("/x");
  16796. ASSERT_TRUE(res);
  16797. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16798. EXPECT_EQ(1, target_hits.load());
  16799. EXPECT_FALSE(target_saw_proxy_authz.load());
  16800. }
  16801. #endif
  16802. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16803. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16804. std::atomic<int> proxy_hits{0};
  16805. std::atomic<int> bypass_hits{0};
  16806. std::atomic<bool> proxy_saw_c_url{false};
  16807. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16808. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16809. proxy_hits++;
  16810. if (req.path.find("/start") != std::string::npos) {
  16811. res.status = 302;
  16812. res.set_header("Location", "http://127.0.0.1:" +
  16813. std::to_string(bypass_server.port()) +
  16814. "/middle");
  16815. return;
  16816. }
  16817. if (req.path.find("/end") != std::string::npos) {
  16818. proxy_saw_c_url = true;
  16819. res.set_content("c-via-proxy", "text/plain");
  16820. return;
  16821. }
  16822. res.set_content("unexpected", "text/plain");
  16823. });
  16824. // public.example's "advertised" port is arbitrary (the request never lands
  16825. // there — it goes through the proxy), but use a dynamic value to stay
  16826. // friendly with sharded parallel runs.
  16827. int public_port = bypass_server.port();
  16828. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16829. bypass_hits++;
  16830. res.status = 302;
  16831. res.set_header("Location", "http://public.example:" +
  16832. std::to_string(public_port) + "/end");
  16833. });
  16834. proxy_mock.listen();
  16835. bypass_server.listen();
  16836. Client cli("public.example", public_port);
  16837. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16838. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16839. cli.set_no_proxy({"127.0.0.1"});
  16840. cli.set_follow_location(true);
  16841. auto res = cli.Get("/start");
  16842. ASSERT_TRUE(res);
  16843. EXPECT_EQ(StatusCode::OK_200, res->status);
  16844. EXPECT_EQ("c-via-proxy", res->body);
  16845. EXPECT_GE(proxy_hits.load(), 2);
  16846. EXPECT_GE(bypass_hits.load(), 1);
  16847. EXPECT_TRUE(proxy_saw_c_url.load());
  16848. }
  16849. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16850. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16851. // request reconnects to the correct endpoint.
  16852. std::atomic<int> proxy_hits{0};
  16853. std::atomic<int> target_hits{0};
  16854. no_proxy_test::ScopedServer proxy_mock, target;
  16855. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16856. proxy_hits++;
  16857. res.set_content("via-proxy", "text/plain");
  16858. });
  16859. target.svr().Get(".*", [&](const Request &, Response &res) {
  16860. target_hits++;
  16861. res.set_content("direct", "text/plain");
  16862. });
  16863. proxy_mock.listen();
  16864. target.listen();
  16865. Client cli("public.example", target.port());
  16866. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16867. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16868. cli.set_keep_alive(true);
  16869. auto res1 = cli.Get("/a");
  16870. ASSERT_TRUE(res1);
  16871. EXPECT_EQ("via-proxy", res1->body);
  16872. EXPECT_EQ(1, proxy_hits.load());
  16873. EXPECT_EQ(0, target_hits.load());
  16874. cli.set_no_proxy({"public.example"});
  16875. auto res2 = cli.Get("/b");
  16876. ASSERT_TRUE(res2);
  16877. EXPECT_EQ("direct", res2->body);
  16878. EXPECT_EQ(1, proxy_hits.load());
  16879. EXPECT_EQ(1, target_hits.load());
  16880. }
  16881. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16882. namespace proxy_tunnel_test {
  16883. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16884. class ScopedSSLServer {
  16885. public:
  16886. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16887. port_ = svr_.bind_to_any_port("127.0.0.1");
  16888. }
  16889. ~ScopedSSLServer() {
  16890. svr_.stop();
  16891. if (th_.joinable()) { th_.join(); }
  16892. }
  16893. SSLServer &svr() { return svr_; }
  16894. int port() const { return port_; }
  16895. void listen() {
  16896. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16897. svr_.wait_until_ready();
  16898. }
  16899. private:
  16900. SSLServer svr_;
  16901. std::thread th_;
  16902. int port_ = 0;
  16903. };
  16904. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16905. class ScopedConnectProxy {
  16906. public:
  16907. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16908. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16909. if (listen_fd_ < 0) { return; }
  16910. int yes = 1;
  16911. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16912. sockaddr_in a{};
  16913. a.sin_family = AF_INET;
  16914. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16915. a.sin_port = 0;
  16916. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16917. return;
  16918. }
  16919. socklen_t alen = sizeof(a);
  16920. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16921. 0) {
  16922. return;
  16923. }
  16924. port_ = ntohs(a.sin_port);
  16925. if (::listen(listen_fd_, 1) != 0) { return; }
  16926. th_ = std::thread([this] { run(); });
  16927. }
  16928. ~ScopedConnectProxy() {
  16929. stop_ = true;
  16930. if (listen_fd_ >= 0) {
  16931. ::shutdown(listen_fd_, SHUT_RDWR);
  16932. ::close(listen_fd_);
  16933. }
  16934. if (th_.joinable()) { th_.join(); }
  16935. }
  16936. int port() const { return port_; }
  16937. int connect_hits() const { return connect_hits_.load(); }
  16938. private:
  16939. void run() {
  16940. while (!stop_.load()) {
  16941. fd_set rfds;
  16942. FD_ZERO(&rfds);
  16943. FD_SET(listen_fd_, &rfds);
  16944. timeval tv{0, 100 * 1000};
  16945. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16946. if (sel <= 0) { continue; }
  16947. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16948. if (client_fd < 0) { continue; }
  16949. std::string req;
  16950. char buf[2048];
  16951. while (req.find("\r\n\r\n") == std::string::npos) {
  16952. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16953. if (n <= 0) { break; }
  16954. req.append(buf, static_cast<size_t>(n));
  16955. }
  16956. if (req.compare(0, 7, "CONNECT") != 0) {
  16957. ::close(client_fd);
  16958. continue;
  16959. }
  16960. connect_hits_++;
  16961. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16962. ::send(client_fd, ok, std::strlen(ok), 0);
  16963. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16964. sockaddr_in o{};
  16965. o.sin_family = AF_INET;
  16966. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16967. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16968. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16969. 0) {
  16970. ::close(client_fd);
  16971. ::close(origin_fd);
  16972. continue;
  16973. }
  16974. auto forward = [](int from, int to) {
  16975. char b[8192];
  16976. for (;;) {
  16977. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16978. if (n <= 0) { break; }
  16979. ssize_t off = 0;
  16980. while (off < n) {
  16981. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16982. if (s <= 0) {
  16983. off = n;
  16984. break;
  16985. }
  16986. off += s;
  16987. }
  16988. }
  16989. ::shutdown(to, SHUT_WR);
  16990. };
  16991. std::thread t1([&] { forward(client_fd, origin_fd); });
  16992. std::thread t2([&] { forward(origin_fd, client_fd); });
  16993. t1.join();
  16994. t2.join();
  16995. ::close(client_fd);
  16996. ::close(origin_fd);
  16997. }
  16998. }
  16999. int forward_port_ = -1;
  17000. int listen_fd_ = -1;
  17001. int port_ = 0;
  17002. std::thread th_;
  17003. std::atomic<bool> stop_{false};
  17004. std::atomic<int> connect_hits_{0};
  17005. };
  17006. } // namespace proxy_tunnel_test
  17007. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17008. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17009. // retry; otherwise proxy creds would be sent to the origin.
  17010. std::atomic<int> origin_hits{0};
  17011. std::atomic<bool> origin_saw_proxy_authz{false};
  17012. proxy_tunnel_test::ScopedSSLServer origin;
  17013. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17014. origin_hits++;
  17015. if (req.has_header("Proxy-Authorization")) {
  17016. origin_saw_proxy_authz = true;
  17017. }
  17018. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17019. res.set_header("Proxy-Authenticate",
  17020. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17021. "algorithm=MD5");
  17022. });
  17023. origin.listen();
  17024. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17025. ASSERT_NE(0, proxy.port());
  17026. SSLClient cli(HOST, origin.port());
  17027. cli.enable_server_certificate_verification(false);
  17028. cli.set_proxy(HOST, proxy.port());
  17029. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17030. auto res = cli.Get("/x");
  17031. ASSERT_TRUE(res);
  17032. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17033. EXPECT_EQ(1, origin_hits.load());
  17034. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17035. EXPECT_EQ(1, proxy.connect_hits());
  17036. }
  17037. #endif