test.cc 630 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413
  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, LoggerSeesContentLength) {
  6353. size_t logged_content_length = 0;
  6354. std::string logged_content_length_header;
  6355. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6356. logged_content_length = res.content_length_;
  6357. logged_content_length_header = res.get_header_value("Content-Length");
  6358. });
  6359. auto res = cli_.Get("/nocompress");
  6360. ASSERT_TRUE(res);
  6361. EXPECT_EQ(StatusCode::OK_200, res->status);
  6362. EXPECT_EQ(res->body.size(), logged_content_length);
  6363. EXPECT_EQ(std::to_string(logged_content_length),
  6364. logged_content_length_header);
  6365. }
  6366. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6367. const std::string test_content =
  6368. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6369. "3456789012345678901234567890";
  6370. std::string pre_compression_body;
  6371. bool pre_logger_called = false;
  6372. // Set only pre-compression logger
  6373. svr_.set_pre_compression_logger(
  6374. [&](const Request & /*req*/, const Response &res) {
  6375. pre_compression_body = res.body;
  6376. pre_logger_called = true;
  6377. });
  6378. Headers headers;
  6379. headers.emplace("Accept-Encoding", "gzip");
  6380. auto res = cli_.Get("/compress", headers);
  6381. ASSERT_TRUE(res);
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6384. // Verify pre-compression logger was called
  6385. EXPECT_TRUE(pre_logger_called);
  6386. EXPECT_EQ(test_content, pre_compression_body);
  6387. }
  6388. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6389. {
  6390. // Test with Expect: 100-continue header - success case
  6391. // Server returns 100 Continue, client sends body, server returns 200 OK
  6392. Request req;
  6393. req.method = "POST";
  6394. req.path = "/post-large";
  6395. req.set_header("Expect", "100-continue");
  6396. req.body = LARGE_DATA;
  6397. Response res;
  6398. auto error = Error::Success;
  6399. cli_.set_keep_alive(true);
  6400. auto ret = cli_.send(req, res, error);
  6401. EXPECT_TRUE(ret);
  6402. EXPECT_EQ(StatusCode::OK_200, res.status);
  6403. EXPECT_EQ(LARGE_DATA, res.body);
  6404. }
  6405. {
  6406. // Test with Expect: 100-continue header - error case
  6407. // Client should not send the body when server returns an error
  6408. Request req;
  6409. req.method = "POST";
  6410. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6411. req.set_header("Expect", "100-continue");
  6412. req.body = LARGE_DATA;
  6413. Response res;
  6414. auto error = Error::Success;
  6415. auto start = std::chrono::high_resolution_clock::now();
  6416. cli_.set_keep_alive(true);
  6417. auto ret = cli_.send(req, res, error);
  6418. auto end = std::chrono::high_resolution_clock::now();
  6419. auto elapsed =
  6420. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6421. .count();
  6422. // With Expect: 100-continue, request completes successfully but with error
  6423. EXPECT_TRUE(ret);
  6424. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6425. EXPECT_EQ("close", res.get_header_value("Connection"));
  6426. EXPECT_FALSE(cli_.is_socket_open());
  6427. EXPECT_LE(elapsed, 2000);
  6428. }
  6429. {
  6430. // Send an extra GET request to ensure error recovery without hanging
  6431. Request req;
  6432. req.method = "GET";
  6433. req.path = "/hi";
  6434. auto start = std::chrono::high_resolution_clock::now();
  6435. auto res = cli_.send(req);
  6436. auto end = std::chrono::high_resolution_clock::now();
  6437. auto elapsed =
  6438. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6439. .count();
  6440. ASSERT_TRUE(res);
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("Hello World!", res->body);
  6443. EXPECT_LE(elapsed, 500);
  6444. }
  6445. }
  6446. TEST(ZstdDecompressor, ChunkedDecompression) {
  6447. std::string data;
  6448. for (size_t i = 0; i < 32 * 1024; ++i) {
  6449. data.push_back(static_cast<char>('a' + i % 26));
  6450. }
  6451. std::string compressed_data;
  6452. {
  6453. httplib::detail::zstd_compressor compressor;
  6454. bool result = compressor.compress(
  6455. data.data(), data.size(),
  6456. /*last=*/true,
  6457. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6458. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6459. compressed_data_size);
  6460. return true;
  6461. });
  6462. ASSERT_TRUE(result);
  6463. }
  6464. std::string decompressed_data;
  6465. {
  6466. httplib::detail::zstd_decompressor decompressor;
  6467. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6468. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6469. size_t chunk_size = 130;
  6470. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6471. chunk_begin += chunk_size) {
  6472. size_t current_chunk_size =
  6473. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6474. bool result = decompressor.decompress(
  6475. compressed_data.data() + chunk_begin, current_chunk_size,
  6476. [&](const char *decompressed_data_chunk,
  6477. size_t decompressed_data_chunk_size) {
  6478. decompressed_data.insert(decompressed_data.size(),
  6479. decompressed_data_chunk,
  6480. decompressed_data_chunk_size);
  6481. return true;
  6482. });
  6483. ASSERT_TRUE(result);
  6484. }
  6485. }
  6486. ASSERT_EQ(data, decompressed_data);
  6487. }
  6488. TEST(ZstdDecompressor, Decompress) {
  6489. std::string original_text = "Compressed with ZSTD";
  6490. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6491. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6492. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6493. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6494. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6495. std::string decompressed_data;
  6496. {
  6497. httplib::detail::zstd_decompressor decompressor;
  6498. bool result = decompressor.decompress(
  6499. compressed_data.data(), compressed_data.size(),
  6500. [&](const char *decompressed_data_chunk,
  6501. size_t decompressed_data_chunk_size) {
  6502. decompressed_data.insert(decompressed_data.size(),
  6503. decompressed_data_chunk,
  6504. decompressed_data_chunk_size);
  6505. return true;
  6506. });
  6507. ASSERT_TRUE(result);
  6508. }
  6509. ASSERT_EQ(original_text, decompressed_data);
  6510. }
  6511. #endif
  6512. // Sends a raw request to a server listening at HOST:PORT.
  6513. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6514. std::string *resp = nullptr) {
  6515. auto error = Error::Success;
  6516. auto client_sock = detail::create_client_socket(
  6517. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6518. /*connection_timeout_sec=*/5, 0,
  6519. /*read_timeout_sec=*/5, 0,
  6520. /*write_timeout_sec=*/5, 0, std::string(), error);
  6521. if (client_sock == INVALID_SOCKET) { return false; }
  6522. auto ret = detail::process_client_socket(
  6523. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6524. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6525. if (req.size() !=
  6526. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6527. return false;
  6528. }
  6529. char buf[512];
  6530. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6531. while (line_reader.getline()) {
  6532. if (resp) { *resp += line_reader.ptr(); }
  6533. }
  6534. return true;
  6535. });
  6536. detail::close_socket(client_sock);
  6537. return ret;
  6538. }
  6539. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6540. Server svr;
  6541. std::string header_value;
  6542. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6543. header_value = req.get_header_value("foo");
  6544. res.set_content("ok", "text/plain");
  6545. });
  6546. thread t = thread([&] { svr.listen(HOST, PORT); });
  6547. auto se = detail::scope_exit([&] {
  6548. svr.stop();
  6549. t.join();
  6550. ASSERT_FALSE(svr.is_running());
  6551. });
  6552. svr.wait_until_ready();
  6553. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6554. // like characters are not treated the same - use vertical tab and escape.
  6555. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6556. "foo: \t \v bar \x1B\t \r\n"
  6557. "Connection: close\r\n"
  6558. "\r\n";
  6559. std::string res;
  6560. ASSERT_TRUE(send_request(5, req, &res));
  6561. EXPECT_EQ(header_value, "");
  6562. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6563. }
  6564. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6565. Server svr;
  6566. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6567. auto i = new int(0);
  6568. res.set_header("Trailer", "X-Safe, X-Reflected");
  6569. res.set_chunked_content_provider(
  6570. "text/plain",
  6571. [i](size_t /*offset*/, DataSink &sink) {
  6572. if (*i == 0) {
  6573. sink.os << "body";
  6574. } else {
  6575. Headers trailer;
  6576. // A valid trailer that must survive.
  6577. trailer.emplace("X-Safe", "safe");
  6578. // Attacker-controlled value carrying CR/LF (response splitting).
  6579. trailer.emplace("X-Reflected",
  6580. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6581. // Attacker-controlled name carrying CR/LF.
  6582. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6583. sink.done_with_trailer(trailer);
  6584. }
  6585. (*i)++;
  6586. return true;
  6587. },
  6588. [i](bool /*success*/) { delete i; });
  6589. });
  6590. thread t = thread([&] { svr.listen(HOST, PORT); });
  6591. auto se = detail::scope_exit([&] {
  6592. svr.stop();
  6593. t.join();
  6594. ASSERT_FALSE(svr.is_running());
  6595. });
  6596. svr.wait_until_ready();
  6597. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6598. "Host: " + HOST +
  6599. "\r\n"
  6600. "Connection: close\r\n"
  6601. "\r\n";
  6602. std::string res;
  6603. ASSERT_TRUE(send_request(5, req, &res));
  6604. // The injected fields must not appear anywhere in the raw response.
  6605. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6606. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6607. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6608. // Invalid trailers are dropped entirely, matching set_header().
  6609. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6610. // The valid trailer still passes through.
  6611. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6612. }
  6613. // Sends a raw request and verifies that there isn't a crash or exception.
  6614. static void test_raw_request(const std::string &req,
  6615. std::string *out = nullptr) {
  6616. Server svr;
  6617. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6618. res.set_content("ok", "text/plain");
  6619. });
  6620. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6621. res.set_content("ok", "text/plain");
  6622. });
  6623. svr.Get("/header_field_value_check",
  6624. [&](const Request & /*req*/, Response &res) {
  6625. res.set_content("ok", "text/plain");
  6626. });
  6627. // Server read timeout must be longer than the client read timeout for the
  6628. // bug to reproduce, probably to force the server to process a request
  6629. // without a trailing blank line.
  6630. const time_t client_read_timeout_sec = 1;
  6631. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6632. bool listen_thread_ok = false;
  6633. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6634. auto se = detail::scope_exit([&] {
  6635. svr.stop();
  6636. t.join();
  6637. ASSERT_FALSE(svr.is_running());
  6638. EXPECT_TRUE(listen_thread_ok);
  6639. });
  6640. svr.wait_until_ready();
  6641. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6642. }
  6643. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6644. // A certain header line causes an exception if the header property is parsed
  6645. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6646. test_raw_request(
  6647. "GET /hi HTTP/1.1\r\n"
  6648. " : "
  6649. " "
  6650. " ");
  6651. }
  6652. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6653. // A certain header line causes an exception if the header property *name* is
  6654. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6655. // greedy matcher and requires backtracking when there are a lot of ":"
  6656. // characters.
  6657. // This occurs with libc++ but not libstdc++.
  6658. test_raw_request(
  6659. "GET /hi HTTP/1.1\r\n"
  6660. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6661. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6662. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6663. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6664. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6665. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6666. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6667. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6668. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6669. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6670. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6671. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6672. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6673. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6674. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6675. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6676. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6677. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6678. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6679. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6680. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6681. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6682. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6683. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6684. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6685. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6686. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6687. "&&&%%%");
  6688. }
  6689. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6690. // Make sure this doesn't crash the server.
  6691. // In a previous version of the header line regex, the "\r" rendered the line
  6692. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6693. // a new position where the leading white space ended and the field value
  6694. // began.
  6695. // The crash occurs with libc++ but not libstdc++.
  6696. test_raw_request("GET /hi HTTP/1.1\r\n"
  6697. "a:" +
  6698. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6699. "\r\n"
  6700. "\r\n");
  6701. }
  6702. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6703. std::string out;
  6704. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6705. "Content-Type: text/plain\r\n"
  6706. "Transfer-Encoding: chunked\r\n"
  6707. "\r\n"
  6708. "nothex\r\n",
  6709. &out);
  6710. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6711. }
  6712. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6713. std::string out;
  6714. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6715. "Content-Type: text/plain\r\n"
  6716. "Transfer-Encoding: chunked\r\n"
  6717. "\r\n"
  6718. "3\r\n"
  6719. "xyz\r\n"
  6720. "NaN\r\n",
  6721. &out);
  6722. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6723. }
  6724. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6725. std::string out;
  6726. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6727. "Content-Type: text/plain\r\n"
  6728. "Transfer-Encoding: chunked\r\n"
  6729. "\r\n"
  6730. // Length is too large for 64 bits.
  6731. "1ffffffffffffffff\r\n"
  6732. "xyz\r\n",
  6733. &out);
  6734. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6735. }
  6736. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6737. test_raw_request("GET /hi HTTP/1.1\r\n"
  6738. "Content-Type: text/plain\r\n\r");
  6739. }
  6740. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6741. std::string out;
  6742. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6743. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6744. }
  6745. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6746. Server svr;
  6747. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6748. EXPECT_TRUE(!req.remote_addr.empty());
  6749. });
  6750. thread t = thread([&] { svr.listen(HOST, PORT); });
  6751. auto se = detail::scope_exit([&] {
  6752. svr.stop();
  6753. t.join();
  6754. ASSERT_FALSE(svr.is_running());
  6755. });
  6756. svr.wait_until_ready();
  6757. // Send an invalid request line to trigger Bad Request
  6758. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6759. std::string out;
  6760. ASSERT_TRUE(send_request(5, bad_req, &out));
  6761. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6762. }
  6763. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6764. std::string out;
  6765. std::string request(
  6766. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\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, InvalidFieldValueContains_LF) {
  6771. std::string out;
  6772. std::string request(
  6773. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6774. test_raw_request(request, &out);
  6775. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6776. }
  6777. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6778. std::string out;
  6779. std::string request(
  6780. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6781. test_raw_request(request, &out);
  6782. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6783. }
  6784. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6785. std::string out;
  6786. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6787. "Test: \r\n\r\n",
  6788. &out);
  6789. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6790. }
  6791. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6792. Server svr;
  6793. std::string x_custom;
  6794. std::string cookie;
  6795. std::string xff;
  6796. std::string x_unicode;
  6797. std::string x_iis;
  6798. svr.Get("/check", [&](const Request &req, Response &res) {
  6799. x_custom = req.get_header_value("X-Custom");
  6800. cookie = req.get_header_value("Cookie");
  6801. xff = req.get_header_value("X-Forwarded-For");
  6802. x_unicode = req.get_header_value("X-Unicode");
  6803. x_iis = req.get_header_value("X-IIS");
  6804. res.set_content("ok", "text/plain");
  6805. });
  6806. thread t = thread([&] { svr.listen(HOST, PORT); });
  6807. auto se = detail::scope_exit([&] {
  6808. svr.stop();
  6809. t.join();
  6810. ASSERT_FALSE(svr.is_running());
  6811. });
  6812. svr.wait_until_ready();
  6813. const std::string req = "GET /check HTTP/1.1\r\n"
  6814. "Host: localhost\r\n"
  6815. "X-Custom: a%0D%0AInjected: b\r\n"
  6816. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6817. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6818. "X-Unicode: %E3%81%82\r\n"
  6819. "X-IIS: %u00E9\r\n"
  6820. "Connection: close\r\n"
  6821. "\r\n";
  6822. std::string res;
  6823. ASSERT_TRUE(send_request(5, req, &res));
  6824. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6825. // Every value must be returned verbatim (wire form), with no decoding.
  6826. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6827. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6828. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6829. EXPECT_EQ("%E3%81%82", x_unicode);
  6830. EXPECT_EQ("%u00E9", x_iis);
  6831. }
  6832. // Applications that previously relied on automatic percent-decoding can
  6833. // reproduce the old behavior by explicitly calling decode_path_component()
  6834. // or, for RFC 3986 conformance, decode_uri_component().
  6835. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6836. Server svr;
  6837. std::string decoded;
  6838. svr.Get("/check", [&](const Request &req, Response &res) {
  6839. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6840. res.set_content("ok", "text/plain");
  6841. });
  6842. thread t = thread([&] { svr.listen(HOST, PORT); });
  6843. auto se = detail::scope_exit([&] {
  6844. svr.stop();
  6845. t.join();
  6846. ASSERT_FALSE(svr.is_running());
  6847. });
  6848. svr.wait_until_ready();
  6849. const std::string req = "GET /check HTTP/1.1\r\n"
  6850. "Host: localhost\r\n"
  6851. "X-Custom: hello%20world\r\n"
  6852. "Connection: close\r\n"
  6853. "\r\n";
  6854. std::string res;
  6855. ASSERT_TRUE(send_request(5, req, &res));
  6856. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6857. EXPECT_EQ("hello world", decoded);
  6858. }
  6859. // Regression test for #2033. Browsers send Referer values that include
  6860. // percent-encoded characters such as %0A inside the URL. Decoding the
  6861. // header value would either trip the post-decode CR/LF/NUL guard (the
  6862. // original bug, returning 400) or, after that guard was relaxed, silently
  6863. // store a literal LF — both unacceptable. The wire form must round-trip.
  6864. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6865. Server svr;
  6866. std::string referer;
  6867. svr.Get("/check", [&](const Request &req, Response &res) {
  6868. referer = req.get_header_value("Referer");
  6869. res.set_content("ok", "text/plain");
  6870. });
  6871. thread t = thread([&] { svr.listen(HOST, PORT); });
  6872. auto se = detail::scope_exit([&] {
  6873. svr.stop();
  6874. t.join();
  6875. ASSERT_FALSE(svr.is_running());
  6876. });
  6877. svr.wait_until_ready();
  6878. const std::string req = "GET /check HTTP/1.1\r\n"
  6879. "Host: localhost\r\n"
  6880. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6881. "Connection: close\r\n"
  6882. "\r\n";
  6883. std::string res;
  6884. ASSERT_TRUE(send_request(5, req, &res));
  6885. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6886. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6887. }
  6888. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6889. Server svr;
  6890. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6891. res.set_header("Cache-Control", "no-cache");
  6892. res.set_chunked_content_provider(
  6893. "text/event-stream", [](size_t offset, DataSink &sink) {
  6894. std::string s = "data:";
  6895. s += std::to_string(offset);
  6896. s += "\n\n";
  6897. auto ret = sink.write(s.data(), s.size());
  6898. EXPECT_TRUE(ret);
  6899. std::this_thread::sleep_for(std::chrono::seconds(1));
  6900. return true;
  6901. });
  6902. });
  6903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6904. svr.wait_until_ready();
  6905. Client client(HOST, PORT);
  6906. const Headers headers = {{"Accept", "text/event-stream"}};
  6907. auto get_thread = std::thread([&client, &headers]() {
  6908. auto res = client.Get(
  6909. "/events", headers,
  6910. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6911. });
  6912. auto se = detail::scope_exit([&] {
  6913. svr.stop();
  6914. get_thread.join();
  6915. listen_thread.join();
  6916. ASSERT_FALSE(svr.is_running());
  6917. });
  6918. // Give GET time to get a few messages.
  6919. std::this_thread::sleep_for(std::chrono::seconds(2));
  6920. }
  6921. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6922. httplib::Server svr;
  6923. svr.Post("/hi",
  6924. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6925. res.status = StatusCode::OK_200;
  6926. });
  6927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6928. svr.wait_until_ready();
  6929. Client cli(HOST, PORT);
  6930. auto res = cli.Post("/hi", "data", "text/plain");
  6931. ASSERT_TRUE(res);
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. svr.stop();
  6934. thread.join();
  6935. ASSERT_FALSE(svr.is_running());
  6936. res = cli.Post("/hi", "data", "text/plain");
  6937. ASSERT_FALSE(res);
  6938. }
  6939. TEST(ServerStopTest, ListenFailure) {
  6940. Server svr;
  6941. auto t = thread([&]() {
  6942. auto ret = svr.listen("????", PORT);
  6943. EXPECT_FALSE(ret);
  6944. });
  6945. svr.wait_until_ready();
  6946. svr.stop();
  6947. t.join();
  6948. }
  6949. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6950. TEST(ServerStopTest, Decommision) {
  6951. Server svr;
  6952. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6953. for (int i = 0; i < 4; i++) {
  6954. auto is_even = !(i % 2);
  6955. std::thread t{[&] {
  6956. try {
  6957. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6958. if (is_even) {
  6959. throw std::runtime_error("Some thing that happens to go wrong.");
  6960. }
  6961. svr.listen(HOST, PORT);
  6962. } catch (...) { svr.decommission(); }
  6963. }};
  6964. svr.wait_until_ready();
  6965. // Server is up
  6966. {
  6967. Client cli(HOST, PORT);
  6968. auto res = cli.Get("/hi");
  6969. if (is_even) {
  6970. EXPECT_FALSE(res);
  6971. } else {
  6972. EXPECT_TRUE(res);
  6973. EXPECT_EQ("hi...", res->body);
  6974. }
  6975. }
  6976. svr.stop();
  6977. t.join();
  6978. // Server is down...
  6979. {
  6980. Client cli(HOST, PORT);
  6981. auto res = cli.Get("/hi");
  6982. EXPECT_FALSE(res);
  6983. }
  6984. }
  6985. }
  6986. #endif
  6987. // Helper function for string body upload progress tests
  6988. template <typename SetupHandler, typename ClientCall>
  6989. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6990. ClientCall &&client_call,
  6991. const string &body) {
  6992. Server svr;
  6993. setup_handler(svr);
  6994. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6995. auto se = detail::scope_exit([&] {
  6996. svr.stop();
  6997. t.join();
  6998. });
  6999. svr.wait_until_ready();
  7000. Client cli(HOST, PORT);
  7001. vector<uint64_t> progress_values;
  7002. bool progress_called = false;
  7003. auto res =
  7004. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7005. progress_values.push_back(current);
  7006. progress_called = true;
  7007. return true;
  7008. });
  7009. ASSERT_TRUE(res);
  7010. EXPECT_EQ(200, res->status);
  7011. EXPECT_TRUE(progress_called);
  7012. }
  7013. TEST(UploadProgressTest, PostStringBodyBasic) {
  7014. TestStringBodyUploadProgress(
  7015. [](Server &svr) {
  7016. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7017. res.set_content("received", "text/plain");
  7018. });
  7019. },
  7020. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7021. return cli.Post("/test", body, "text/plain", progress_callback);
  7022. },
  7023. "test data for upload progress");
  7024. }
  7025. TEST(UploadProgressTest, PutStringBodyBasic) {
  7026. TestStringBodyUploadProgress(
  7027. [](Server &svr) {
  7028. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7029. res.set_content("put received", "text/plain");
  7030. });
  7031. },
  7032. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7033. return cli.Put("/test", body, "text/plain", progress_callback);
  7034. },
  7035. "put test data for upload progress");
  7036. }
  7037. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7038. TestStringBodyUploadProgress(
  7039. [](Server &svr) {
  7040. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7041. res.set_content("patch received", "text/plain");
  7042. });
  7043. },
  7044. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7045. return cli.Patch("/test", body, "text/plain", progress_callback);
  7046. },
  7047. "patch test data for upload progress");
  7048. }
  7049. // Helper function for content provider upload progress tests
  7050. template <typename SetupHandler, typename ClientCall>
  7051. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7052. ClientCall &&client_call) {
  7053. Server svr;
  7054. setup_handler(svr);
  7055. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7056. auto se = detail::scope_exit([&] {
  7057. svr.stop();
  7058. t.join();
  7059. });
  7060. svr.wait_until_ready();
  7061. Client cli(HOST, PORT);
  7062. vector<uint64_t> progress_values;
  7063. auto res =
  7064. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7065. progress_values.push_back(current);
  7066. return true;
  7067. });
  7068. ASSERT_TRUE(res);
  7069. EXPECT_EQ(200, res->status);
  7070. EXPECT_FALSE(progress_values.empty());
  7071. }
  7072. TEST(UploadProgressTest, PostContentProviderProgress) {
  7073. TestContentProviderUploadProgress(
  7074. [](Server &svr) {
  7075. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7076. res.set_content("provider received", "text/plain");
  7077. });
  7078. },
  7079. [](Client &cli, UploadProgress progress_callback) {
  7080. return cli.Post(
  7081. "/test", 10,
  7082. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7083. sink.os << "test data";
  7084. return true;
  7085. },
  7086. "text/plain", progress_callback);
  7087. });
  7088. }
  7089. // Helper function for multipart upload progress tests
  7090. template <typename SetupHandler, typename ClientCall>
  7091. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7092. ClientCall &&client_call,
  7093. const string &endpoint) {
  7094. Server svr;
  7095. setup_handler(svr);
  7096. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7097. auto se = detail::scope_exit([&] {
  7098. svr.stop();
  7099. t.join();
  7100. });
  7101. svr.wait_until_ready();
  7102. Client cli(HOST, PORT);
  7103. vector<uint64_t> progress_values;
  7104. UploadFormDataItems items = {
  7105. {"field1", "value1", "", ""},
  7106. {"field2", "longer value for progress tracking test", "", ""},
  7107. {"file1", "file content data for upload progress", "test.txt",
  7108. "text/plain"}};
  7109. auto res = client_call(cli, endpoint, items,
  7110. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7111. progress_values.push_back(current);
  7112. return true;
  7113. });
  7114. ASSERT_TRUE(res);
  7115. EXPECT_EQ(200, res->status);
  7116. EXPECT_FALSE(progress_values.empty());
  7117. }
  7118. TEST(UploadProgressTest, PostMultipartProgress) {
  7119. TestMultipartUploadProgress(
  7120. [](Server &svr) {
  7121. svr.Post("/multipart", [](const Request &req, Response &res) {
  7122. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7123. res.set_content("multipart received", "text/plain");
  7124. });
  7125. },
  7126. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7127. UploadProgress progress_callback) {
  7128. return cli.Post(endpoint, items, progress_callback);
  7129. },
  7130. "/multipart");
  7131. }
  7132. // Helper function for basic download progress tests
  7133. template <typename SetupHandler, typename ClientCall>
  7134. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7135. ClientCall &&client_call, const string &endpoint,
  7136. size_t expected_content_size) {
  7137. Server svr;
  7138. setup_handler(svr);
  7139. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7140. auto se = detail::scope_exit([&] {
  7141. svr.stop();
  7142. t.join();
  7143. });
  7144. svr.wait_until_ready();
  7145. Client cli(HOST, PORT);
  7146. vector<uint64_t> progress_values;
  7147. auto res = client_call(cli, endpoint,
  7148. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7149. progress_values.push_back(current);
  7150. return true;
  7151. });
  7152. ASSERT_TRUE(res);
  7153. EXPECT_EQ(200, res->status);
  7154. EXPECT_FALSE(progress_values.empty());
  7155. EXPECT_EQ(expected_content_size, res->body.size());
  7156. }
  7157. TEST(DownloadProgressTest, GetBasic) {
  7158. TestBasicDownloadProgress(
  7159. [](Server &svr) {
  7160. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7161. string content(1000, 'D');
  7162. res.set_content(content, "text/plain");
  7163. });
  7164. },
  7165. [](Client &cli, const string &endpoint,
  7166. DownloadProgress progress_callback) {
  7167. return cli.Get(endpoint, progress_callback);
  7168. },
  7169. "/download", 1000u);
  7170. }
  7171. // Helper function for content receiver download progress tests
  7172. template <typename SetupHandler, typename ClientCall>
  7173. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7174. ClientCall &&client_call,
  7175. const string &endpoint,
  7176. size_t expected_content_size) {
  7177. Server svr;
  7178. setup_handler(svr);
  7179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7180. auto se = detail::scope_exit([&] {
  7181. svr.stop();
  7182. t.join();
  7183. });
  7184. svr.wait_until_ready();
  7185. Client cli(HOST, PORT);
  7186. vector<uint64_t> progress_values;
  7187. string received_body;
  7188. auto res = client_call(
  7189. cli, endpoint,
  7190. [&](const char *data, size_t data_length) -> bool {
  7191. received_body.append(data, data_length);
  7192. return true;
  7193. },
  7194. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7195. progress_values.push_back(current);
  7196. return true;
  7197. });
  7198. ASSERT_TRUE(res);
  7199. EXPECT_EQ(200, res->status);
  7200. EXPECT_FALSE(progress_values.empty());
  7201. EXPECT_EQ(expected_content_size, received_body.size());
  7202. EXPECT_TRUE(res->body.empty());
  7203. }
  7204. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7205. TestContentReceiverDownloadProgress(
  7206. [](Server &svr) {
  7207. svr.Get("/download-receiver",
  7208. [](const Request & /*req*/, Response &res) {
  7209. string content(2000, 'R');
  7210. res.set_content(content, "text/plain");
  7211. });
  7212. },
  7213. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7214. DownloadProgress progress_callback) {
  7215. return cli.Get(endpoint, content_receiver, progress_callback);
  7216. },
  7217. "/download-receiver", 2000u);
  7218. }
  7219. TEST(StreamingTest, NoContentLengthStreaming) {
  7220. Server svr;
  7221. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7222. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7223. if (offset < 6) {
  7224. sink.os << (offset < 3 ? "a" : "b");
  7225. } else {
  7226. sink.done();
  7227. }
  7228. return true;
  7229. });
  7230. });
  7231. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7232. auto listen_se = detail::scope_exit([&] {
  7233. svr.stop();
  7234. listen_thread.join();
  7235. ASSERT_FALSE(svr.is_running());
  7236. });
  7237. svr.wait_until_ready();
  7238. Client client(HOST, PORT);
  7239. auto get_thread = std::thread([&client]() {
  7240. std::string s;
  7241. auto res =
  7242. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7243. s += std::string(data, len);
  7244. return true;
  7245. });
  7246. ASSERT_TRUE(res);
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. EXPECT_EQ("aaabbb", s);
  7249. });
  7250. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7251. // Give GET time to get a few messages.
  7252. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7253. }
  7254. TEST(MountTest, Unmount) {
  7255. Server svr;
  7256. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7257. auto se = detail::scope_exit([&] {
  7258. svr.stop();
  7259. listen_thread.join();
  7260. ASSERT_FALSE(svr.is_running());
  7261. });
  7262. svr.wait_until_ready();
  7263. Client cli("localhost", PORT);
  7264. svr.set_mount_point("/mount2", "./www2");
  7265. auto res = cli.Get("/");
  7266. ASSERT_TRUE(res);
  7267. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7268. res = cli.Get("/mount2/dir/test.html");
  7269. ASSERT_TRUE(res);
  7270. EXPECT_EQ(StatusCode::OK_200, res->status);
  7271. svr.set_mount_point("/", "./www");
  7272. res = cli.Get("/dir/");
  7273. ASSERT_TRUE(res);
  7274. EXPECT_EQ(StatusCode::OK_200, res->status);
  7275. svr.remove_mount_point("/");
  7276. res = cli.Get("/dir/");
  7277. ASSERT_TRUE(res);
  7278. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7279. svr.remove_mount_point("/mount2");
  7280. res = cli.Get("/mount2/dir/test.html");
  7281. ASSERT_TRUE(res);
  7282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7283. }
  7284. TEST(MountTest, Redicect) {
  7285. Server svr;
  7286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7287. auto se = detail::scope_exit([&] {
  7288. svr.stop();
  7289. listen_thread.join();
  7290. ASSERT_FALSE(svr.is_running());
  7291. });
  7292. svr.set_mount_point("/", "./www");
  7293. svr.wait_until_ready();
  7294. Client cli("localhost", PORT);
  7295. auto res = cli.Get("/dir/");
  7296. ASSERT_TRUE(res);
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. res = cli.Get("/dir");
  7299. ASSERT_TRUE(res);
  7300. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7301. res = cli.Get("/file");
  7302. ASSERT_TRUE(res);
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. res = cli.Get("/file/");
  7305. ASSERT_TRUE(res);
  7306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7307. cli.set_follow_location(true);
  7308. res = cli.Get("/dir");
  7309. ASSERT_TRUE(res);
  7310. EXPECT_EQ(StatusCode::OK_200, res->status);
  7311. }
  7312. TEST(MountTest, MultibytesPathName) {
  7313. Server svr;
  7314. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7315. auto se = detail::scope_exit([&] {
  7316. svr.stop();
  7317. listen_thread.join();
  7318. ASSERT_FALSE(svr.is_running());
  7319. });
  7320. svr.set_mount_point("/", "./www");
  7321. svr.wait_until_ready();
  7322. Client cli("localhost", PORT);
  7323. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7324. ASSERT_TRUE(res);
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7327. }
  7328. #ifdef _WIN32
  7329. // Issue #2435: mmap::open() must succeed even when another handle holds
  7330. // the file open for writing (e.g. an active log file).
  7331. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7332. const char *path = "mmap_concurrent_writer_test.txt";
  7333. const char *content = "hello";
  7334. {
  7335. std::ofstream f(path, std::ios::binary);
  7336. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7337. }
  7338. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7339. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7340. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7341. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7342. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7343. detail::mmap m(path);
  7344. ASSERT_TRUE(m.is_open());
  7345. EXPECT_EQ(strlen(content), m.size());
  7346. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7347. }
  7348. #endif
  7349. TEST(KeepAliveTest, ReadTimeout) {
  7350. Server svr;
  7351. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7352. std::this_thread::sleep_for(std::chrono::seconds(2));
  7353. res.set_content("a", "text/plain");
  7354. });
  7355. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7356. res.set_content("b", "text/plain");
  7357. });
  7358. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7359. auto se = detail::scope_exit([&] {
  7360. svr.stop();
  7361. listen_thread.join();
  7362. ASSERT_FALSE(svr.is_running());
  7363. });
  7364. svr.wait_until_ready();
  7365. Client cli("localhost", PORT);
  7366. cli.set_keep_alive(true);
  7367. cli.set_read_timeout(std::chrono::seconds(1));
  7368. auto resa = cli.Get("/a");
  7369. ASSERT_FALSE(resa);
  7370. EXPECT_EQ(Error::Read, resa.error());
  7371. auto resb = cli.Get("/b");
  7372. ASSERT_TRUE(resb);
  7373. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7374. EXPECT_EQ("b", resb->body);
  7375. }
  7376. TEST(KeepAliveTest, MaxCount) {
  7377. size_t keep_alive_max_count = 3;
  7378. Server svr;
  7379. svr.set_keep_alive_max_count(keep_alive_max_count);
  7380. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7381. res.set_content("Hello World!", "text/plain");
  7382. });
  7383. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7384. auto se = detail::scope_exit([&] {
  7385. svr.stop();
  7386. listen_thread.join();
  7387. ASSERT_FALSE(svr.is_running());
  7388. });
  7389. svr.wait_until_ready();
  7390. Client cli(HOST, PORT);
  7391. cli.set_keep_alive(true);
  7392. for (size_t i = 0; i < 5; i++) {
  7393. auto result = cli.Get("/hi");
  7394. ASSERT_TRUE(result);
  7395. EXPECT_EQ(StatusCode::OK_200, result->status);
  7396. if (i == keep_alive_max_count - 1) {
  7397. EXPECT_EQ("close", result->get_header_value("Connection"));
  7398. } else {
  7399. EXPECT_FALSE(result->has_header("Connection"));
  7400. }
  7401. }
  7402. }
  7403. TEST(KeepAliveTest, Issue1041) {
  7404. Server svr;
  7405. svr.set_keep_alive_timeout(3);
  7406. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7407. res.set_content("Hello World!", "text/plain");
  7408. });
  7409. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7410. auto se = detail::scope_exit([&] {
  7411. svr.stop();
  7412. listen_thread.join();
  7413. ASSERT_FALSE(svr.is_running());
  7414. });
  7415. svr.wait_until_ready();
  7416. Client cli(HOST, PORT);
  7417. cli.set_keep_alive(true);
  7418. auto result = cli.Get("/hi");
  7419. ASSERT_TRUE(result);
  7420. EXPECT_EQ(StatusCode::OK_200, result->status);
  7421. std::this_thread::sleep_for(std::chrono::seconds(5));
  7422. result = cli.Get("/hi");
  7423. ASSERT_TRUE(result);
  7424. EXPECT_EQ(StatusCode::OK_200, result->status);
  7425. }
  7426. TEST(KeepAliveTest, Issue1959) {
  7427. Server svr;
  7428. svr.set_keep_alive_timeout(5);
  7429. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7430. res.set_content("a", "text/plain");
  7431. });
  7432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7433. auto se = detail::scope_exit([&] {
  7434. if (!svr.is_running()) return;
  7435. svr.stop();
  7436. listen_thread.join();
  7437. ASSERT_FALSE(svr.is_running());
  7438. });
  7439. svr.wait_until_ready();
  7440. Client cli("localhost", PORT);
  7441. cli.set_keep_alive(true);
  7442. using namespace std::chrono;
  7443. auto start = steady_clock::now();
  7444. cli.Get("/a");
  7445. svr.stop();
  7446. listen_thread.join();
  7447. auto end = steady_clock::now();
  7448. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7449. EXPECT_LT(elapsed, 5000);
  7450. }
  7451. #ifdef CPPHTTPLIB_SSL_ENABLED
  7452. TEST(KeepAliveTest, SSLClientReconnection) {
  7453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7454. ASSERT_TRUE(svr.is_valid());
  7455. svr.set_keep_alive_timeout(1);
  7456. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7457. res.set_content("Hello World!", "text/plain");
  7458. });
  7459. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7460. auto se = detail::scope_exit([&] {
  7461. svr.stop();
  7462. listen_thread.join();
  7463. ASSERT_FALSE(svr.is_running());
  7464. });
  7465. svr.wait_until_ready();
  7466. SSLClient cli(HOST, PORT);
  7467. cli.enable_server_certificate_verification(false);
  7468. cli.set_keep_alive(true);
  7469. auto result = cli.Get("/hi");
  7470. ASSERT_TRUE(result);
  7471. EXPECT_EQ(StatusCode::OK_200, result->status);
  7472. result = cli.Get("/hi");
  7473. ASSERT_TRUE(result);
  7474. EXPECT_EQ(StatusCode::OK_200, result->status);
  7475. std::this_thread::sleep_for(std::chrono::seconds(2));
  7476. // Recoonect
  7477. result = cli.Get("/hi");
  7478. ASSERT_TRUE(result);
  7479. EXPECT_EQ(StatusCode::OK_200, result->status);
  7480. result = cli.Get("/hi");
  7481. ASSERT_TRUE(result);
  7482. EXPECT_EQ(StatusCode::OK_200, result->status);
  7483. }
  7484. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7486. ASSERT_TRUE(svr.is_valid());
  7487. svr.set_keep_alive_timeout(1);
  7488. std::string content = "reconnect";
  7489. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7490. res.set_content("Hello World!", "text/plain");
  7491. });
  7492. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7493. auto se = detail::scope_exit([&] {
  7494. svr.stop();
  7495. listen_thread.join();
  7496. ASSERT_FALSE(svr.is_running());
  7497. });
  7498. svr.wait_until_ready();
  7499. SSLClient cli(HOST, PORT);
  7500. cli.enable_server_certificate_verification(false);
  7501. cli.set_keep_alive(true);
  7502. auto result = cli.Post(
  7503. "/hi", content.size(),
  7504. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7505. sink.write(content.c_str(), content.size());
  7506. return true;
  7507. },
  7508. "text/plain");
  7509. ASSERT_TRUE(result);
  7510. EXPECT_EQ(200, result->status);
  7511. std::this_thread::sleep_for(std::chrono::seconds(2));
  7512. // Recoonect
  7513. result = cli.Post(
  7514. "/hi", content.size(),
  7515. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7516. sink.write(content.c_str(), content.size());
  7517. return true;
  7518. },
  7519. "text/plain");
  7520. ASSERT_TRUE(result);
  7521. EXPECT_EQ(200, result->status);
  7522. result = cli.Post(
  7523. "/hi", content.size(),
  7524. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7525. sink.write(content.c_str(), content.size());
  7526. return true;
  7527. },
  7528. "text/plain");
  7529. ASSERT_TRUE(result);
  7530. EXPECT_EQ(200, result->status);
  7531. }
  7532. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7533. using namespace httplib::tls;
  7534. {
  7535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7536. ASSERT_TRUE(svr.is_valid());
  7537. svr.Get("/sni", [&](const Request &req, Response &res) {
  7538. std::string expected = req.sni();
  7539. EXPECT_EQ(expected, req.get_param_value("expected"));
  7540. res.set_content("ok", "text/plain");
  7541. });
  7542. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7543. auto se = detail::scope_exit([&] {
  7544. svr.stop();
  7545. listen_thread.join();
  7546. ASSERT_FALSE(svr.is_running());
  7547. });
  7548. svr.wait_until_ready();
  7549. {
  7550. SSLClient cli("localhost", PORT);
  7551. cli.enable_server_certificate_verification(false);
  7552. auto res = cli.Get("/sni?expected=localhost");
  7553. ASSERT_TRUE(res);
  7554. }
  7555. {
  7556. SSLClient cli("::1", PORT);
  7557. cli.enable_server_certificate_verification(false);
  7558. auto res = cli.Get("/sni?expected=");
  7559. // NOTE: This may fail if the server is listening on IPv4 only
  7560. // (e.g., when localhost resolves to 127.0.0.1 only)
  7561. if (res) {
  7562. EXPECT_EQ(StatusCode::OK_200, res->status);
  7563. } else {
  7564. EXPECT_EQ(Error::Connection, res.error());
  7565. }
  7566. }
  7567. }
  7568. }
  7569. #endif
  7570. TEST(ClientProblemDetectionTest, ContentProvider) {
  7571. Server svr;
  7572. size_t content_length = 1024 * 1024;
  7573. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7574. res.set_content_provider(
  7575. content_length, "text/plain",
  7576. [&](size_t offset, size_t length, DataSink &sink) {
  7577. auto out_len = std::min(length, static_cast<size_t>(1024));
  7578. std::string out(out_len, '@');
  7579. sink.write(out.data(), out_len);
  7580. return offset < 4096;
  7581. },
  7582. [](bool success) { ASSERT_FALSE(success); });
  7583. });
  7584. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7585. res.set_content_provider(
  7586. 0, "text/plain",
  7587. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7588. EXPECT_TRUE(false);
  7589. return true;
  7590. },
  7591. [](bool success) { ASSERT_FALSE(success); });
  7592. });
  7593. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7594. auto se = detail::scope_exit([&] {
  7595. svr.stop();
  7596. listen_thread.join();
  7597. ASSERT_FALSE(svr.is_running());
  7598. });
  7599. svr.wait_until_ready();
  7600. Client cli("localhost", PORT);
  7601. {
  7602. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7603. size_t /*data_length*/) { return false; });
  7604. ASSERT_FALSE(res);
  7605. }
  7606. {
  7607. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7608. size_t /*data_length*/) { return false; });
  7609. ASSERT_TRUE(res);
  7610. }
  7611. }
  7612. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7613. Server svr;
  7614. svr.set_error_handler([](Request const &, Response &res) -> void {
  7615. res.set_chunked_content_provider(
  7616. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7617. sink.os << "hello";
  7618. sink.os << "world";
  7619. sink.done();
  7620. return true;
  7621. });
  7622. });
  7623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7624. auto se = detail::scope_exit([&] {
  7625. svr.stop();
  7626. listen_thread.join();
  7627. ASSERT_FALSE(svr.is_running());
  7628. });
  7629. svr.wait_until_ready();
  7630. Client cli("localhost", PORT);
  7631. auto res = cli.Get("/");
  7632. ASSERT_TRUE(res);
  7633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7634. EXPECT_EQ("helloworld", res->body);
  7635. }
  7636. TEST(LongPollingTest, ClientCloseDetection) {
  7637. Server svr;
  7638. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7639. res.set_chunked_content_provider(
  7640. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7641. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7642. sink.os << "hello";
  7643. auto count = 10;
  7644. while (count > 0 && sink.is_writable()) {
  7645. this_thread::sleep_for(chrono::milliseconds(10));
  7646. count--;
  7647. }
  7648. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7649. return true;
  7650. });
  7651. });
  7652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7653. auto se = detail::scope_exit([&] {
  7654. svr.stop();
  7655. listen_thread.join();
  7656. ASSERT_FALSE(svr.is_running());
  7657. });
  7658. svr.wait_until_ready();
  7659. Client cli("localhost", PORT);
  7660. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7661. EXPECT_EQ("hello", string(data, data_length));
  7662. return false; // close the socket immediately.
  7663. });
  7664. ASSERT_FALSE(res);
  7665. }
  7666. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7667. Server svr;
  7668. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7669. res.set_chunked_content_provider(
  7670. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7671. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7672. sink.os << "hello";
  7673. EXPECT_TRUE(sink.os.good());
  7674. // Wait for the client to close the connection
  7675. auto count = 10;
  7676. while (count > 0 && sink.is_writable()) {
  7677. this_thread::sleep_for(chrono::milliseconds(10));
  7678. count--;
  7679. }
  7680. // After client disconnect, write repeatedly until the socket
  7681. // write actually fails (small writes may be absorbed by the
  7682. // kernel buffer)
  7683. std::string chunk(1024, 'x');
  7684. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7685. sink.os << chunk;
  7686. }
  7687. EXPECT_TRUE(sink.os.fail());
  7688. return true;
  7689. });
  7690. });
  7691. auto port = svr.bind_to_any_port("localhost");
  7692. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7693. auto se = detail::scope_exit([&] {
  7694. svr.stop();
  7695. listen_thread.join();
  7696. ASSERT_FALSE(svr.is_running());
  7697. });
  7698. svr.wait_until_ready();
  7699. Client cli("localhost", port);
  7700. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7701. EXPECT_EQ("hello", string(data, data_length));
  7702. return false; // close the socket immediately.
  7703. });
  7704. ASSERT_FALSE(res);
  7705. }
  7706. TEST(GetWithParametersTest, GetWithParameters) {
  7707. Server svr;
  7708. svr.Get("/", [&](const Request &req, Response &) {
  7709. EXPECT_EQ("world", req.get_param_value("hello"));
  7710. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7711. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7712. });
  7713. svr.Get("/params", [&](const Request &req, Response &) {
  7714. EXPECT_EQ("world", req.get_param_value("hello"));
  7715. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7716. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7717. });
  7718. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7719. EXPECT_EQ("resource-id", req.matches[1]);
  7720. EXPECT_EQ("foo", req.get_param_value("param1"));
  7721. EXPECT_EQ("bar", req.get_param_value("param2"));
  7722. });
  7723. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7724. EXPECT_EQ("user-id", req.path_params.at("id"));
  7725. EXPECT_EQ("foo", req.get_param_value("param1"));
  7726. EXPECT_EQ("bar", req.get_param_value("param2"));
  7727. });
  7728. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7729. auto se = detail::scope_exit([&] {
  7730. svr.stop();
  7731. listen_thread.join();
  7732. ASSERT_FALSE(svr.is_running());
  7733. });
  7734. svr.wait_until_ready();
  7735. {
  7736. Client cli(HOST, PORT);
  7737. Params params;
  7738. params.emplace("hello", "world");
  7739. params.emplace("hello2", "world2");
  7740. params.emplace("hello3", "world3");
  7741. auto res = cli.Get("/", params, Headers{});
  7742. ASSERT_TRUE(res);
  7743. EXPECT_EQ(StatusCode::OK_200, res->status);
  7744. }
  7745. {
  7746. Client cli(HOST, PORT);
  7747. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7748. ASSERT_TRUE(res);
  7749. EXPECT_EQ(StatusCode::OK_200, res->status);
  7750. }
  7751. {
  7752. Client cli(HOST, PORT);
  7753. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7754. ASSERT_TRUE(res);
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. }
  7757. {
  7758. Client cli(HOST, PORT);
  7759. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7760. ASSERT_TRUE(res);
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. }
  7763. }
  7764. TEST(GetWithParametersTest, GetWithParameters2) {
  7765. Server svr;
  7766. svr.Get("/", [&](const Request &req, Response &res) {
  7767. auto text = req.get_param_value("hello");
  7768. res.set_content(text, "text/plain");
  7769. });
  7770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7771. auto se = detail::scope_exit([&] {
  7772. svr.stop();
  7773. listen_thread.join();
  7774. ASSERT_FALSE(svr.is_running());
  7775. });
  7776. svr.wait_until_ready();
  7777. Client cli("localhost", PORT);
  7778. Params params;
  7779. params.emplace("hello", "world");
  7780. std::string body;
  7781. auto res = cli.Get("/", params, Headers{},
  7782. [&](const char *data, size_t data_length) {
  7783. body.append(data, data_length);
  7784. return true;
  7785. });
  7786. ASSERT_TRUE(res);
  7787. EXPECT_EQ(StatusCode::OK_200, res->status);
  7788. EXPECT_EQ("world", body);
  7789. }
  7790. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7791. Server svr;
  7792. svr.Get("/search", [&](const Request &req, Response &res) {
  7793. auto q = req.get_param_value("q");
  7794. res.set_content(q, "text/plain");
  7795. });
  7796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7797. auto se = detail::scope_exit([&] {
  7798. svr.stop();
  7799. listen_thread.join();
  7800. ASSERT_FALSE(svr.is_running());
  7801. });
  7802. svr.wait_until_ready();
  7803. Client cli("localhost", PORT);
  7804. // Verify that Get(path, params) works without requiring Headers argument
  7805. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7806. ASSERT_TRUE(res);
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_EQ("cpp-httplib", res->body);
  7809. }
  7810. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7811. auto host = "httpbingo.org";
  7812. auto path = std::string{"/range/32"};
  7813. #ifdef CPPHTTPLIB_SSL_ENABLED
  7814. SSLClient cli(host);
  7815. #else
  7816. Client cli(host);
  7817. #endif
  7818. cli.set_default_headers({make_range_header({{1, 10}})});
  7819. cli.set_connection_timeout(5);
  7820. {
  7821. auto res = cli.Get(path);
  7822. ASSERT_TRUE(res);
  7823. EXPECT_EQ("bcdefghijk", res->body);
  7824. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7825. }
  7826. {
  7827. auto res = cli.Get(path);
  7828. ASSERT_TRUE(res);
  7829. EXPECT_EQ("bcdefghijk", res->body);
  7830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7831. }
  7832. }
  7833. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7834. Server svr;
  7835. svr.set_default_headers({{"Hello", "World"}});
  7836. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7837. res.set_content("ok", "text/plain");
  7838. });
  7839. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7840. auto se = detail::scope_exit([&] {
  7841. svr.stop();
  7842. listen_thread.join();
  7843. ASSERT_FALSE(svr.is_running());
  7844. });
  7845. svr.wait_until_ready();
  7846. Client cli("localhost", PORT);
  7847. auto res = cli.Get("/");
  7848. ASSERT_TRUE(res);
  7849. EXPECT_EQ(StatusCode::OK_200, res->status);
  7850. EXPECT_EQ("ok", res->body);
  7851. EXPECT_EQ("World", res->get_header_value("Hello"));
  7852. }
  7853. #ifdef CPPHTTPLIB_SSL_ENABLED
  7854. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7856. ASSERT_TRUE(svr.is_valid());
  7857. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7858. std::this_thread::sleep_for(std::chrono::seconds(2));
  7859. res.set_content("a", "text/plain");
  7860. });
  7861. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7862. res.set_content("b", "text/plain");
  7863. });
  7864. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7865. auto se = detail::scope_exit([&] {
  7866. svr.stop();
  7867. listen_thread.join();
  7868. ASSERT_FALSE(svr.is_running());
  7869. });
  7870. svr.wait_until_ready();
  7871. SSLClient cli("localhost", PORT);
  7872. cli.enable_server_certificate_verification(false);
  7873. cli.set_keep_alive(true);
  7874. cli.set_read_timeout(std::chrono::seconds(1));
  7875. auto resa = cli.Get("/a");
  7876. ASSERT_TRUE(!resa);
  7877. EXPECT_EQ(Error::Read, resa.error());
  7878. auto resb = cli.Get("/b");
  7879. ASSERT_TRUE(resb);
  7880. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7881. EXPECT_EQ("b", resb->body);
  7882. }
  7883. #endif
  7884. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7885. protected:
  7886. ServerTestWithAI_PASSIVE()
  7887. : cli_(HOST, PORT)
  7888. #ifdef CPPHTTPLIB_SSL_ENABLED
  7889. ,
  7890. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7891. #endif
  7892. {
  7893. #ifdef CPPHTTPLIB_SSL_ENABLED
  7894. cli_.enable_server_certificate_verification(false);
  7895. #endif
  7896. }
  7897. virtual void SetUp() {
  7898. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7899. res.set_content("Hello World!", "text/plain");
  7900. });
  7901. t_ = thread(
  7902. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7903. svr_.wait_until_ready();
  7904. }
  7905. virtual void TearDown() {
  7906. svr_.stop();
  7907. t_.join();
  7908. }
  7909. #ifdef CPPHTTPLIB_SSL_ENABLED
  7910. SSLClient cli_;
  7911. SSLServer svr_;
  7912. #else
  7913. Client cli_;
  7914. Server svr_;
  7915. #endif
  7916. thread t_;
  7917. };
  7918. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7919. auto res = cli_.Get("/hi");
  7920. ASSERT_TRUE(res);
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7923. EXPECT_EQ("Hello World!", res->body);
  7924. }
  7925. class ServerUpDownTest : public ::testing::Test {
  7926. protected:
  7927. ServerUpDownTest() : cli_(HOST, PORT) {}
  7928. virtual void SetUp() {
  7929. t_ = thread([&]() {
  7930. svr_.bind_to_any_port(HOST);
  7931. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7932. ASSERT_TRUE(svr_.listen_after_bind());
  7933. });
  7934. svr_.wait_until_ready();
  7935. }
  7936. virtual void TearDown() {
  7937. svr_.stop();
  7938. t_.join();
  7939. }
  7940. Client cli_;
  7941. Server svr_;
  7942. thread t_;
  7943. };
  7944. TEST_F(ServerUpDownTest, QuickStartStop) {
  7945. // Should not crash, especially when run with
  7946. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7947. }
  7948. class PayloadMaxLengthTest : public ::testing::Test {
  7949. protected:
  7950. PayloadMaxLengthTest()
  7951. : cli_(HOST, PORT)
  7952. #ifdef CPPHTTPLIB_SSL_ENABLED
  7953. ,
  7954. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7955. #endif
  7956. {
  7957. #ifdef CPPHTTPLIB_SSL_ENABLED
  7958. cli_.enable_server_certificate_verification(false);
  7959. #endif
  7960. }
  7961. virtual void SetUp() {
  7962. svr_.set_payload_max_length(8);
  7963. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7964. res.set_content("test", "text/plain");
  7965. });
  7966. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7967. svr_.wait_until_ready();
  7968. }
  7969. virtual void TearDown() {
  7970. svr_.stop();
  7971. t_.join();
  7972. }
  7973. #ifdef CPPHTTPLIB_SSL_ENABLED
  7974. SSLClient cli_;
  7975. SSLServer svr_;
  7976. #else
  7977. Client cli_;
  7978. Server svr_;
  7979. #endif
  7980. thread t_;
  7981. };
  7982. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7983. auto res = cli_.Post("/test", "123456789", "text/plain");
  7984. ASSERT_TRUE(res);
  7985. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7986. res = cli_.Post("/test", "12345678", "text/plain");
  7987. ASSERT_TRUE(res);
  7988. EXPECT_EQ(StatusCode::OK_200, res->status);
  7989. }
  7990. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7991. // Test chunked encoding with payload exceeding the 8-byte limit
  7992. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7993. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7994. ASSERT_TRUE(res);
  7995. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7996. }
  7997. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7998. // Test chunked encoding with payload within the 8-byte limit
  7999. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8000. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8001. ASSERT_TRUE(res);
  8002. EXPECT_EQ(StatusCode::OK_200, res->status);
  8003. }
  8004. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8005. // Test using send_request to send chunked data exceeding payload limit
  8006. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8007. "Host: " +
  8008. std::string(HOST) + ":" + std::to_string(PORT) +
  8009. "\r\n"
  8010. "Transfer-Encoding: chunked\r\n"
  8011. "Connection: close\r\n"
  8012. "\r\n"
  8013. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8014. "0123456789\r\n"
  8015. "0\r\n" // End chunk
  8016. "\r\n";
  8017. std::string response;
  8018. bool result = send_request(1, chunked_request, &response);
  8019. if (!result) {
  8020. // If send_request fails, it might be because the server closed the
  8021. // connection due to payload limit enforcement, which is acceptable
  8022. SUCCEED()
  8023. << "Server rejected oversized chunked request (connection closed)";
  8024. } else {
  8025. // If we got a response, check if it's an error response or connection was
  8026. // closed early Short response length indicates connection was closed due to
  8027. // payload limit
  8028. if (response.length() <= 10) {
  8029. SUCCEED() << "Server closed connection for oversized chunked request";
  8030. } else {
  8031. // Check for error status codes
  8032. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8033. response.find("Payload Too Large") != std::string::npos ||
  8034. response.find("400") != std::string::npos);
  8035. }
  8036. }
  8037. }
  8038. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8039. // Test request without Content-Length header exceeding payload limit
  8040. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8041. "Host: " +
  8042. std::string(HOST) + ":" +
  8043. std::to_string(PORT) +
  8044. "\r\n"
  8045. "Connection: close\r\n"
  8046. "\r\n";
  8047. // Add payload exceeding the 8-byte limit
  8048. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8049. request_without_content_length += large_payload;
  8050. std::string response;
  8051. bool result = send_request(1, request_without_content_length, &response);
  8052. if (!result) {
  8053. // If send_request fails, server likely closed connection due to payload
  8054. // limit
  8055. SUCCEED() << "Server rejected oversized request without Content-Length "
  8056. "(connection closed)";
  8057. } else {
  8058. // Check if server responded with error or closed connection early
  8059. if (response.length() <= 10) {
  8060. SUCCEED() << "Server closed connection for oversized request without "
  8061. "Content-Length";
  8062. } else {
  8063. // Check for error status codes
  8064. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8065. response.find("Payload Too Large") != std::string::npos ||
  8066. response.find("400") != std::string::npos);
  8067. }
  8068. }
  8069. }
  8070. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8071. // Test request without Content-Length header within payload limit
  8072. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8073. "Host: " +
  8074. std::string(HOST) + ":" +
  8075. std::to_string(PORT) +
  8076. "\r\n"
  8077. "Connection: close\r\n"
  8078. "\r\n";
  8079. // Add payload within the 8-byte limit
  8080. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8081. request_without_content_length += small_payload;
  8082. std::string response;
  8083. bool result = send_request(1, request_without_content_length, &response);
  8084. // For requests without Content-Length, the server may have different behavior
  8085. // The key is that it should not reject due to payload limit for small
  8086. // payloads
  8087. if (result) {
  8088. // Check for any HTTP response (success or error, but not connection closed)
  8089. if (response.length() > 10) {
  8090. SUCCEED()
  8091. << "Server processed request without Content-Length within limit";
  8092. } else {
  8093. // Short response might indicate connection closed, which is acceptable
  8094. SUCCEED() << "Server closed connection for request without "
  8095. "Content-Length (acceptable behavior)";
  8096. }
  8097. } else {
  8098. // Connection failure might be due to protocol requirements
  8099. SUCCEED() << "Connection issue with request without Content-Length "
  8100. "(environment-specific)";
  8101. }
  8102. }
  8103. class LargePayloadMaxLengthTest : public ::testing::Test {
  8104. protected:
  8105. LargePayloadMaxLengthTest()
  8106. : cli_(HOST, PORT)
  8107. #ifdef CPPHTTPLIB_SSL_ENABLED
  8108. ,
  8109. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8110. #endif
  8111. {
  8112. #ifdef CPPHTTPLIB_SSL_ENABLED
  8113. cli_.enable_server_certificate_verification(false);
  8114. #endif
  8115. }
  8116. virtual void SetUp() {
  8117. // Set 10MB payload limit
  8118. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8119. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8120. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8121. res.set_content("Large payload test", "text/plain");
  8122. });
  8123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8124. svr_.wait_until_ready();
  8125. }
  8126. virtual void TearDown() {
  8127. svr_.stop();
  8128. t_.join();
  8129. }
  8130. #ifdef CPPHTTPLIB_SSL_ENABLED
  8131. SSLClient cli_;
  8132. SSLServer svr_;
  8133. #else
  8134. Client cli_;
  8135. Server svr_;
  8136. #endif
  8137. thread t_;
  8138. };
  8139. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8140. // Test chunked encoding with payload within 10MB limit
  8141. std::string medium_payload(5 * 1024 * 1024,
  8142. 'A'); // 5MB payload, within 10MB limit
  8143. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8144. ASSERT_TRUE(res);
  8145. EXPECT_EQ(StatusCode::OK_200, res->status);
  8146. }
  8147. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8148. // Test chunked encoding with payload exceeding 10MB limit
  8149. std::string large_payload(12 * 1024 * 1024,
  8150. 'B'); // 12MB payload, exceeds 10MB limit
  8151. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8152. // Server may either return 413 or close the connection
  8153. if (res) {
  8154. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8155. } else {
  8156. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8157. }
  8158. }
  8159. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8160. // Test request without Content-Length header within 10MB limit
  8161. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8162. "Host: " +
  8163. std::string(HOST) + ":" +
  8164. std::to_string(PORT) +
  8165. "\r\n"
  8166. "Connection: close\r\n"
  8167. "\r\n";
  8168. // Add 1MB payload (within 10MB limit)
  8169. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8170. request_without_content_length += medium_payload;
  8171. std::string response;
  8172. bool result = send_request(5, request_without_content_length, &response);
  8173. if (result) {
  8174. // Should get a proper HTTP response for payloads within limit
  8175. if (response.length() > 10) {
  8176. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8177. "10MB limit";
  8178. } else {
  8179. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8180. "Content-Length)";
  8181. }
  8182. } else {
  8183. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8184. }
  8185. }
  8186. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8187. // Test request without Content-Length header exceeding 10MB limit
  8188. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8189. "Host: " +
  8190. std::string(HOST) + ":" +
  8191. std::to_string(PORT) +
  8192. "\r\n"
  8193. "Connection: close\r\n"
  8194. "\r\n";
  8195. // Add 12MB payload (exceeds 10MB limit)
  8196. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8197. request_without_content_length += large_payload;
  8198. std::string response;
  8199. bool result = send_request(10, request_without_content_length, &response);
  8200. if (!result) {
  8201. // Server should close connection due to payload limit
  8202. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8203. "(connection closed)";
  8204. } else {
  8205. // Check for error response
  8206. if (response.length() <= 10) {
  8207. SUCCEED()
  8208. << "Server closed connection for 12MB request exceeding 10MB limit";
  8209. } else {
  8210. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8211. response.find("Payload Too Large") != std::string::npos ||
  8212. response.find("400") != std::string::npos);
  8213. }
  8214. }
  8215. }
  8216. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8217. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8218. // path.
  8219. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8220. Server svr;
  8221. const size_t LIMIT = 64 * 1024; // 64KB
  8222. svr.set_payload_max_length(LIMIT);
  8223. size_t total = 0;
  8224. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8225. const ContentReader &content_reader) {
  8226. content_reader([&](const char * /*data*/, size_t len) {
  8227. total += len;
  8228. return true;
  8229. });
  8230. res.status = 200;
  8231. res.set_content("stream_ok", "text/plain");
  8232. });
  8233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8234. auto se = detail::scope_exit([&] {
  8235. svr.stop();
  8236. thread.join();
  8237. ASSERT_FALSE(svr.is_running());
  8238. });
  8239. svr.wait_until_ready();
  8240. // Prepare 256KB raw data and gzip-compress it
  8241. std::string raw(256 * 1024, 'A');
  8242. std::string gz;
  8243. {
  8244. z_stream zs{};
  8245. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8246. Z_DEFAULT_STRATEGY);
  8247. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8248. zs.avail_in = static_cast<uInt>(raw.size());
  8249. char outbuf[4096];
  8250. int ret;
  8251. do {
  8252. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8253. zs.avail_out = sizeof(outbuf);
  8254. ret = deflate(&zs, Z_FINISH);
  8255. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8256. } while (ret != Z_STREAM_END);
  8257. deflateEnd(&zs);
  8258. }
  8259. Client cli(HOST, PORT);
  8260. cli.set_connection_timeout(std::chrono::seconds(5));
  8261. Headers headers = {{"Content-Encoding", "gzip"}};
  8262. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8263. "application/octet-stream");
  8264. ASSERT_TRUE(res);
  8265. // Server must reject oversized decompressed payloads with 413.
  8266. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8267. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8268. EXPECT_LE(total, LIMIT);
  8269. }
  8270. #endif
  8271. // Regression test for DoS vulnerability: a malicious server sending a response
  8272. // without Content-Length header must not cause unbounded memory consumption on
  8273. // the client side. The client should stop reading after a reasonable limit,
  8274. // similar to the server-side set_payload_max_length protection.
  8275. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8276. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8277. #ifndef _WIN32
  8278. signal(SIGPIPE, SIG_IGN);
  8279. #endif
  8280. auto server_thread = std::thread([] {
  8281. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8282. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8283. default_socket_options(srv);
  8284. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8285. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8286. sockaddr_in addr{};
  8287. addr.sin_family = AF_INET;
  8288. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8289. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8290. int opt = 1;
  8291. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8292. #ifdef _WIN32
  8293. reinterpret_cast<const char *>(&opt),
  8294. #else
  8295. &opt,
  8296. #endif
  8297. sizeof(opt));
  8298. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8299. ::listen(srv, 1);
  8300. sockaddr_in cli_addr{};
  8301. socklen_t cli_len = sizeof(cli_addr);
  8302. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8303. if (cli != INVALID_SOCKET) {
  8304. char buf[4096];
  8305. ::recv(cli, buf, sizeof(buf), 0);
  8306. // Malicious response: no Content-Length, no chunked encoding
  8307. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8308. "Connection: close\r\n"
  8309. "\r\n";
  8310. ::send(cli,
  8311. #ifdef _WIN32
  8312. static_cast<const char *>(response_header.c_str()),
  8313. static_cast<int>(response_header.size()),
  8314. #else
  8315. response_header.c_str(), response_header.size(),
  8316. #endif
  8317. 0);
  8318. // Send 10MB of data
  8319. std::string chunk(64 * 1024, 'A');
  8320. size_t total_sent = 0;
  8321. while (total_sent < MALICIOUS_DATA_SIZE) {
  8322. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8323. auto sent = ::send(cli,
  8324. #ifdef _WIN32
  8325. static_cast<const char *>(chunk.c_str()),
  8326. static_cast<int>(to_send),
  8327. #else
  8328. chunk.c_str(), to_send,
  8329. #endif
  8330. 0);
  8331. if (sent <= 0) break;
  8332. total_sent += static_cast<size_t>(sent);
  8333. }
  8334. detail::close_socket(cli);
  8335. }
  8336. detail::close_socket(srv);
  8337. });
  8338. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8339. size_t total_read = 0;
  8340. {
  8341. Client cli("127.0.0.1", PORT + 2);
  8342. cli.set_read_timeout(5, 0);
  8343. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8344. auto stream = cli.open_stream("GET", "/malicious");
  8345. ASSERT_TRUE(stream.is_valid());
  8346. char buffer[64 * 1024];
  8347. ssize_t n;
  8348. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8349. total_read += static_cast<size_t>(n);
  8350. }
  8351. } // StreamHandle and Client destroyed here, closing the socket
  8352. server_thread.join();
  8353. // With set_payload_max_length, the client must stop reading before consuming
  8354. // all 10MB. The read loop should be cut off at or near the configured limit.
  8355. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8356. << "Client read " << total_read << " bytes, exceeding the configured "
  8357. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8358. }
  8359. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8360. // the entire response body without truncation.
  8361. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8362. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8363. #ifndef _WIN32
  8364. signal(SIGPIPE, SIG_IGN);
  8365. #endif
  8366. auto server_thread = std::thread([] {
  8367. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8368. default_socket_options(srv);
  8369. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8370. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8371. sockaddr_in addr{};
  8372. addr.sin_family = AF_INET;
  8373. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8374. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8375. int opt = 1;
  8376. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8377. #ifdef _WIN32
  8378. reinterpret_cast<const char *>(&opt),
  8379. #else
  8380. &opt,
  8381. #endif
  8382. sizeof(opt));
  8383. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8384. ::listen(srv, 1);
  8385. sockaddr_in cli_addr{};
  8386. socklen_t cli_len = sizeof(cli_addr);
  8387. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8388. if (cli != INVALID_SOCKET) {
  8389. char buf[4096];
  8390. ::recv(cli, buf, sizeof(buf), 0);
  8391. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8392. "Connection: close\r\n"
  8393. "\r\n";
  8394. ::send(cli,
  8395. #ifdef _WIN32
  8396. static_cast<const char *>(response_header.c_str()),
  8397. static_cast<int>(response_header.size()),
  8398. #else
  8399. response_header.c_str(), response_header.size(),
  8400. #endif
  8401. 0);
  8402. std::string chunk(64 * 1024, 'A');
  8403. size_t total_sent = 0;
  8404. while (total_sent < DATA_SIZE) {
  8405. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8406. auto sent = ::send(cli,
  8407. #ifdef _WIN32
  8408. static_cast<const char *>(chunk.c_str()),
  8409. static_cast<int>(to_send),
  8410. #else
  8411. chunk.c_str(), to_send,
  8412. #endif
  8413. 0);
  8414. if (sent <= 0) break;
  8415. total_sent += static_cast<size_t>(sent);
  8416. }
  8417. #ifdef _WIN32
  8418. ::shutdown(cli, SD_SEND);
  8419. #else
  8420. ::shutdown(cli, SHUT_WR);
  8421. #endif
  8422. // Drain until the client closes its end, ensuring all data is delivered
  8423. char drain[1024];
  8424. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8425. detail::close_socket(cli);
  8426. }
  8427. detail::close_socket(srv);
  8428. });
  8429. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8430. size_t total_read = 0;
  8431. {
  8432. Client cli("127.0.0.1", PORT + 2);
  8433. cli.set_read_timeout(5, 0);
  8434. cli.set_payload_max_length(0); // 0 means no limit
  8435. auto stream = cli.open_stream("GET", "/data");
  8436. ASSERT_TRUE(stream.is_valid());
  8437. char buffer[64 * 1024];
  8438. ssize_t n;
  8439. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8440. total_read += static_cast<size_t>(n);
  8441. }
  8442. }
  8443. server_thread.join();
  8444. EXPECT_EQ(total_read, DATA_SIZE)
  8445. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8446. << " bytes without truncation, but only read " << total_read << " bytes.";
  8447. }
  8448. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8449. // enormous Content-Length must not cause the client to pre-allocate a huge
  8450. // response body buffer. The reservation is capped at payload_max_length_, and
  8451. // the read itself fails when the body exceeds the limit.
  8452. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8453. #ifndef _WIN32
  8454. signal(SIGPIPE, SIG_IGN);
  8455. #endif
  8456. auto server_thread = std::thread([] {
  8457. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8458. default_socket_options(srv);
  8459. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8460. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8461. sockaddr_in addr{};
  8462. addr.sin_family = AF_INET;
  8463. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8464. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8465. int opt = 1;
  8466. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8467. #ifdef _WIN32
  8468. reinterpret_cast<const char *>(&opt),
  8469. #else
  8470. &opt,
  8471. #endif
  8472. sizeof(opt));
  8473. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8474. ::listen(srv, 1);
  8475. sockaddr_in cli_addr{};
  8476. socklen_t cli_len = sizeof(cli_addr);
  8477. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8478. if (cli != INVALID_SOCKET) {
  8479. char buf[4096];
  8480. ::recv(cli, buf, sizeof(buf), 0);
  8481. // Malicious response: claim a 20GB body but send only a tiny payload.
  8482. std::string response = "HTTP/1.1 200 OK\r\n"
  8483. "Content-Length: 20000000000\r\n"
  8484. "\r\n"
  8485. "abc";
  8486. ::send(cli,
  8487. #ifdef _WIN32
  8488. static_cast<const char *>(response.c_str()),
  8489. static_cast<int>(response.size()),
  8490. #else
  8491. response.c_str(), response.size(),
  8492. #endif
  8493. 0);
  8494. detail::close_socket(cli);
  8495. }
  8496. detail::close_socket(srv);
  8497. });
  8498. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8499. {
  8500. Client cli("127.0.0.1", PORT + 2);
  8501. cli.set_read_timeout(5, 0);
  8502. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8503. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8504. // (server claims more bytes than payload_max_length permits), but it must
  8505. // not exhaust memory before getting there.
  8506. auto res = cli.Get("/malicious");
  8507. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8508. }
  8509. server_thread.join();
  8510. }
  8511. // Verify that content_receiver bypasses the default payload_max_length,
  8512. // allowing streaming downloads larger than 100MB without requiring an explicit
  8513. // set_payload_max_length call.
  8514. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8515. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8516. #ifndef _WIN32
  8517. signal(SIGPIPE, SIG_IGN);
  8518. #endif
  8519. auto server_thread = std::thread([] {
  8520. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8521. default_socket_options(srv);
  8522. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8523. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8524. sockaddr_in addr{};
  8525. addr.sin_family = AF_INET;
  8526. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8528. int opt = 1;
  8529. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8530. #ifdef _WIN32
  8531. reinterpret_cast<const char *>(&opt),
  8532. #else
  8533. &opt,
  8534. #endif
  8535. sizeof(opt));
  8536. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8537. ::listen(srv, 1);
  8538. sockaddr_in cli_addr{};
  8539. socklen_t cli_len = sizeof(cli_addr);
  8540. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8541. if (cli != INVALID_SOCKET) {
  8542. char buf[4096];
  8543. ::recv(cli, buf, sizeof(buf), 0);
  8544. // Response with Content-Length larger than default 100MB limit
  8545. auto content_length = std::to_string(DATA_SIZE);
  8546. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8547. "Content-Length: " +
  8548. content_length +
  8549. "\r\n"
  8550. "Connection: close\r\n"
  8551. "\r\n";
  8552. ::send(cli,
  8553. #ifdef _WIN32
  8554. static_cast<const char *>(response_header.c_str()),
  8555. static_cast<int>(response_header.size()),
  8556. #else
  8557. response_header.c_str(), response_header.size(),
  8558. #endif
  8559. 0);
  8560. std::string chunk(64 * 1024, 'A');
  8561. size_t total_sent = 0;
  8562. while (total_sent < DATA_SIZE) {
  8563. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8564. auto sent = ::send(cli,
  8565. #ifdef _WIN32
  8566. static_cast<const char *>(chunk.c_str()),
  8567. static_cast<int>(to_send),
  8568. #else
  8569. chunk.c_str(), to_send,
  8570. #endif
  8571. 0);
  8572. if (sent <= 0) break;
  8573. total_sent += static_cast<size_t>(sent);
  8574. }
  8575. detail::close_socket(cli);
  8576. }
  8577. detail::close_socket(srv);
  8578. });
  8579. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8580. size_t total_received = 0;
  8581. {
  8582. Client cli("127.0.0.1", PORT + 2);
  8583. cli.set_read_timeout(10, 0);
  8584. // Do NOT call set_payload_max_length — use the default 100MB limit
  8585. auto res =
  8586. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8587. total_received += data_length;
  8588. return true;
  8589. });
  8590. ASSERT_TRUE(res);
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. }
  8593. server_thread.join();
  8594. EXPECT_EQ(total_received, DATA_SIZE)
  8595. << "With content_receiver, the client should read all " << DATA_SIZE
  8596. << " bytes despite the default 100MB payload_max_length, but only read "
  8597. << total_received << " bytes.";
  8598. }
  8599. // Verify that an explicit set_payload_max_length smaller than the response is
  8600. // enforced even when a content_receiver is used.
  8601. TEST(ClientVulnerabilityTest,
  8602. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8603. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8604. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8605. #ifndef _WIN32
  8606. signal(SIGPIPE, SIG_IGN);
  8607. #endif
  8608. auto server_thread = std::thread([] {
  8609. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8610. default_socket_options(srv);
  8611. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8612. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8613. sockaddr_in addr{};
  8614. addr.sin_family = AF_INET;
  8615. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8616. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8617. int opt = 1;
  8618. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8619. #ifdef _WIN32
  8620. reinterpret_cast<const char *>(&opt),
  8621. #else
  8622. &opt,
  8623. #endif
  8624. sizeof(opt));
  8625. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8626. ::listen(srv, 1);
  8627. sockaddr_in cli_addr{};
  8628. socklen_t cli_len = sizeof(cli_addr);
  8629. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8630. if (cli != INVALID_SOCKET) {
  8631. char buf[4096];
  8632. ::recv(cli, buf, sizeof(buf), 0);
  8633. auto content_length = std::to_string(DATA_SIZE);
  8634. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8635. "Content-Length: " +
  8636. content_length +
  8637. "\r\n"
  8638. "Connection: close\r\n"
  8639. "\r\n";
  8640. ::send(cli,
  8641. #ifdef _WIN32
  8642. static_cast<const char *>(response_header.c_str()),
  8643. static_cast<int>(response_header.size()),
  8644. #else
  8645. response_header.c_str(), response_header.size(),
  8646. #endif
  8647. 0);
  8648. std::string chunk(64 * 1024, 'A');
  8649. size_t total_sent = 0;
  8650. while (total_sent < DATA_SIZE) {
  8651. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8652. auto sent = ::send(cli,
  8653. #ifdef _WIN32
  8654. static_cast<const char *>(chunk.c_str()),
  8655. static_cast<int>(to_send),
  8656. #else
  8657. chunk.c_str(), to_send,
  8658. #endif
  8659. 0);
  8660. if (sent <= 0) break;
  8661. total_sent += static_cast<size_t>(sent);
  8662. }
  8663. detail::close_socket(cli);
  8664. }
  8665. detail::close_socket(srv);
  8666. });
  8667. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8668. size_t total_received = 0;
  8669. {
  8670. Client cli("127.0.0.1", PORT + 2);
  8671. cli.set_read_timeout(10, 0);
  8672. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8673. auto res =
  8674. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8675. total_received += data_length;
  8676. return true;
  8677. });
  8678. // Should fail because 200MB exceeds the explicit 150MB limit
  8679. EXPECT_FALSE(res);
  8680. }
  8681. server_thread.join();
  8682. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8683. << "Client with content_receiver should respect the explicit "
  8684. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8685. << total_received << " bytes.";
  8686. }
  8687. // Verify that an explicit set_payload_max_length larger than the response
  8688. // allows the content_receiver to read all data successfully.
  8689. TEST(ClientVulnerabilityTest,
  8690. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8691. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8692. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8693. #ifndef _WIN32
  8694. signal(SIGPIPE, SIG_IGN);
  8695. #endif
  8696. auto server_thread = std::thread([] {
  8697. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8698. default_socket_options(srv);
  8699. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8700. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8701. sockaddr_in addr{};
  8702. addr.sin_family = AF_INET;
  8703. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8704. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8705. int opt = 1;
  8706. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8707. #ifdef _WIN32
  8708. reinterpret_cast<const char *>(&opt),
  8709. #else
  8710. &opt,
  8711. #endif
  8712. sizeof(opt));
  8713. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8714. ::listen(srv, 1);
  8715. sockaddr_in cli_addr{};
  8716. socklen_t cli_len = sizeof(cli_addr);
  8717. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8718. if (cli != INVALID_SOCKET) {
  8719. char buf[4096];
  8720. ::recv(cli, buf, sizeof(buf), 0);
  8721. auto content_length = std::to_string(DATA_SIZE);
  8722. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8723. "Content-Length: " +
  8724. content_length +
  8725. "\r\n"
  8726. "Connection: close\r\n"
  8727. "\r\n";
  8728. ::send(cli,
  8729. #ifdef _WIN32
  8730. static_cast<const char *>(response_header.c_str()),
  8731. static_cast<int>(response_header.size()),
  8732. #else
  8733. response_header.c_str(), response_header.size(),
  8734. #endif
  8735. 0);
  8736. std::string chunk(64 * 1024, 'A');
  8737. size_t total_sent = 0;
  8738. while (total_sent < DATA_SIZE) {
  8739. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8740. auto sent = ::send(cli,
  8741. #ifdef _WIN32
  8742. static_cast<const char *>(chunk.c_str()),
  8743. static_cast<int>(to_send),
  8744. #else
  8745. chunk.c_str(), to_send,
  8746. #endif
  8747. 0);
  8748. if (sent <= 0) break;
  8749. total_sent += static_cast<size_t>(sent);
  8750. }
  8751. #ifdef _WIN32
  8752. ::shutdown(cli, SD_SEND);
  8753. #else
  8754. ::shutdown(cli, SHUT_WR);
  8755. #endif
  8756. char drain[1024];
  8757. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8758. detail::close_socket(cli);
  8759. }
  8760. detail::close_socket(srv);
  8761. });
  8762. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8763. size_t total_received = 0;
  8764. {
  8765. Client cli("127.0.0.1", PORT + 2);
  8766. cli.set_read_timeout(10, 0);
  8767. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8768. auto res =
  8769. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8770. total_received += data_length;
  8771. return true;
  8772. });
  8773. ASSERT_TRUE(res);
  8774. EXPECT_EQ(StatusCode::OK_200, res->status);
  8775. }
  8776. server_thread.join();
  8777. EXPECT_EQ(total_received, DATA_SIZE)
  8778. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8779. << " bytes (larger than " << DATA_SIZE
  8780. << " bytes response), content_receiver should read all data, but only "
  8781. "read "
  8782. << total_received << " bytes.";
  8783. }
  8784. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8785. // Regression test for "zip bomb" attack on the client side: a malicious server
  8786. // sends a small gzip-compressed response that decompresses to a huge payload.
  8787. // The client must enforce payload_max_length on the decompressed size.
  8788. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8789. constexpr size_t DECOMPRESSED_SIZE =
  8790. 10 * 1024 * 1024; // 10MB after decompression
  8791. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8792. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8793. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8794. std::string compressed;
  8795. {
  8796. httplib::detail::gzip_compressor compressor;
  8797. bool ok =
  8798. compressor.compress(uncompressed.data(), uncompressed.size(),
  8799. /*last=*/true, [&](const char *buf, size_t len) {
  8800. compressed.append(buf, len);
  8801. return true;
  8802. });
  8803. ASSERT_TRUE(ok);
  8804. }
  8805. // Sanity: compressed data should be much smaller than the decompressed size
  8806. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8807. #ifndef _WIN32
  8808. signal(SIGPIPE, SIG_IGN);
  8809. #endif
  8810. // Set up the listening socket in the main thread so the server is guaranteed
  8811. // to be ready before the client connects (eliminates race condition).
  8812. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8813. default_socket_options(srv);
  8814. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8815. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8816. sockaddr_in addr{};
  8817. addr.sin_family = AF_INET;
  8818. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8819. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8820. int opt = 1;
  8821. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8822. #ifdef _WIN32
  8823. reinterpret_cast<const char *>(&opt),
  8824. #else
  8825. &opt,
  8826. #endif
  8827. sizeof(opt));
  8828. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8829. ASSERT_EQ(0, ::listen(srv, 1));
  8830. auto server_thread = std::thread([&compressed, srv] {
  8831. sockaddr_in cli_addr{};
  8832. socklen_t cli_len = sizeof(cli_addr);
  8833. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8834. if (cli != INVALID_SOCKET) {
  8835. // Read the full HTTP request (until \r\n\r\n)
  8836. char buf[4096];
  8837. size_t total = 0;
  8838. while (total < sizeof(buf)) {
  8839. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8840. if (n <= 0) break;
  8841. total += static_cast<size_t>(n);
  8842. // Check for end of headers
  8843. if (total >= 4) {
  8844. std::string req(buf, total);
  8845. if (req.find("\r\n\r\n") != std::string::npos) break;
  8846. }
  8847. }
  8848. // Malicious response: gzip-compressed body, no Content-Length
  8849. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8850. "Content-Encoding: gzip\r\n"
  8851. "Connection: close\r\n"
  8852. "\r\n";
  8853. ::send(cli,
  8854. #ifdef _WIN32
  8855. static_cast<const char *>(response_header.c_str()),
  8856. static_cast<int>(response_header.size()),
  8857. #else
  8858. response_header.c_str(), response_header.size(),
  8859. #endif
  8860. 0);
  8861. // Send the compressed payload (small on the wire, huge when decompressed)
  8862. size_t total_sent = 0;
  8863. while (total_sent < compressed.size()) {
  8864. auto to_send = std::min(compressed.size() - total_sent,
  8865. static_cast<size_t>(64 * 1024));
  8866. auto sent =
  8867. ::send(cli,
  8868. #ifdef _WIN32
  8869. static_cast<const char *>(compressed.c_str() + total_sent),
  8870. static_cast<int>(to_send),
  8871. #else
  8872. compressed.c_str() + total_sent, to_send,
  8873. #endif
  8874. 0);
  8875. if (sent <= 0) break;
  8876. total_sent += static_cast<size_t>(sent);
  8877. }
  8878. detail::close_socket(cli);
  8879. }
  8880. });
  8881. auto se = detail::scope_exit([&] {
  8882. detail::close_socket(srv);
  8883. server_thread.join();
  8884. });
  8885. size_t total_decompressed = 0;
  8886. {
  8887. Client cli("127.0.0.1", PORT + 3);
  8888. cli.set_read_timeout(5, 0);
  8889. cli.set_decompress(true);
  8890. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8891. auto stream = cli.open_stream("GET", "/zipbomb");
  8892. ASSERT_TRUE(stream.is_valid());
  8893. char buffer[64 * 1024];
  8894. ssize_t n;
  8895. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8896. total_decompressed += static_cast<size_t>(n);
  8897. }
  8898. }
  8899. // The decompressed size must be capped by payload_max_length. Without
  8900. // protection, the client would decompress the full 10MB from a tiny
  8901. // compressed payload, enabling a zip bomb DoS attack.
  8902. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8903. << "Client decompressed " << total_decompressed
  8904. << " bytes from a gzip response. The decompressed size should be "
  8905. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8906. }
  8907. #endif
  8908. TEST(HostAndPortPropertiesTest, NoSSL) {
  8909. httplib::Client cli("www.google.com", 1234);
  8910. ASSERT_EQ("www.google.com", cli.host());
  8911. ASSERT_EQ(1234, cli.port());
  8912. }
  8913. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8914. httplib::Client cli("www.google.com:1234");
  8915. ASSERT_EQ("www.google.com", cli.host());
  8916. ASSERT_EQ(1234, cli.port());
  8917. }
  8918. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8919. // Port number that overflows int — should not crash, client becomes invalid
  8920. httplib::Client cli("http://www.google.com:99999999999999999999");
  8921. ASSERT_FALSE(cli.is_valid());
  8922. }
  8923. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8924. // Port 99999 exceeds valid range (1-65535) — should not crash
  8925. httplib::Client cli("http://www.google.com:99999");
  8926. ASSERT_FALSE(cli.is_valid());
  8927. }
  8928. #ifdef CPPHTTPLIB_SSL_ENABLED
  8929. TEST(HostAndPortPropertiesTest, SSL) {
  8930. httplib::SSLClient cli("www.google.com");
  8931. ASSERT_EQ("www.google.com", cli.host());
  8932. ASSERT_EQ(443, cli.port());
  8933. }
  8934. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8935. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8936. std::string cert;
  8937. read_file(CA_CERT_FILE, cert);
  8938. httplib::SSLClient httplib_client("www.google.com");
  8939. // Load CA store first time
  8940. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8941. // Load CA store second time (update)
  8942. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8943. // Verify client is still valid and can make connections
  8944. httplib_client.enable_server_certificate_verification(true);
  8945. auto res = httplib_client.Get("/");
  8946. ASSERT_TRUE(res);
  8947. // Google may return 200 or 301 depending on various factors
  8948. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8949. res->status == StatusCode::MovedPermanently_301);
  8950. }
  8951. TEST(SSLClientTest, ServerNameIndication_Online) {
  8952. auto host = "httpbingo.org";
  8953. auto path = std::string{"/get"};
  8954. SSLClient cli(host, 443);
  8955. auto res = cli.Get(path);
  8956. ASSERT_TRUE(res);
  8957. ASSERT_EQ(StatusCode::OK_200, res->status);
  8958. }
  8959. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8960. // Use a site that will cause SSL verification failure due to self-signed cert
  8961. SSLClient cli("self-signed.badssl.com", 443);
  8962. cli.enable_server_certificate_verification(true);
  8963. auto res = cli.Get("/");
  8964. ASSERT_TRUE(!res);
  8965. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8966. // Verify backend error is captured for SSLServerVerification
  8967. // This occurs when certificate verification fails
  8968. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8969. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8970. EXPECT_NE(0UL, res.ssl_backend_error());
  8971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8972. // For OpenSSL, ssl_error is 0 for verification errors
  8973. EXPECT_EQ(0, res.ssl_error());
  8974. #if !defined(_WIN32) || \
  8975. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8976. // On non-Windows or when Windows Schannel is disabled, the error comes
  8977. // from OpenSSL's verification
  8978. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8979. res.ssl_backend_error());
  8980. #endif
  8981. #endif
  8982. }
  8983. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8984. // Use a site where hostname doesn't match the certificate
  8985. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8986. SSLClient cli("wrong.host.badssl.com", 443);
  8987. cli.enable_server_certificate_verification(true);
  8988. cli.enable_server_hostname_verification(true);
  8989. auto res = cli.Get("/");
  8990. ASSERT_TRUE(!res);
  8991. // The error type depends on when hostname verification occurs:
  8992. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8993. // - Mbed TLS: SSLServerVerification (during handshake)
  8994. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8995. res.error() == Error::SSLServerVerification);
  8996. // Verify backend error is captured for hostname verification failure
  8997. EXPECT_NE(0UL, res.ssl_backend_error());
  8998. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8999. // For OpenSSL, ssl_error is 0 for verification errors
  9000. EXPECT_EQ(0, res.ssl_error());
  9001. #if !defined(_WIN32) || \
  9002. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9003. // On non-Windows or when Windows Schannel is disabled, the error comes
  9004. // from OpenSSL's hostname verification
  9005. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9006. res.ssl_backend_error());
  9007. #endif
  9008. #endif
  9009. }
  9010. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9011. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9012. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9013. SSLClient cli("www.google.com", 443);
  9014. cli.enable_server_certificate_verification(true);
  9015. auto res = cli.Get("/");
  9016. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9017. }
  9018. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9019. SSLClient cli("www.google.com", 443);
  9020. cli.enable_server_certificate_verification(true);
  9021. cli.enable_windows_certificate_verification(false);
  9022. auto res = cli.Get("/");
  9023. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9024. }
  9025. #endif
  9026. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9027. Client cli("https://google.com");
  9028. auto res = cli.Get("/");
  9029. ASSERT_TRUE(res);
  9030. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9031. }
  9032. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9033. SSLClient cli("google.com");
  9034. cli.set_ca_cert_path(CA_CERT_FILE);
  9035. auto res = cli.Get("/");
  9036. ASSERT_TRUE(res);
  9037. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9038. }
  9039. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9040. SSLClient cli("google.com");
  9041. cli.enable_server_certificate_verification(true);
  9042. cli.set_ca_cert_path("hello");
  9043. auto res = cli.Get("/");
  9044. ASSERT_TRUE(!res);
  9045. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9046. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9047. // should be set
  9048. EXPECT_EQ(0, res.ssl_error());
  9049. // Verify backend error is captured for SSLLoadingCerts
  9050. // This error occurs when loading CA certificates fails
  9051. EXPECT_NE(0UL, res.ssl_backend_error());
  9052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9053. // OpenSSL specific error codes:
  9054. // > openssl errstr 0x80000002
  9055. // error:80000002:system library::No such file or directory
  9056. // > openssl errstr 0xA000126
  9057. // error:0A000126:SSL routines::unexpected eof while reading
  9058. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9059. res.ssl_backend_error() == 0xA000126);
  9060. #endif
  9061. }
  9062. TEST(SSLClientTest, ServerCertificateVerification4) {
  9063. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9064. ASSERT_TRUE(svr.is_valid());
  9065. svr.Get("/test", [&](const Request &, Response &res) {
  9066. res.set_content("test", "text/plain");
  9067. svr.stop();
  9068. ASSERT_TRUE(true);
  9069. });
  9070. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9071. auto se = detail::scope_exit([&] {
  9072. t.join();
  9073. ASSERT_FALSE(svr.is_running());
  9074. });
  9075. svr.wait_until_ready();
  9076. SSLClient cli("127.0.0.1", PORT);
  9077. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9078. cli.enable_server_certificate_verification(true);
  9079. cli.set_connection_timeout(30);
  9080. auto res = cli.Get("/test");
  9081. ASSERT_TRUE(res);
  9082. ASSERT_EQ(StatusCode::OK_200, res->status);
  9083. }
  9084. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9085. std::string cert;
  9086. read_file(CA_CERT_FILE, cert);
  9087. SSLClient cli("google.com");
  9088. cli.load_ca_cert_store(cert.data(), cert.size());
  9089. const auto res = cli.Get("/");
  9090. ASSERT_TRUE(res);
  9091. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9092. }
  9093. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9094. // clang-format off
  9095. static constexpr char cert[] =
  9096. "GlobalSign Root CA\n"
  9097. "==================\n"
  9098. "-----BEGIN CERTIFICATE-----\n"
  9099. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9100. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9101. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9102. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9103. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9104. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9105. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9106. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9107. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9108. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9109. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9110. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9111. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9112. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9113. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9114. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9115. "-----END CERTIFICATE-----\n";
  9116. // clang-format on
  9117. SSLClient cli("google.com");
  9118. cli.load_ca_cert_store(cert, sizeof(cert));
  9119. const auto res = cli.Get("/");
  9120. ASSERT_TRUE(res);
  9121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9122. }
  9123. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9124. SSLClient cli("www.youtube.com");
  9125. cli.set_ca_cert_path(CA_CERT_FILE);
  9126. cli.enable_server_certificate_verification(true);
  9127. cli.set_follow_location(true);
  9128. auto res = cli.Get("/");
  9129. ASSERT_TRUE(res);
  9130. ASSERT_EQ(StatusCode::OK_200, res->status);
  9131. }
  9132. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9133. SSLClient cli("wWw.YouTube.Com");
  9134. cli.set_ca_cert_path(CA_CERT_FILE);
  9135. cli.enable_server_certificate_verification(true);
  9136. cli.enable_server_hostname_verification(true);
  9137. cli.set_follow_location(true);
  9138. auto res = cli.Get("/");
  9139. ASSERT_TRUE(res);
  9140. ASSERT_EQ(StatusCode::OK_200, res->status);
  9141. }
  9142. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9143. SSLClient cli("gOoGlE.COm");
  9144. cli.enable_server_certificate_verification(true);
  9145. cli.enable_server_hostname_verification(true);
  9146. cli.set_follow_location(true);
  9147. auto res = cli.Get("/");
  9148. ASSERT_TRUE(res);
  9149. ASSERT_EQ(StatusCode::OK_200, res->status);
  9150. }
  9151. TEST(SSLClientTest, Issue2004_Online) {
  9152. Client client("https://google.com");
  9153. client.set_follow_location(true);
  9154. auto res = client.Get("/");
  9155. ASSERT_TRUE(res);
  9156. ASSERT_EQ(StatusCode::OK_200, res->status);
  9157. auto body = res->body;
  9158. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9159. }
  9160. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9161. // Create SSLClient with invalid cert/key to make is_valid() return false
  9162. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9163. "nonexistent_key.pem");
  9164. // is_valid() should be false due to cert loading failure
  9165. ASSERT_FALSE(cli.is_valid());
  9166. auto res = cli.Get("/");
  9167. ASSERT_FALSE(res);
  9168. EXPECT_EQ(Error::SSLConnection, res.error());
  9169. }
  9170. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9171. // Test for Issue #2251: SSL error not properly reported when client cert
  9172. // and key paths are swapped or mismatched
  9173. // This simulates the scenario where user accidentally swaps the cert and key
  9174. // files
  9175. // Using client cert file as private key and vice versa (completely wrong)
  9176. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9177. // Should fail validation due to cert/key mismatch
  9178. ASSERT_FALSE(cli.is_valid());
  9179. // Attempt to make a request should fail with proper error
  9180. auto res = cli.Get("/");
  9181. ASSERT_FALSE(res);
  9182. EXPECT_EQ(Error::SSLConnection, res.error());
  9183. // SSL error should be recorded in the Result object (this is the key fix for
  9184. // Issue #2251)
  9185. auto backend_error = res.ssl_backend_error();
  9186. EXPECT_NE(0u, backend_error);
  9187. }
  9188. // Tests cert/key mismatch detection at the TLS context level
  9189. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9190. // Test that using mismatched cert/key causes connection failure.
  9191. // We verify this at the SSLClient level rather than through internal
  9192. // TLS API functions.
  9193. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9194. cli.enable_server_certificate_verification(false);
  9195. cli.set_connection_timeout(2);
  9196. // The mismatch should cause a connection or handshake error
  9197. auto res = cli.Get("/test");
  9198. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9199. // Either way, the request should fail
  9200. EXPECT_FALSE(res);
  9201. }
  9202. #endif
  9203. #if 0
  9204. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9205. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9206. ASSERT_TRUE(cli != nullptr);
  9207. cli->set_address_family(AF_INET6);
  9208. cli->set_interface("en0");
  9209. auto res = cli->Get("/get");
  9210. ASSERT_TRUE(res);
  9211. ASSERT_EQ(StatusCode::OK_200, res->status);
  9212. }
  9213. #endif
  9214. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9215. #ifdef CPPHTTPLIB_SSL_ENABLED
  9216. void ClientCertPresent(
  9217. const std::string &client_cert_file,
  9218. const std::string &client_private_key_file,
  9219. const std::string &client_encrypted_private_key_pass = std::string()) {
  9220. using namespace httplib::tls;
  9221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9222. CLIENT_CA_CERT_DIR);
  9223. ASSERT_TRUE(svr.is_valid());
  9224. svr.Get("/test", [&](const Request &req, Response &res) {
  9225. res.set_content("test", "text/plain");
  9226. auto cert = req.peer_cert();
  9227. ASSERT_TRUE(static_cast<bool>(cert));
  9228. std::string common_name = cert.subject_cn();
  9229. EXPECT_EQ("Common Name", common_name);
  9230. });
  9231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9232. auto se = detail::scope_exit([&] {
  9233. svr.stop();
  9234. t.join();
  9235. ASSERT_FALSE(svr.is_running());
  9236. });
  9237. svr.wait_until_ready();
  9238. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9239. client_encrypted_private_key_pass);
  9240. cli.enable_server_certificate_verification(false);
  9241. cli.set_connection_timeout(30);
  9242. auto res = cli.Get("/test");
  9243. ASSERT_TRUE(res);
  9244. ASSERT_EQ(StatusCode::OK_200, res->status);
  9245. }
  9246. TEST(SSLClientServerTest, ClientCertPresent) {
  9247. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9248. }
  9249. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9250. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9251. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9252. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9253. }
  9254. // PEM memory-based constructor tests (works with all TLS backends)
  9255. void PemMemoryClientCertPresent(
  9256. const std::string &client_cert_file,
  9257. const std::string &client_private_key_file,
  9258. const std::string &client_encrypted_private_key_pass = std::string()) {
  9259. // Read PEM files into memory
  9260. std::string server_cert_pem, server_key_pem;
  9261. std::string client_ca_pem;
  9262. std::string client_cert_pem, client_key_pem;
  9263. read_file(SERVER_CERT_FILE, server_cert_pem);
  9264. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9265. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9266. read_file(client_cert_file, client_cert_pem);
  9267. read_file(client_private_key_file, client_key_pem);
  9268. // Create server with PEM memory
  9269. SSLServer::PemMemory server_pem = {
  9270. server_cert_pem.c_str(),
  9271. server_cert_pem.size(),
  9272. server_key_pem.c_str(),
  9273. server_key_pem.size(),
  9274. client_ca_pem.c_str(),
  9275. client_ca_pem.size(),
  9276. nullptr // no password for server key
  9277. };
  9278. SSLServer svr(server_pem);
  9279. ASSERT_TRUE(svr.is_valid());
  9280. svr.Get("/test", [&](const Request &, Response &res) {
  9281. res.set_content("test", "text/plain");
  9282. });
  9283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9284. auto se = detail::scope_exit([&] {
  9285. svr.stop();
  9286. t.join();
  9287. ASSERT_FALSE(svr.is_running());
  9288. });
  9289. svr.wait_until_ready();
  9290. // Create client with PEM memory
  9291. const char *password = client_encrypted_private_key_pass.empty()
  9292. ? nullptr
  9293. : client_encrypted_private_key_pass.c_str();
  9294. SSLClient::PemMemory client_pem = {
  9295. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9296. client_key_pem.size(), password};
  9297. SSLClient cli(HOST, PORT, client_pem);
  9298. cli.enable_server_certificate_verification(false);
  9299. cli.set_connection_timeout(30);
  9300. auto res = cli.Get("/test");
  9301. ASSERT_TRUE(res);
  9302. ASSERT_EQ(StatusCode::OK_200, res->status);
  9303. }
  9304. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9305. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9306. }
  9307. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9308. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9309. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9310. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9311. }
  9312. TEST(SSLClientServerTest, ClientCertMissing) {
  9313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9314. CLIENT_CA_CERT_DIR);
  9315. ASSERT_TRUE(svr.is_valid());
  9316. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9317. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9318. auto se = detail::scope_exit([&] {
  9319. svr.stop();
  9320. t.join();
  9321. ASSERT_FALSE(svr.is_running());
  9322. });
  9323. svr.wait_until_ready();
  9324. SSLClient cli(HOST, PORT);
  9325. cli.set_connection_timeout(30);
  9326. auto res = cli.Get("/test");
  9327. ASSERT_TRUE(!res);
  9328. // When client cert is missing and server requires it, connection fails
  9329. // Error type depends on backend implementation
  9330. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9331. res.error() == Error::SSLConnection);
  9332. // Verify backend error is captured
  9333. // Note: This test may have different error codes depending on the exact
  9334. // verification failure
  9335. EXPECT_NE(0UL, res.ssl_backend_error());
  9336. }
  9337. TEST(SSLClientServerTest, TrustDirOptional) {
  9338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9339. ASSERT_TRUE(svr.is_valid());
  9340. svr.Get("/test", [&](const Request &, Response &res) {
  9341. res.set_content("test", "text/plain");
  9342. });
  9343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9344. auto se = detail::scope_exit([&] {
  9345. svr.stop();
  9346. t.join();
  9347. ASSERT_FALSE(svr.is_running());
  9348. });
  9349. svr.wait_until_ready();
  9350. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9351. cli.enable_server_certificate_verification(false);
  9352. cli.set_connection_timeout(30);
  9353. auto res = cli.Get("/test");
  9354. ASSERT_TRUE(res);
  9355. ASSERT_EQ(StatusCode::OK_200, res->status);
  9356. }
  9357. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9358. class NoListenSSLServer : public SSLServer {
  9359. public:
  9360. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9361. const char *client_ca_cert_file_path,
  9362. const char *client_ca_cert_dir_path = nullptr)
  9363. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9364. client_ca_cert_dir_path),
  9365. stop_(false) {}
  9366. std::atomic_bool stop_;
  9367. private:
  9368. bool process_and_close_socket(socket_t /*sock*/) override {
  9369. // Don't create SSL context
  9370. while (!stop_.load()) {
  9371. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9372. }
  9373. return true;
  9374. }
  9375. };
  9376. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9377. CLIENT_CA_CERT_FILE);
  9378. ASSERT_TRUE(svr.is_valid());
  9379. svr.Get("/test", [&](const Request &, Response &res) {
  9380. res.set_content("test", "text/plain");
  9381. });
  9382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9383. auto se = detail::scope_exit([&] {
  9384. svr.stop_ = true;
  9385. svr.stop();
  9386. t.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9391. cli.enable_server_certificate_verification(false);
  9392. cli.set_connection_timeout(1);
  9393. auto res = cli.Get("/test");
  9394. ASSERT_TRUE(!res);
  9395. EXPECT_EQ(Error::SSLConnection, res.error());
  9396. // Timeout results in WantRead error code (maps to backend-specific value)
  9397. EXPECT_NE(0, res.ssl_error());
  9398. }
  9399. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9400. // Test SSLServer with client certificate verification using the standard
  9401. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9403. CLIENT_CA_CERT_DIR);
  9404. ASSERT_TRUE(svr.is_valid());
  9405. svr.Get("/test", [&](const Request &req, Response &res) {
  9406. res.set_content("test", "text/plain");
  9407. auto cert = req.peer_cert();
  9408. ASSERT_TRUE(static_cast<bool>(cert));
  9409. auto common_name = cert.subject_cn();
  9410. EXPECT_EQ("Common Name", common_name);
  9411. });
  9412. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9413. auto se = detail::scope_exit([&] {
  9414. svr.stop();
  9415. t.join();
  9416. ASSERT_FALSE(svr.is_running());
  9417. });
  9418. svr.wait_until_ready();
  9419. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9420. cli.enable_server_certificate_verification(false);
  9421. cli.set_connection_timeout(30);
  9422. auto res = cli.Get("/test");
  9423. ASSERT_TRUE(res);
  9424. ASSERT_EQ(StatusCode::OK_200, res->status);
  9425. }
  9426. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9427. // Verifies that wildcard matching and exact matching work consistently
  9428. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9429. using namespace httplib::tls;
  9430. // We need a running server to test against
  9431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9432. ASSERT_TRUE(svr.is_valid());
  9433. svr.Get("/test", [](const Request &, Response &res) {
  9434. res.set_content("ok", "text/plain");
  9435. });
  9436. thread t([&]() { svr.listen(HOST, PORT); });
  9437. auto se = detail::scope_exit([&] {
  9438. svr.stop();
  9439. t.join();
  9440. });
  9441. svr.wait_until_ready();
  9442. bool verify_callback_called = false;
  9443. bool verify_result_wrong = false;
  9444. SSLClient cli(HOST, PORT);
  9445. cli.enable_server_certificate_verification(true);
  9446. cli.set_ca_cert_path(CA_CERT_FILE);
  9447. cli.set_connection_timeout(5);
  9448. // Note: Test certificate has CN="Common Name", not "localhost"
  9449. bool verify_result_cn = false;
  9450. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9451. verify_callback_called = true;
  9452. if (!ctx.cert) return false;
  9453. // Test 1: "Common Name" should match (our test server cert CN)
  9454. verify_result_cn = ctx.check_hostname("Common Name");
  9455. // Test 2: wrong hostname should not match
  9456. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9457. return true; // Accept for the purpose of this test
  9458. });
  9459. auto res = cli.Get("/test");
  9460. // The request may succeed or fail depending on cert configuration
  9461. // but the callback should have been called
  9462. ASSERT_TRUE(verify_callback_called)
  9463. << "Verify callback should have been called";
  9464. // CN="Common Name" should match our test certificate
  9465. //
  9466. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9467. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9468. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9469. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9470. // <openssl/base.h>, which is included transitively when
  9471. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9472. #if defined(OPENSSL_IS_BORINGSSL)
  9473. EXPECT_FALSE(verify_result_cn)
  9474. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9475. #else
  9476. EXPECT_TRUE(verify_result_cn)
  9477. << "verify_hostname should match 'Common Name' (certificate CN)";
  9478. #endif
  9479. // Wrong hostname should not match
  9480. EXPECT_FALSE(verify_result_wrong)
  9481. << "verify_hostname should not match 'wronghost.example.com'";
  9482. }
  9483. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9484. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9485. // X509_check_ip behavior and must hold for every backend.
  9486. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9487. using namespace httplib::tls;
  9488. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9489. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9490. ASSERT_TRUE(svr.is_valid());
  9491. svr.Get("/test", [](const Request &, Response &res) {
  9492. res.set_content("ok", "text/plain");
  9493. });
  9494. thread t([&]() { svr.listen(HOST, PORT); });
  9495. auto se = detail::scope_exit([&] {
  9496. svr.stop();
  9497. t.join();
  9498. });
  9499. svr.wait_until_ready();
  9500. bool verify_callback_called = false;
  9501. bool ip_matched_via_cn = true;
  9502. SSLClient cli(HOST, PORT);
  9503. cli.enable_server_certificate_verification(true);
  9504. cli.set_ca_cert_path(CA_CERT_FILE);
  9505. cli.set_connection_timeout(5);
  9506. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9507. verify_callback_called = true;
  9508. if (!ctx.cert) return false;
  9509. // The IP appears only in the CN, so it must NOT be accepted.
  9510. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9511. return true; // Accept for the purpose of this test
  9512. });
  9513. cli.Get("/test");
  9514. ASSERT_TRUE(verify_callback_called)
  9515. << "Verify callback should have been called";
  9516. EXPECT_FALSE(ip_matched_via_cn)
  9517. << "An IP host must not be authenticated via the certificate CN";
  9518. }
  9519. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9520. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9521. using namespace httplib::tls;
  9522. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9523. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9524. ASSERT_TRUE(svr.is_valid());
  9525. svr.Get("/test", [](const Request &, Response &res) {
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t([&]() { svr.listen(HOST, PORT); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. });
  9533. svr.wait_until_ready();
  9534. bool verify_callback_called = false;
  9535. bool san_matched = false;
  9536. bool wrong_ipv6_matched = true;
  9537. bool cn_ipv6_matched = true;
  9538. SSLClient cli(HOST, PORT);
  9539. cli.enable_server_certificate_verification(true);
  9540. cli.set_ca_cert_path(CA_CERT_FILE);
  9541. cli.set_connection_timeout(5);
  9542. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9543. verify_callback_called = true;
  9544. if (!ctx.cert) return false;
  9545. // Matches the IPv6 iPAddress SAN.
  9546. san_matched = ctx.check_hostname("2001:db8::1");
  9547. // A different IPv6 address must not match.
  9548. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9549. // "::1" lives only in the CN, so it must not be accepted.
  9550. cn_ipv6_matched = ctx.check_hostname("::1");
  9551. return true; // Accept for the purpose of this test
  9552. });
  9553. cli.Get("/test");
  9554. ASSERT_TRUE(verify_callback_called)
  9555. << "Verify callback should have been called";
  9556. EXPECT_TRUE(san_matched)
  9557. << "verify_hostname should match an IPv6 iPAddress SAN";
  9558. EXPECT_FALSE(wrong_ipv6_matched)
  9559. << "verify_hostname should not match a non-matching IPv6 address";
  9560. EXPECT_FALSE(cn_ipv6_matched)
  9561. << "An IPv6 host must not be authenticated via the certificate CN";
  9562. }
  9563. #endif
  9564. // mbedTLS-specific callback constructor test
  9565. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9566. #ifdef CPPHTTPLIB_SSL_ENABLED
  9567. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9569. ASSERT_TRUE(svr.is_valid());
  9570. // Set up a handler to verify client certificate is present
  9571. bool client_cert_verified = false;
  9572. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9573. // Verify that client certificate was provided
  9574. client_cert_verified = true;
  9575. res.set_content("success", "text/plain");
  9576. });
  9577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9578. auto se = detail::scope_exit([&] {
  9579. svr.stop();
  9580. t.join();
  9581. ASSERT_FALSE(svr.is_running());
  9582. });
  9583. svr.wait_until_ready();
  9584. // Client with certificate
  9585. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9586. cli.enable_server_certificate_verification(false);
  9587. cli.set_connection_timeout(30);
  9588. auto res = cli.Get("/test");
  9589. ASSERT_TRUE(res);
  9590. ASSERT_EQ(StatusCode::OK_200, res->status);
  9591. ASSERT_TRUE(client_cert_verified);
  9592. EXPECT_EQ("success", res->body);
  9593. }
  9594. #endif
  9595. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9596. // backends
  9597. #ifdef CPPHTTPLIB_SSL_ENABLED
  9598. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9599. using namespace httplib::tls;
  9600. // Test that when client CA cert file is provided,
  9601. // the server properly requests and validates client certificates
  9602. // Create a server with client authentication
  9603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9604. ASSERT_TRUE(svr.is_valid());
  9605. bool handler_called = false;
  9606. svr.Get("/test", [&](const Request &req, Response &res) {
  9607. handler_called = true;
  9608. // Verify that a client certificate was provided
  9609. auto cert = req.peer_cert();
  9610. ASSERT_TRUE(static_cast<bool>(cert));
  9611. // Get the issuer name
  9612. std::string issuer_str = cert.issuer_name();
  9613. ASSERT_FALSE(issuer_str.empty());
  9614. // The client certificate should be issued by our test CA
  9615. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9616. res.set_content("authenticated", "text/plain");
  9617. });
  9618. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9619. auto se = detail::scope_exit([&] {
  9620. svr.stop();
  9621. t.join();
  9622. ASSERT_FALSE(svr.is_running());
  9623. });
  9624. svr.wait_until_ready();
  9625. // Connect with a client certificate issued by the CA
  9626. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9627. cli.enable_server_certificate_verification(false);
  9628. cli.set_connection_timeout(30);
  9629. auto res = cli.Get("/test");
  9630. ASSERT_TRUE(res);
  9631. ASSERT_EQ(StatusCode::OK_200, res->status);
  9632. ASSERT_TRUE(handler_called);
  9633. EXPECT_EQ("authenticated", res->body);
  9634. }
  9635. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9636. using namespace httplib::tls;
  9637. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9638. ASSERT_TRUE(svr.is_valid());
  9639. svr.Get("/test", [](const Request &, Response &res) {
  9640. res.set_content("ok", "text/plain");
  9641. });
  9642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9643. auto se = detail::scope_exit([&] {
  9644. svr.stop();
  9645. t.join();
  9646. });
  9647. svr.wait_until_ready();
  9648. SSLClient cli(HOST, PORT);
  9649. cli.enable_server_certificate_verification(false);
  9650. cli.set_connection_timeout(30);
  9651. bool cert_checked = false;
  9652. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9653. if (ctx.cert) {
  9654. auto sans = ctx.sans();
  9655. // Test certificate may or may not have SANs - just verify the API
  9656. // works If SANs exist, verify the types are valid
  9657. for (const auto &san : sans) {
  9658. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9659. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9660. san.type == SanType::OTHER);
  9661. EXPECT_FALSE(san.value.empty());
  9662. }
  9663. cert_checked = true;
  9664. }
  9665. return true;
  9666. });
  9667. auto res = cli.Get("/test");
  9668. ASSERT_TRUE(res);
  9669. EXPECT_TRUE(cert_checked);
  9670. }
  9671. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9672. using namespace httplib::tls;
  9673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9674. ASSERT_TRUE(svr.is_valid());
  9675. svr.Get("/test", [](const Request &, Response &res) {
  9676. res.set_content("ok", "text/plain");
  9677. });
  9678. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. t.join();
  9682. });
  9683. svr.wait_until_ready();
  9684. SSLClient cli(HOST, PORT);
  9685. cli.enable_server_certificate_verification(false);
  9686. cli.set_connection_timeout(30);
  9687. bool validity_checked = false;
  9688. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9689. if (ctx.cert) {
  9690. time_t not_before = 0, not_after = 0;
  9691. bool result = ctx.validity(not_before, not_after);
  9692. EXPECT_TRUE(result);
  9693. // Verify that not_before < now < not_after for a valid cert
  9694. time_t now = time(nullptr);
  9695. EXPECT_LT(not_before, now);
  9696. EXPECT_GT(not_after, now);
  9697. validity_checked = true;
  9698. }
  9699. return true;
  9700. });
  9701. auto res = cli.Get("/test");
  9702. ASSERT_TRUE(res);
  9703. EXPECT_TRUE(validity_checked);
  9704. }
  9705. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9706. using namespace httplib::tls;
  9707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9708. ASSERT_TRUE(svr.is_valid());
  9709. svr.Get("/test", [](const Request &, Response &res) {
  9710. res.set_content("ok", "text/plain");
  9711. });
  9712. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9713. auto se = detail::scope_exit([&] {
  9714. svr.stop();
  9715. t.join();
  9716. });
  9717. svr.wait_until_ready();
  9718. SSLClient cli(HOST, PORT);
  9719. cli.enable_server_certificate_verification(false);
  9720. cli.set_connection_timeout(30);
  9721. bool serial_checked = false;
  9722. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9723. if (ctx.cert) {
  9724. std::string serial = ctx.serial();
  9725. EXPECT_FALSE(serial.empty());
  9726. // Serial should be a hex string
  9727. for (char c : serial) {
  9728. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9729. (c >= 'a' && c <= 'f'));
  9730. }
  9731. serial_checked = true;
  9732. }
  9733. return true;
  9734. });
  9735. auto res = cli.Get("/test");
  9736. ASSERT_TRUE(res);
  9737. EXPECT_TRUE(serial_checked);
  9738. }
  9739. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9740. // Test 1: Valid CA file - no error should be recorded
  9741. {
  9742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9743. CLIENT_CA_CERT_FILE);
  9744. ASSERT_TRUE(svr.is_valid());
  9745. // With valid setup, last_ssl_error should be 0
  9746. EXPECT_EQ(0, svr.ssl_last_error());
  9747. }
  9748. // Test 2: Invalid CA file content
  9749. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9750. {
  9751. // Create a temporary file with completely invalid content
  9752. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9753. {
  9754. std::ofstream ofs(temp_invalid_ca);
  9755. ofs << "This is not a certificate file at all\n";
  9756. ofs << "Just plain text content\n";
  9757. }
  9758. // Create server with invalid CA file
  9759. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9760. // Clean up temporary file
  9761. std::remove(temp_invalid_ca);
  9762. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9763. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9764. // Note: SSL_CTX_load_verify_locations typically fails first,
  9765. // but our error handling code path is still exercised
  9766. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9767. }
  9768. }
  9769. TEST(VerifyCallbackTest, VerifyContextFields) {
  9770. using namespace httplib::tls;
  9771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9772. ASSERT_TRUE(svr.is_valid());
  9773. svr.Get("/test", [](const Request &, Response &res) {
  9774. res.set_content("ok", "text/plain");
  9775. });
  9776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9777. auto se = detail::scope_exit([&] {
  9778. svr.stop();
  9779. t.join();
  9780. });
  9781. svr.wait_until_ready();
  9782. SSLClient cli(HOST, PORT);
  9783. cli.enable_server_certificate_verification(false);
  9784. cli.set_connection_timeout(30);
  9785. int callback_count = 0;
  9786. bool saw_leaf_cert = false;
  9787. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9788. if (ctx.cert) {
  9789. callback_count++;
  9790. // We should see at least one certificate (the leaf)
  9791. std::string cn = ctx.subject_cn();
  9792. if (!cn.empty()) { saw_leaf_cert = true; }
  9793. // Verify context fields are populated
  9794. EXPECT_NE(ctx.session, nullptr);
  9795. EXPECT_GE(ctx.depth, 0);
  9796. }
  9797. return true;
  9798. });
  9799. auto res = cli.Get("/test");
  9800. ASSERT_TRUE(res);
  9801. EXPECT_GT(callback_count, 0);
  9802. EXPECT_TRUE(saw_leaf_cert);
  9803. }
  9804. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9805. using httplib::tls::TlsError;
  9806. // Test that verify_error_to_string returns empty for success
  9807. std::string success_str = TlsError::verify_error_to_string(0);
  9808. EXPECT_TRUE(success_str.empty());
  9809. // Test that verify_error_to_string returns non-empty for error codes
  9810. // Using a common error code (certificate expired)
  9811. std::string error_str =
  9812. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9813. EXPECT_FALSE(error_str.empty());
  9814. }
  9815. TEST(SessionVerifierTest, CertificateAccepted) {
  9816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9817. ASSERT_TRUE(svr.is_valid());
  9818. svr.Get("/test", [](const Request &, Response &res) {
  9819. res.set_content("ok", "text/plain");
  9820. });
  9821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9822. auto se = detail::scope_exit([&] {
  9823. svr.stop();
  9824. t.join();
  9825. });
  9826. svr.wait_until_ready();
  9827. SSLClient cli(HOST, PORT);
  9828. cli.enable_server_certificate_verification(false);
  9829. cli.set_connection_timeout(30);
  9830. bool callback_called = false;
  9831. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9832. EXPECT_NE(session, nullptr);
  9833. callback_called = true;
  9834. return SSLVerifierResponse::CertificateAccepted;
  9835. });
  9836. auto res = cli.Get("/test");
  9837. ASSERT_TRUE(res);
  9838. EXPECT_EQ(200, res->status);
  9839. EXPECT_TRUE(callback_called);
  9840. }
  9841. TEST(SessionVerifierTest, CertificateRejected) {
  9842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9843. ASSERT_TRUE(svr.is_valid());
  9844. svr.Get("/test", [](const Request &, Response &res) {
  9845. res.set_content("ok", "text/plain");
  9846. });
  9847. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9848. auto se = detail::scope_exit([&] {
  9849. svr.stop();
  9850. t.join();
  9851. });
  9852. svr.wait_until_ready();
  9853. SSLClient cli(HOST, PORT);
  9854. cli.enable_server_certificate_verification(false);
  9855. cli.set_connection_timeout(30);
  9856. bool callback_called = false;
  9857. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9858. EXPECT_NE(session, nullptr);
  9859. callback_called = true;
  9860. return SSLVerifierResponse::CertificateRejected;
  9861. });
  9862. auto res = cli.Get("/test");
  9863. EXPECT_FALSE(res);
  9864. EXPECT_TRUE(callback_called);
  9865. }
  9866. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9868. ASSERT_TRUE(svr.is_valid());
  9869. svr.Get("/test", [](const Request &, Response &res) {
  9870. res.set_content("ok", "text/plain");
  9871. });
  9872. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9873. auto se = detail::scope_exit([&] {
  9874. svr.stop();
  9875. t.join();
  9876. });
  9877. svr.wait_until_ready();
  9878. // NoDecisionMade with verification disabled should succeed (no default check)
  9879. SSLClient cli(HOST, PORT);
  9880. cli.enable_server_certificate_verification(false);
  9881. cli.set_connection_timeout(30);
  9882. bool callback_called = false;
  9883. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9884. EXPECT_NE(session, nullptr);
  9885. callback_called = true;
  9886. return SSLVerifierResponse::NoDecisionMade;
  9887. });
  9888. auto res = cli.Get("/test");
  9889. ASSERT_TRUE(res);
  9890. EXPECT_EQ(200, res->status);
  9891. EXPECT_TRUE(callback_called);
  9892. }
  9893. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9895. ASSERT_TRUE(svr.is_valid());
  9896. svr.Get("/test", [](const Request &, Response &res) {
  9897. res.set_content("ok", "text/plain");
  9898. });
  9899. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9900. auto se = detail::scope_exit([&] {
  9901. svr.stop();
  9902. t.join();
  9903. });
  9904. svr.wait_until_ready();
  9905. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9906. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9907. // so we only check that the request fails, not whether the callback was
  9908. // called.
  9909. SSLClient cli(HOST, PORT);
  9910. cli.enable_server_certificate_verification(true);
  9911. cli.set_connection_timeout(30);
  9912. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9913. EXPECT_NE(session, nullptr);
  9914. return SSLVerifierResponse::NoDecisionMade;
  9915. });
  9916. auto res = cli.Get("/test");
  9917. EXPECT_FALSE(res);
  9918. }
  9919. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9920. // Test SSL server using PemMemory constructor with client CA certificates
  9921. // Read PEM files
  9922. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9923. read_file(SERVER_CERT_FILE, server_cert_pem);
  9924. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9925. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9926. // Create SSLServer with PemMemory constructor including client CA
  9927. SSLServer::PemMemory server_pem = {
  9928. server_cert_pem.c_str(),
  9929. server_cert_pem.size(),
  9930. server_key_pem.c_str(),
  9931. server_key_pem.size(),
  9932. client_ca_pem.c_str(),
  9933. client_ca_pem.size(),
  9934. nullptr // no password for server key
  9935. };
  9936. SSLServer svr(server_pem);
  9937. ASSERT_TRUE(svr.is_valid());
  9938. // No SSL error should be recorded for valid setup
  9939. EXPECT_EQ(0, svr.ssl_last_error());
  9940. // Set up server endpoints
  9941. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9942. res.set_content("ok", "text/plain");
  9943. });
  9944. // Start server in a thread
  9945. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9946. svr.wait_until_ready();
  9947. // Connect with client certificate (using constructor with paths)
  9948. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9949. cli.enable_server_certificate_verification(false);
  9950. auto res = cli.Get("/test-pem-ca");
  9951. ASSERT_TRUE(res);
  9952. EXPECT_EQ(200, res->status);
  9953. EXPECT_EQ("ok", res->body);
  9954. svr.stop();
  9955. server_thread.join();
  9956. }
  9957. #endif
  9958. #ifdef _WIN32
  9959. TEST(CleanupTest, WSACleanup) {
  9960. int ret = WSACleanup();
  9961. ASSERT_EQ(0, ret);
  9962. }
  9963. #endif
  9964. #ifndef CPPHTTPLIB_SSL_ENABLED
  9965. TEST(NoSSLSupport, SimpleInterface) {
  9966. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9967. }
  9968. #endif
  9969. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9970. TEST(InvalidScheme, SimpleInterface) {
  9971. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9972. }
  9973. #endif
  9974. TEST(NoScheme, SimpleInterface) {
  9975. Client cli("yahoo.com:80");
  9976. ASSERT_TRUE(cli.is_valid());
  9977. }
  9978. TEST(SendAPI, SimpleInterface_Online) {
  9979. Client cli("http://yahoo.com");
  9980. Request req;
  9981. req.method = "GET";
  9982. req.path = "/";
  9983. auto res = cli.send(req);
  9984. ASSERT_TRUE(res);
  9985. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9986. }
  9987. TEST(SendAPI, WithParamsInRequest) {
  9988. Server svr;
  9989. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9990. EXPECT_TRUE(req.has_param("test"));
  9991. EXPECT_EQ("test_value", req.get_param_value("test"));
  9992. });
  9993. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. t.join();
  9997. ASSERT_FALSE(svr.is_running());
  9998. });
  9999. svr.wait_until_ready();
  10000. Client cli(HOST, PORT);
  10001. {
  10002. Request req;
  10003. req.method = "GET";
  10004. req.path = "/";
  10005. req.params.emplace("test", "test_value");
  10006. auto res = cli.send(req);
  10007. ASSERT_TRUE(res);
  10008. }
  10009. {
  10010. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10011. ASSERT_TRUE(res);
  10012. }
  10013. }
  10014. TEST(ClientImplMethods, GetSocketTest) {
  10015. httplib::Server svr;
  10016. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10017. res.status = StatusCode::OK_200;
  10018. });
  10019. auto port = svr.bind_to_any_port("127.0.0.1");
  10020. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. thread.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. });
  10026. svr.wait_until_ready();
  10027. {
  10028. httplib::Client cli("127.0.0.1", port);
  10029. cli.set_keep_alive(true);
  10030. // Use the behavior of cpp-httplib of opening the connection
  10031. // only when the first request happens. If that changes,
  10032. // this test would be obsolete.
  10033. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10034. // This also implicitly tests the server. But other tests would fail much
  10035. // earlier than this one to be considered.
  10036. auto res = cli.Get("/");
  10037. ASSERT_TRUE(res);
  10038. EXPECT_EQ(StatusCode::OK_200, res->status);
  10039. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10040. }
  10041. }
  10042. #ifdef CPPHTTPLIB_SSL_ENABLED
  10043. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10044. Client cli("http://yahoo.com");
  10045. auto res = cli.Get("/");
  10046. ASSERT_TRUE(res);
  10047. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10048. cli.set_follow_location(true);
  10049. res = cli.Get("/");
  10050. ASSERT_TRUE(res);
  10051. EXPECT_EQ(StatusCode::OK_200, res->status);
  10052. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10053. }
  10054. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10055. Client cli("https://yahoo.com");
  10056. auto res = cli.Get("/");
  10057. ASSERT_TRUE(res);
  10058. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10059. cli.set_follow_location(true);
  10060. res = cli.Get("/");
  10061. ASSERT_TRUE(res);
  10062. EXPECT_EQ(StatusCode::OK_200, res->status);
  10063. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10064. }
  10065. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10066. Client cli("https://yahoo.com");
  10067. auto res = cli.Get("/");
  10068. ASSERT_TRUE(res);
  10069. ASSERT_FALSE(!res);
  10070. ASSERT_TRUE(res);
  10071. ASSERT_FALSE(res == nullptr);
  10072. ASSERT_TRUE(res != nullptr);
  10073. EXPECT_EQ(Error::Success, res.error());
  10074. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10075. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10076. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10077. cli.set_follow_location(true);
  10078. res = cli.Get("/");
  10079. ASSERT_TRUE(res);
  10080. EXPECT_EQ(Error::Success, res.error());
  10081. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10082. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10083. EXPECT_EQ(StatusCode::OK_200, res->status);
  10084. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10085. }
  10086. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10087. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10088. Client cli("https://cdnjs.cloudflare.com");
  10089. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10090. Headers{{"Accept-Encoding", "br"}});
  10091. ASSERT_TRUE(res);
  10092. EXPECT_EQ(StatusCode::OK_200, res->status);
  10093. EXPECT_EQ(287630U, res->body.size());
  10094. EXPECT_EQ("application/javascript; charset=utf-8",
  10095. res->get_header_value("Content-Type"));
  10096. }
  10097. #endif
  10098. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10099. #undef REDIR_HOST // Silence compiler warning
  10100. #define REDIR_HOST "https://httpbingo.org"
  10101. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10102. Client cli(REDIR_HOST);
  10103. cli.set_follow_location(true);
  10104. auto res =
  10105. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10106. ASSERT_TRUE(res);
  10107. EXPECT_EQ(StatusCode::OK_200, res->status);
  10108. }
  10109. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10110. Client cli(REDIR_HOST);
  10111. cli.set_follow_location(true);
  10112. Params params;
  10113. params.emplace("url", "http://example.com");
  10114. params.emplace("status_code", "302");
  10115. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10116. ASSERT_TRUE(res);
  10117. EXPECT_EQ(StatusCode::OK_200, res->status);
  10118. }
  10119. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10120. Client cli(REDIR_HOST);
  10121. cli.set_follow_location(true);
  10122. Params params;
  10123. params.emplace("url", "http://example.com");
  10124. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10125. ASSERT_TRUE(res);
  10126. EXPECT_EQ(StatusCode::OK_200, res->status);
  10127. }
  10128. TEST(HttpToHttpsRedirectTest, CertFile) {
  10129. auto ssl_port = PORT + 1;
  10130. Server svr;
  10131. ASSERT_TRUE(svr.is_valid());
  10132. svr.Get("/index", [&](const Request &, Response &res) {
  10133. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10134. "/index");
  10135. svr.stop();
  10136. });
  10137. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10138. ASSERT_TRUE(ssl_svr.is_valid());
  10139. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10140. res.set_content("test", "text/plain");
  10141. ssl_svr.stop();
  10142. });
  10143. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10144. thread t2 =
  10145. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10146. auto se = detail::scope_exit([&] {
  10147. t2.join();
  10148. t.join();
  10149. ASSERT_FALSE(svr.is_running());
  10150. });
  10151. svr.wait_until_ready();
  10152. ssl_svr.wait_until_ready();
  10153. Client cli("127.0.0.1", PORT);
  10154. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10155. cli.enable_server_certificate_verification(true);
  10156. cli.set_follow_location(true);
  10157. cli.set_connection_timeout(30);
  10158. auto res = cli.Get("/index");
  10159. ASSERT_TRUE(res);
  10160. ASSERT_EQ(StatusCode::OK_200, res->status);
  10161. }
  10162. TEST(SSLClientRedirectTest, CertFile) {
  10163. auto ssl_port = PORT + 1;
  10164. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10165. ASSERT_TRUE(ssl_svr1.is_valid());
  10166. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10167. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10168. "/index");
  10169. ssl_svr1.stop();
  10170. });
  10171. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10172. ASSERT_TRUE(ssl_svr2.is_valid());
  10173. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10174. res.set_content("test", "text/plain");
  10175. ssl_svr2.stop();
  10176. });
  10177. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10178. thread t2 =
  10179. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10180. auto se = detail::scope_exit([&] {
  10181. t2.join();
  10182. t.join();
  10183. ASSERT_FALSE(ssl_svr1.is_running());
  10184. });
  10185. ssl_svr1.wait_until_ready();
  10186. ssl_svr2.wait_until_ready();
  10187. SSLClient cli("127.0.0.1", PORT);
  10188. std::string cert;
  10189. read_file(SERVER_CERT2_FILE, cert);
  10190. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10191. cli.enable_server_certificate_verification(true);
  10192. cli.set_follow_location(true);
  10193. cli.set_connection_timeout(30);
  10194. auto res = cli.Get("/index");
  10195. ASSERT_TRUE(res);
  10196. ASSERT_EQ(StatusCode::OK_200, res->status);
  10197. }
  10198. #endif
  10199. #ifdef CPPHTTPLIB_SSL_ENABLED
  10200. // Test that set_ca_cert_store() skips system certs (consistent with
  10201. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10202. // should be trusted - system certs should NOT be loaded.
  10203. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10204. // Load a specific cert that is NOT a system CA cert
  10205. std::string cert;
  10206. read_file(SERVER_CERT2_FILE, cert);
  10207. SSLClient cli("google.com");
  10208. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10209. cli.enable_server_certificate_verification(true);
  10210. // This should FAIL because:
  10211. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10212. // 2. System certs should NOT be loaded when custom store is set
  10213. // If system certs WERE loaded, this would succeed
  10214. auto res = cli.Get("/");
  10215. ASSERT_FALSE(res);
  10216. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10217. }
  10218. // Same as above, but through the native store handle path. Regression test:
  10219. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10220. // merged system certs into the user-provided store.
  10221. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10222. std::string cert;
  10223. read_file(SERVER_CERT2_FILE, cert);
  10224. SSLClient cli("google.com");
  10225. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10226. cli.enable_server_certificate_verification(true);
  10227. auto res = cli.Get("/");
  10228. ASSERT_FALSE(res);
  10229. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10230. }
  10231. // A custom store set via the native handle must still verify a server whose
  10232. // cert it does contain.
  10233. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10234. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10235. ASSERT_TRUE(svr.is_valid());
  10236. svr.Get("/test", [&](const Request &, Response &res) {
  10237. res.set_content("test", "text/plain");
  10238. });
  10239. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10240. auto se = detail::scope_exit([&] {
  10241. svr.stop();
  10242. t.join();
  10243. ASSERT_FALSE(svr.is_running());
  10244. });
  10245. svr.wait_until_ready();
  10246. SSLClient cli("127.0.0.1", PORT);
  10247. std::string cert;
  10248. read_file(SERVER_CERT2_FILE, cert);
  10249. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10250. cli.enable_server_certificate_verification(true);
  10251. cli.set_connection_timeout(30);
  10252. auto res = cli.Get("/test");
  10253. ASSERT_TRUE(res);
  10254. ASSERT_EQ(StatusCode::OK_200, res->status);
  10255. }
  10256. // CA certs loaded through the universal Client must be transferred to the
  10257. // client created internally for following an HTTPS redirect. Regression test:
  10258. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10259. // the CA data for redirect transfer.
  10260. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10261. auto ssl_port = PORT + 1;
  10262. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10263. ASSERT_TRUE(ssl_svr1.is_valid());
  10264. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10265. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10266. "/index");
  10267. });
  10268. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10269. ASSERT_TRUE(ssl_svr2.is_valid());
  10270. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10271. res.set_content("test", "text/plain");
  10272. });
  10273. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10274. thread t2 =
  10275. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10276. auto se = detail::scope_exit([&] {
  10277. ssl_svr2.stop();
  10278. ssl_svr1.stop();
  10279. t2.join();
  10280. t.join();
  10281. ASSERT_FALSE(ssl_svr1.is_running());
  10282. });
  10283. ssl_svr1.wait_until_ready();
  10284. ssl_svr2.wait_until_ready();
  10285. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10286. std::string cert;
  10287. read_file(SERVER_CERT2_FILE, cert);
  10288. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10289. cli.enable_server_certificate_verification(true);
  10290. cli.set_follow_location(true);
  10291. cli.set_connection_timeout(30);
  10292. auto res = cli.Get("/index");
  10293. ASSERT_TRUE(res);
  10294. ASSERT_EQ(StatusCode::OK_200, res->status);
  10295. }
  10296. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10297. // so a host signed by a system CA verifies even though a custom CA is set
  10298. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10299. std::string cert;
  10300. read_file(SERVER_CERT2_FILE, cert);
  10301. SSLClient cli("google.com");
  10302. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10303. cli.enable_system_ca(true);
  10304. cli.enable_server_certificate_verification(true);
  10305. auto res = cli.Get("/");
  10306. ASSERT_TRUE(res);
  10307. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10308. }
  10309. // The custom CA remains effective when combined with the system CA
  10310. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10311. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10312. ASSERT_TRUE(svr.is_valid());
  10313. svr.Get("/test", [&](const Request &, Response &res) {
  10314. res.set_content("test", "text/plain");
  10315. });
  10316. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10317. auto se = detail::scope_exit([&] {
  10318. svr.stop();
  10319. t.join();
  10320. ASSERT_FALSE(svr.is_running());
  10321. });
  10322. svr.wait_until_ready();
  10323. SSLClient cli("127.0.0.1", PORT);
  10324. std::string cert;
  10325. read_file(SERVER_CERT2_FILE, cert);
  10326. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10327. cli.enable_system_ca(true);
  10328. cli.enable_server_certificate_verification(true);
  10329. cli.set_connection_timeout(30);
  10330. auto res = cli.Get("/test");
  10331. ASSERT_TRUE(res);
  10332. ASSERT_EQ(StatusCode::OK_200, res->status);
  10333. }
  10334. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10335. // skip chain verification entirely (only the certificate identity was
  10336. // checked), so a server presenting an untrusted certificate with a matching
  10337. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10338. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10339. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10340. ASSERT_TRUE(svr.is_valid());
  10341. svr.Get("/test", [&](const Request &, Response &res) {
  10342. res.set_content("test", "text/plain");
  10343. });
  10344. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10345. auto se = detail::scope_exit([&] {
  10346. svr.stop();
  10347. t.join();
  10348. ASSERT_FALSE(svr.is_running());
  10349. });
  10350. svr.wait_until_ready();
  10351. SSLClient cli("127.0.0.1", PORT);
  10352. std::string cert;
  10353. // A trusted CA that did not sign the server certificate. The server cert
  10354. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10355. // this connection.
  10356. read_file(CLIENT_CA_CERT_FILE, cert);
  10357. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10358. cli.enable_server_certificate_verification(true);
  10359. cli.set_connection_timeout(30);
  10360. auto res = cli.Get("/test");
  10361. ASSERT_FALSE(res);
  10362. }
  10363. // enable_system_ca(false) prevents system CA loading entirely
  10364. TEST(SSLClientTest, DisableSystemCa_Online) {
  10365. SSLClient cli("google.com");
  10366. cli.enable_system_ca(false);
  10367. cli.enable_server_certificate_verification(true);
  10368. auto res = cli.Get("/");
  10369. ASSERT_FALSE(res);
  10370. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10371. // itself when the CA chain is empty
  10372. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10373. res.error() == Error::SSLConnection);
  10374. }
  10375. // The universal Client forwards enable_system_ca()
  10376. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10377. std::string cert;
  10378. read_file(SERVER_CERT2_FILE, cert);
  10379. Client cli("https://google.com");
  10380. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10381. cli.enable_system_ca(true);
  10382. cli.enable_server_certificate_verification(true);
  10383. auto res = cli.Get("/");
  10384. ASSERT_TRUE(res);
  10385. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10386. }
  10387. // The system CA policy must carry over to the client created internally for
  10388. // following a cross-host HTTPS redirect
  10389. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10390. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10391. ASSERT_TRUE(svr.is_valid());
  10392. svr.Get("/index", [&](const Request &, Response &res) {
  10393. res.set_redirect("https://www.google.com/");
  10394. });
  10395. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10396. auto se = detail::scope_exit([&] {
  10397. svr.stop();
  10398. t.join();
  10399. ASSERT_FALSE(svr.is_running());
  10400. });
  10401. svr.wait_until_ready();
  10402. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10403. std::string cert;
  10404. read_file(SERVER_CERT2_FILE, cert);
  10405. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10406. cli.enable_system_ca(true);
  10407. cli.enable_server_certificate_verification(true);
  10408. cli.set_follow_location(true);
  10409. cli.set_connection_timeout(30);
  10410. // Receiving any response proves the redirect client completed the TLS
  10411. // handshake with a system-CA-signed host
  10412. auto res = cli.Get("/index");
  10413. ASSERT_TRUE(res);
  10414. }
  10415. TEST(MultipartFormDataTest, LargeData) {
  10416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10417. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10418. const ContentReader &content_reader) {
  10419. if (req.is_multipart_form_data()) {
  10420. std::vector<FormData> items;
  10421. content_reader(
  10422. [&](const FormData &file) {
  10423. items.push_back(file);
  10424. return true;
  10425. },
  10426. [&](const char *data, size_t data_length) {
  10427. items.back().content.append(data, data_length);
  10428. return true;
  10429. });
  10430. EXPECT_TRUE(std::string(items[0].name) == "document");
  10431. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10432. EXPECT_TRUE(items[0].filename == "2MB_data");
  10433. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10434. EXPECT_TRUE(items[1].name == "hello");
  10435. EXPECT_TRUE(items[1].content == "world");
  10436. EXPECT_TRUE(items[1].filename == "");
  10437. EXPECT_TRUE(items[1].content_type == "");
  10438. } else {
  10439. std::string body;
  10440. content_reader([&](const char *data, size_t data_length) {
  10441. body.append(data, data_length);
  10442. return true;
  10443. });
  10444. }
  10445. });
  10446. auto port = svr.bind_to_any_port(HOST);
  10447. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10448. auto se = detail::scope_exit([&] {
  10449. svr.stop();
  10450. t.join();
  10451. ASSERT_FALSE(svr.is_running());
  10452. });
  10453. svr.wait_until_ready();
  10454. {
  10455. std::string data(1024 * 1024 * 2, '.');
  10456. std::stringstream buffer;
  10457. buffer << data;
  10458. SSLClient cli(HOST, port);
  10459. cli.enable_server_certificate_verification(false);
  10460. UploadFormDataItems items{
  10461. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10462. {"hello", "world", "", ""},
  10463. };
  10464. auto res = cli.Post("/post", items);
  10465. ASSERT_TRUE(res);
  10466. ASSERT_EQ(StatusCode::OK_200, res->status);
  10467. }
  10468. }
  10469. TEST(MultipartFormDataTest, DataProviderItems) {
  10470. std::random_device seed_gen;
  10471. std::mt19937 random(seed_gen());
  10472. std::string rand1;
  10473. rand1.resize(1000);
  10474. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10475. std::string rand2;
  10476. rand2.resize(3000);
  10477. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10479. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10480. const ContentReader &content_reader) {
  10481. ASSERT_FALSE(req.is_multipart_form_data());
  10482. std::string body;
  10483. content_reader([&](const char *data, size_t data_length) {
  10484. body.append(data, data_length);
  10485. return true;
  10486. });
  10487. EXPECT_EQ(body, "");
  10488. });
  10489. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10490. const ContentReader &content_reader) {
  10491. ASSERT_TRUE(req.is_multipart_form_data());
  10492. std::vector<FormData> items;
  10493. content_reader(
  10494. [&](const FormData &file) {
  10495. items.push_back(file);
  10496. return true;
  10497. },
  10498. [&](const char *data, size_t data_length) {
  10499. items.back().content.append(data, data_length);
  10500. return true;
  10501. });
  10502. ASSERT_TRUE(items.size() == 2);
  10503. EXPECT_EQ(std::string(items[0].name), "name1");
  10504. EXPECT_EQ(items[0].content, "Testing123");
  10505. EXPECT_EQ(items[0].filename, "filename1");
  10506. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10507. EXPECT_EQ(items[1].name, "name2");
  10508. EXPECT_EQ(items[1].content, "Testing456");
  10509. EXPECT_EQ(items[1].filename, "");
  10510. EXPECT_EQ(items[1].content_type, "");
  10511. });
  10512. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10513. const ContentReader &content_reader) {
  10514. ASSERT_TRUE(req.is_multipart_form_data());
  10515. std::vector<FormData> items;
  10516. content_reader(
  10517. [&](const FormData &file) {
  10518. items.push_back(file);
  10519. return true;
  10520. },
  10521. [&](const char *data, size_t data_length) {
  10522. items.back().content.append(data, data_length);
  10523. return true;
  10524. });
  10525. ASSERT_TRUE(items.size() == 2);
  10526. EXPECT_EQ(items[0].name, "name3");
  10527. EXPECT_EQ(items[0].content, rand1);
  10528. EXPECT_EQ(items[0].filename, "filename3");
  10529. EXPECT_EQ(items[0].content_type, "");
  10530. EXPECT_EQ(items[1].name, "name4");
  10531. EXPECT_EQ(items[1].content, rand2);
  10532. EXPECT_EQ(items[1].filename, "filename4");
  10533. EXPECT_EQ(items[1].content_type, "");
  10534. });
  10535. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10536. const ContentReader &content_reader) {
  10537. ASSERT_TRUE(req.is_multipart_form_data());
  10538. std::vector<FormData> items;
  10539. content_reader(
  10540. [&](const FormData &file) {
  10541. items.push_back(file);
  10542. return true;
  10543. },
  10544. [&](const char *data, size_t data_length) {
  10545. items.back().content.append(data, data_length);
  10546. return true;
  10547. });
  10548. ASSERT_TRUE(items.size() == 4);
  10549. EXPECT_EQ(std::string(items[0].name), "name1");
  10550. EXPECT_EQ(items[0].content, "Testing123");
  10551. EXPECT_EQ(items[0].filename, "filename1");
  10552. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10553. EXPECT_EQ(items[1].name, "name2");
  10554. EXPECT_EQ(items[1].content, "Testing456");
  10555. EXPECT_EQ(items[1].filename, "");
  10556. EXPECT_EQ(items[1].content_type, "");
  10557. EXPECT_EQ(items[2].name, "name3");
  10558. EXPECT_EQ(items[2].content, rand1);
  10559. EXPECT_EQ(items[2].filename, "filename3");
  10560. EXPECT_EQ(items[2].content_type, "");
  10561. EXPECT_EQ(items[3].name, "name4");
  10562. EXPECT_EQ(items[3].content, rand2);
  10563. EXPECT_EQ(items[3].filename, "filename4");
  10564. EXPECT_EQ(items[3].content_type, "");
  10565. });
  10566. auto port = svr.bind_to_any_port("localhost");
  10567. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10568. auto se = detail::scope_exit([&] {
  10569. svr.stop();
  10570. t.join();
  10571. ASSERT_FALSE(svr.is_running());
  10572. });
  10573. svr.wait_until_ready();
  10574. {
  10575. SSLClient cli("localhost", port);
  10576. cli.enable_server_certificate_verification(false);
  10577. UploadFormDataItems items{
  10578. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10579. {"name2", "Testing456", "", ""}, // not a file
  10580. };
  10581. {
  10582. auto res = cli.Post("/post-none", {}, {}, {});
  10583. ASSERT_TRUE(res);
  10584. ASSERT_EQ(StatusCode::OK_200, res->status);
  10585. }
  10586. FormDataProviderItems providers;
  10587. {
  10588. auto res =
  10589. cli.Post("/post-items", {}, items, providers); // empty providers
  10590. ASSERT_TRUE(res);
  10591. ASSERT_EQ(StatusCode::OK_200, res->status);
  10592. }
  10593. providers.push_back({"name3",
  10594. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10595. // test the offset is given correctly at each step
  10596. if (!offset)
  10597. sink.os.write(rand1.data(), 30);
  10598. else if (offset == 30)
  10599. sink.os.write(rand1.data() + 30, 300);
  10600. else if (offset == 330)
  10601. sink.os.write(rand1.data() + 330, 670);
  10602. else if (offset == rand1.size())
  10603. sink.done();
  10604. return true;
  10605. },
  10606. "filename3",
  10607. {}});
  10608. providers.push_back({"name4",
  10609. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10610. // test the offset is given correctly at each step
  10611. if (!offset)
  10612. sink.os.write(rand2.data(), 2000);
  10613. else if (offset == 2000)
  10614. sink.os.write(rand2.data() + 2000, 1);
  10615. else if (offset == 2001)
  10616. sink.os.write(rand2.data() + 2001, 999);
  10617. else if (offset == rand2.size())
  10618. sink.done();
  10619. return true;
  10620. },
  10621. "filename4",
  10622. {}});
  10623. {
  10624. auto res = cli.Post("/post-providers", {}, {}, providers);
  10625. ASSERT_TRUE(res);
  10626. ASSERT_EQ(StatusCode::OK_200, res->status);
  10627. }
  10628. {
  10629. auto res = cli.Post("/post-both", {}, items, providers);
  10630. ASSERT_TRUE(res);
  10631. ASSERT_EQ(StatusCode::OK_200, res->status);
  10632. }
  10633. }
  10634. }
  10635. TEST(MultipartFormDataTest, BadHeader) {
  10636. Server svr;
  10637. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10638. res.set_content("ok", "text/plain");
  10639. });
  10640. thread t = thread([&] { svr.listen(HOST, PORT); });
  10641. auto se = detail::scope_exit([&] {
  10642. svr.stop();
  10643. t.join();
  10644. ASSERT_FALSE(svr.is_running());
  10645. });
  10646. svr.wait_until_ready();
  10647. const std::string body =
  10648. "This is the preamble. It is to be ignored, though it\r\n"
  10649. "is a handy place for composition agents to include an\r\n"
  10650. "explanatory note to non-MIME conformant readers.\r\n"
  10651. "\r\n"
  10652. "\r\n"
  10653. "--simple boundary\r\n"
  10654. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10655. ": BAD...\r\n"
  10656. "\r\n"
  10657. "value1\r\n"
  10658. "--simple boundary\r\n"
  10659. "Content-Disposition: form-data; name=\"field2\"; "
  10660. "filename=\"example.txt\"\r\n"
  10661. "\r\n"
  10662. "value2\r\n"
  10663. "--simple boundary--\r\n"
  10664. "This is the epilogue. It is also to be ignored.\r\n";
  10665. std::string content_type =
  10666. R"(multipart/form-data; boundary="simple boundary")";
  10667. Client cli(HOST, PORT);
  10668. auto res = cli.Post("/post", body, content_type.c_str());
  10669. ASSERT_TRUE(res);
  10670. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10671. }
  10672. TEST(MultipartFormDataTest, WithPreamble) {
  10673. Server svr;
  10674. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10675. res.set_content("ok", "text/plain");
  10676. });
  10677. thread t = thread([&] { svr.listen(HOST, PORT); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. t.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. });
  10683. svr.wait_until_ready();
  10684. const std::string body =
  10685. "This is the preamble. It is to be ignored, though it\r\n"
  10686. "is a handy place for composition agents to include an\r\n"
  10687. "explanatory note to non-MIME conformant readers.\r\n"
  10688. "\r\n"
  10689. "\r\n"
  10690. "--simple boundary\r\n"
  10691. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10692. "\r\n"
  10693. "value1\r\n"
  10694. "--simple boundary\r\n"
  10695. "Content-Disposition: form-data; name=\"field2\"; "
  10696. "filename=\"example.txt\"\r\n"
  10697. "\r\n"
  10698. "value2\r\n"
  10699. "--simple boundary--\r\n"
  10700. "This is the epilogue. It is also to be ignored.\r\n";
  10701. std::string content_type =
  10702. R"(multipart/form-data; boundary="simple boundary")";
  10703. Client cli(HOST, PORT);
  10704. auto res = cli.Post("/post", body, content_type.c_str());
  10705. ASSERT_TRUE(res);
  10706. EXPECT_EQ(StatusCode::OK_200, res->status);
  10707. }
  10708. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10710. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10711. const ContentReader &content_reader) {
  10712. if (req.is_multipart_form_data()) {
  10713. std::vector<FormData> items;
  10714. content_reader(
  10715. [&](const FormData &file) {
  10716. items.push_back(file);
  10717. return true;
  10718. },
  10719. [&](const char *data, size_t data_length) {
  10720. items.back().content.append(data, data_length);
  10721. return true;
  10722. });
  10723. EXPECT_TRUE(std::string(items[0].name) == "document");
  10724. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10725. EXPECT_TRUE(items[0].filename == "2MB_data");
  10726. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10727. EXPECT_TRUE(items[1].name == "hello");
  10728. EXPECT_TRUE(items[1].content == "world");
  10729. EXPECT_TRUE(items[1].filename == "");
  10730. EXPECT_TRUE(items[1].content_type == "");
  10731. } else {
  10732. std::string body;
  10733. content_reader([&](const char *data, size_t data_length) {
  10734. body.append(data, data_length);
  10735. return true;
  10736. });
  10737. }
  10738. });
  10739. auto port = svr.bind_to_any_port("localhost");
  10740. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10741. auto se = detail::scope_exit([&] {
  10742. svr.stop();
  10743. t.join();
  10744. ASSERT_FALSE(svr.is_running());
  10745. });
  10746. svr.wait_until_ready();
  10747. {
  10748. std::string data(1024 * 1024 * 2, '.');
  10749. std::stringstream buffer;
  10750. buffer << data;
  10751. SSLClient cli("localhost", port);
  10752. cli.enable_server_certificate_verification(false);
  10753. UploadFormDataItems items{
  10754. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10755. {"hello", "world", "", ""},
  10756. };
  10757. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10758. ASSERT_TRUE(res);
  10759. ASSERT_EQ(StatusCode::OK_200, res->status);
  10760. }
  10761. }
  10762. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10763. std::string data(1024 * 1024 * 2, '&');
  10764. std::stringstream buffer;
  10765. buffer << data;
  10766. Client cli("https://localhost:8080");
  10767. UploadFormDataItems items{
  10768. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10769. {"hello", "world", "", ""},
  10770. };
  10771. for (const char &c : " \t\r\n") {
  10772. auto res =
  10773. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10774. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10775. ASSERT_FALSE(res);
  10776. }
  10777. }
  10778. TEST(MultipartFormDataTest, PutFormData) {
  10779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10780. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10781. const ContentReader &content_reader) {
  10782. if (req.is_multipart_form_data()) {
  10783. std::vector<FormData> items;
  10784. content_reader(
  10785. [&](const FormData &file) {
  10786. items.push_back(file);
  10787. return true;
  10788. },
  10789. [&](const char *data, size_t data_length) {
  10790. items.back().content.append(data, data_length);
  10791. return true;
  10792. });
  10793. EXPECT_TRUE(std::string(items[0].name) == "document");
  10794. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10795. EXPECT_TRUE(items[0].filename == "2MB_data");
  10796. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10797. EXPECT_TRUE(items[1].name == "hello");
  10798. EXPECT_TRUE(items[1].content == "world");
  10799. EXPECT_TRUE(items[1].filename == "");
  10800. EXPECT_TRUE(items[1].content_type == "");
  10801. } else {
  10802. std::string body;
  10803. content_reader([&](const char *data, size_t data_length) {
  10804. body.append(data, data_length);
  10805. return true;
  10806. });
  10807. }
  10808. });
  10809. auto port = svr.bind_to_any_port("localhost");
  10810. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10811. auto se = detail::scope_exit([&] {
  10812. svr.stop();
  10813. t.join();
  10814. ASSERT_FALSE(svr.is_running());
  10815. });
  10816. svr.wait_until_ready();
  10817. {
  10818. std::string data(1024 * 1024 * 2, '&');
  10819. std::stringstream buffer;
  10820. buffer << data;
  10821. SSLClient cli("localhost", port);
  10822. cli.enable_server_certificate_verification(false);
  10823. UploadFormDataItems items{
  10824. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10825. {"hello", "world", "", ""},
  10826. };
  10827. auto res = cli.Put("/put", items);
  10828. ASSERT_TRUE(res);
  10829. ASSERT_EQ(StatusCode::OK_200, res->status);
  10830. }
  10831. }
  10832. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10834. svr.Put("/put_customboundary",
  10835. [&](const Request &req, const Response & /*res*/,
  10836. const ContentReader &content_reader) {
  10837. if (req.is_multipart_form_data()) {
  10838. std::vector<FormData> items;
  10839. content_reader(
  10840. [&](const FormData &file) {
  10841. items.push_back(file);
  10842. return true;
  10843. },
  10844. [&](const char *data, size_t data_length) {
  10845. items.back().content.append(data, data_length);
  10846. return true;
  10847. });
  10848. EXPECT_TRUE(std::string(items[0].name) == "document");
  10849. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10850. EXPECT_TRUE(items[0].filename == "2MB_data");
  10851. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10852. EXPECT_TRUE(items[1].name == "hello");
  10853. EXPECT_TRUE(items[1].content == "world");
  10854. EXPECT_TRUE(items[1].filename == "");
  10855. EXPECT_TRUE(items[1].content_type == "");
  10856. } else {
  10857. std::string body;
  10858. content_reader([&](const char *data, size_t data_length) {
  10859. body.append(data, data_length);
  10860. return true;
  10861. });
  10862. }
  10863. });
  10864. auto port = svr.bind_to_any_port("localhost");
  10865. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10866. auto se = detail::scope_exit([&] {
  10867. svr.stop();
  10868. t.join();
  10869. ASSERT_FALSE(svr.is_running());
  10870. });
  10871. svr.wait_until_ready();
  10872. {
  10873. std::string data(1024 * 1024 * 2, '&');
  10874. std::stringstream buffer;
  10875. buffer << data;
  10876. SSLClient cli("localhost", port);
  10877. cli.enable_server_certificate_verification(false);
  10878. UploadFormDataItems items{
  10879. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10880. {"hello", "world", "", ""},
  10881. };
  10882. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10883. ASSERT_TRUE(res);
  10884. ASSERT_EQ(StatusCode::OK_200, res->status);
  10885. }
  10886. }
  10887. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10888. std::string data(1024 * 1024 * 2, '&');
  10889. std::stringstream buffer;
  10890. buffer << data;
  10891. Client cli("https://localhost:8080");
  10892. cli.enable_server_certificate_verification(false);
  10893. UploadFormDataItems items{
  10894. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10895. {"hello", "world", "", ""},
  10896. };
  10897. for (const char &c : " \t\r\n") {
  10898. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10899. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10900. ASSERT_FALSE(res);
  10901. }
  10902. }
  10903. TEST(MultipartFormDataTest, AlternateFilename) {
  10904. auto handled = false;
  10905. Server svr;
  10906. svr.Post("/test", [&](const Request &req, Response &res) {
  10907. ASSERT_EQ(2u, req.form.files.size());
  10908. ASSERT_EQ(1u, req.form.fields.size());
  10909. // Test files
  10910. const auto &file1 = req.form.get_file("file1");
  10911. ASSERT_EQ("file1", file1.name);
  10912. ASSERT_EQ("A.txt", file1.filename);
  10913. ASSERT_EQ("text/plain", file1.content_type);
  10914. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10915. const auto &file2 = req.form.get_file("file2");
  10916. ASSERT_EQ("file2", file2.name);
  10917. ASSERT_EQ("a.html", file2.filename);
  10918. ASSERT_EQ("text/html", file2.content_type);
  10919. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10920. file2.content);
  10921. // Test text field
  10922. const auto &text = req.form.get_field("text");
  10923. ASSERT_EQ("text default", text);
  10924. res.set_content("ok", "text/plain");
  10925. handled = true;
  10926. });
  10927. thread t = thread([&] { svr.listen(HOST, PORT); });
  10928. auto se = detail::scope_exit([&] {
  10929. svr.stop();
  10930. t.join();
  10931. ASSERT_FALSE(svr.is_running());
  10932. ASSERT_TRUE(handled);
  10933. });
  10934. svr.wait_until_ready();
  10935. auto req = "POST /test HTTP/1.1\r\n"
  10936. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10937. "Content-Length: 399\r\n"
  10938. "\r\n"
  10939. "----------\r\n"
  10940. "Content-Disposition: form-data; name=\"text\"\r\n"
  10941. "\r\n"
  10942. "text default\r\n"
  10943. "----------\r\n"
  10944. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10945. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10946. "Content-Type: text/plain\r\n"
  10947. "\r\n"
  10948. "Content of a.txt.\r\n"
  10949. "\r\n"
  10950. "----------\r\n"
  10951. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10952. "\"a.html\"\r\n"
  10953. "Content-Type: text/html\r\n"
  10954. "\r\n"
  10955. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10956. "\r\n"
  10957. "------------\r\n";
  10958. ASSERT_TRUE(send_request(1, req));
  10959. }
  10960. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10961. auto handled = false;
  10962. Server svr;
  10963. svr.Post("/test", [&](const Request &req, Response &res) {
  10964. // Case-insensitive "utf-8''" prefix with a long value
  10965. const auto &file = req.form.get_file("file1");
  10966. ASSERT_EQ("file1", file.name);
  10967. // 8000 chars exercises both the Content-Disposition parser and the
  10968. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10969. // Prior to the fix, std::regex_match on this header would cause O(N)
  10970. // stack recursion in libstdc++, leading to SIGSEGV.
  10971. std::string expected_filename(8000, 'A');
  10972. ASSERT_EQ(expected_filename, file.filename);
  10973. res.set_content("ok", "text/plain");
  10974. handled = true;
  10975. });
  10976. thread t = thread([&] { svr.listen(HOST, PORT); });
  10977. auto se = detail::scope_exit([&] {
  10978. svr.stop();
  10979. t.join();
  10980. ASSERT_FALSE(svr.is_running());
  10981. ASSERT_TRUE(handled);
  10982. });
  10983. svr.wait_until_ready();
  10984. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10985. // Regression test for GHSA-qq6v-r583-3h69
  10986. std::string long_filename(8000, 'A');
  10987. std::string body = "----------\r\n"
  10988. "Content-Disposition: form-data; name=\"file1\"; "
  10989. "filename*=\"Utf-8''" +
  10990. long_filename +
  10991. "\"\r\n"
  10992. "\r\n"
  10993. "hello\r\n"
  10994. "------------\r\n";
  10995. auto req = "POST /test HTTP/1.1\r\n"
  10996. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10997. "Content-Length: " +
  10998. std::to_string(body.size()) + "\r\n\r\n" + body;
  10999. ASSERT_TRUE(send_request(1, req));
  11000. }
  11001. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11002. auto handled = false;
  11003. Server svr;
  11004. svr.Post("/test", [&](const Request &req, Response &) {
  11005. ASSERT_EQ(2u, req.form.fields.size());
  11006. const auto &text1 = req.form.get_field("text1");
  11007. ASSERT_EQ("text1", text1);
  11008. const auto &text2 = req.form.get_field("text2");
  11009. ASSERT_EQ("text2", text2);
  11010. handled = true;
  11011. });
  11012. thread t = thread([&] { svr.listen(HOST, PORT); });
  11013. auto se = detail::scope_exit([&] {
  11014. svr.stop();
  11015. t.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. ASSERT_TRUE(handled);
  11018. });
  11019. svr.wait_until_ready();
  11020. auto req = "POST /test HTTP/1.1\r\n"
  11021. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11022. "Content-Length: 146\r\n"
  11023. "\r\n----------\r\n"
  11024. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11025. "\r\n"
  11026. "text1"
  11027. "\r\n----------\r\n"
  11028. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11029. "\r\n"
  11030. "text2"
  11031. "\r\n------------";
  11032. std::string response;
  11033. ASSERT_TRUE(send_request(1, req, &response));
  11034. ASSERT_EQ("200", response.substr(9, 3));
  11035. }
  11036. TEST(MultipartFormDataTest, ContentLength) {
  11037. auto handled = false;
  11038. Server svr;
  11039. svr.Post("/test", [&](const Request &req, Response &) {
  11040. ASSERT_EQ(2u, req.form.fields.size());
  11041. const auto &text1 = req.form.get_field("text1");
  11042. ASSERT_EQ("text1", text1);
  11043. const auto &text2 = req.form.get_field("text2");
  11044. ASSERT_EQ("text2", text2);
  11045. handled = true;
  11046. });
  11047. thread t = thread([&] { svr.listen(HOST, PORT); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. t.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. ASSERT_TRUE(handled);
  11053. });
  11054. svr.wait_until_ready();
  11055. auto req = "POST /test HTTP/1.1\r\n"
  11056. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11057. "Content-Length: 167\r\n"
  11058. "\r\n----------\r\n"
  11059. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11060. "Content-Length: 5\r\n"
  11061. "\r\n"
  11062. "text1"
  11063. "\r\n----------\r\n"
  11064. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11065. "\r\n"
  11066. "text2"
  11067. "\r\n------------\r\n";
  11068. std::string response;
  11069. ASSERT_TRUE(send_request(1, req, &response));
  11070. ASSERT_EQ("200", response.substr(9, 3));
  11071. }
  11072. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11073. auto handled = false;
  11074. Server svr;
  11075. svr.Post("/test", [&](const Request &req, Response &) {
  11076. ASSERT_EQ(2u, req.form.fields.size());
  11077. const auto &text1 = req.form.get_field("text1");
  11078. ASSERT_EQ("text1", text1);
  11079. // TODO: Add header access for text fields if needed
  11080. const auto &text2 = req.form.get_field("text2");
  11081. ASSERT_EQ("text2", text2);
  11082. // TODO: Header access for text fields needs to be implemented
  11083. // auto &headers = it->second.headers;
  11084. // ASSERT_EQ(3U, headers.size());
  11085. // auto custom_header = headers.find("x-whatever");
  11086. // ASSERT_TRUE(custom_header != headers.end());
  11087. // ASSERT_NE("customvalue", custom_header->second);
  11088. // ASSERT_EQ("CustomValue", custom_header->second);
  11089. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11090. handled = true;
  11091. });
  11092. thread t = thread([&] { svr.listen(HOST, PORT); });
  11093. auto se = detail::scope_exit([&] {
  11094. svr.stop();
  11095. t.join();
  11096. ASSERT_FALSE(svr.is_running());
  11097. ASSERT_TRUE(handled);
  11098. });
  11099. svr.wait_until_ready();
  11100. auto req = "POST /test HTTP/1.1\r\n"
  11101. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11102. "Content-Length: 232\r\n"
  11103. "\r\n----------\r\n"
  11104. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11105. "Content-Length: 5\r\n"
  11106. "X-Test: 1\r\n"
  11107. "\r\n"
  11108. "text1"
  11109. "\r\n----------\r\n"
  11110. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11111. "Content-Type: text/plain\r\n"
  11112. "X-Whatever: CustomValue\r\n"
  11113. "\r\n"
  11114. "text2"
  11115. "\r\n------------\r\n"
  11116. "That should be disregarded. Not even read";
  11117. std::string response;
  11118. ASSERT_TRUE(send_request(1, req, &response));
  11119. ASSERT_EQ("200", response.substr(9, 3));
  11120. }
  11121. TEST(MultipartFormDataTest, LargeHeader) {
  11122. auto handled = false;
  11123. Server svr;
  11124. svr.Post("/test", [&](const Request &req, Response &) {
  11125. ASSERT_EQ(1u, req.form.fields.size());
  11126. const auto &text = req.form.get_field("name1");
  11127. ASSERT_EQ("text1", text);
  11128. handled = true;
  11129. });
  11130. thread t = thread([&] { svr.listen(HOST, PORT); });
  11131. auto se = detail::scope_exit([&] {
  11132. svr.stop();
  11133. t.join();
  11134. ASSERT_FALSE(svr.is_running());
  11135. ASSERT_TRUE(handled);
  11136. });
  11137. svr.wait_until_ready();
  11138. auto boundary = std::string("cpp-httplib-multipart-data");
  11139. std::string content = "--" + boundary +
  11140. "\r\n"
  11141. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11142. "\r\n"
  11143. "text1\r\n"
  11144. "--" +
  11145. boundary + "--\r\n";
  11146. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11147. "Content-Type: multipart/form-data;boundary=" +
  11148. boundary +
  11149. "\r\n"
  11150. "Content-Length: " +
  11151. std::to_string(content.size()) +
  11152. "\r\n"
  11153. "Dummy-Header: ";
  11154. std::string header_suffix = "\r\n"
  11155. "\r\n";
  11156. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11157. size_t header_dummy_size =
  11158. read_buff_size -
  11159. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11160. auto header_dummy = std::string(header_dummy_size, '@');
  11161. auto req = header_prefix + header_dummy + header_suffix + content;
  11162. std::string response;
  11163. ASSERT_TRUE(send_request(1, req, &response));
  11164. ASSERT_EQ("200", response.substr(9, 3));
  11165. }
  11166. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11167. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11168. // (not chunked Transfer-Encoding) after the streaming refactor.
  11169. auto handled = false;
  11170. Server svr;
  11171. svr.Post("/upload", [&](const Request &req, Response &res) {
  11172. auto cl_it = req.headers.find("Content-Length");
  11173. EXPECT_TRUE(cl_it != req.headers.end());
  11174. auto te_it = req.headers.find("Transfer-Encoding");
  11175. EXPECT_TRUE(te_it == req.headers.end());
  11176. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11177. res.set_content("ok", "text/plain");
  11178. handled = true;
  11179. });
  11180. auto port = svr.bind_to_any_port(HOST);
  11181. auto t = thread([&] { svr.listen_after_bind(); });
  11182. auto se = detail::scope_exit([&] {
  11183. svr.stop();
  11184. t.join();
  11185. ASSERT_FALSE(svr.is_running());
  11186. ASSERT_TRUE(handled);
  11187. });
  11188. svr.wait_until_ready();
  11189. UploadFormDataItems items = {
  11190. {"field1", "hello", "", "text/plain"},
  11191. {"file1", "world", "test.txt", "application/octet-stream"},
  11192. };
  11193. Client cli(HOST, port);
  11194. auto res = cli.Post("/upload", {}, items);
  11195. ASSERT_TRUE(res);
  11196. EXPECT_EQ(StatusCode::OK_200, res->status);
  11197. }
  11198. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11199. // Verify that make_multipart_content_provider coalesces many small segments
  11200. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11201. constexpr size_t kItemCount = 1000;
  11202. UploadFormDataItems items;
  11203. items.reserve(kItemCount);
  11204. for (size_t i = 0; i < kItemCount; i++) {
  11205. items.push_back(
  11206. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11207. }
  11208. const std::string boundary = "----test-boundary";
  11209. auto content_length = detail::get_multipart_content_length(items, boundary);
  11210. auto provider = detail::make_multipart_content_provider(items, boundary);
  11211. // Drive the provider the same way write_content_with_progress does
  11212. size_t write_count = 0;
  11213. size_t total_bytes = 0;
  11214. DataSink sink;
  11215. size_t offset = 0;
  11216. sink.write = [&](const char *d, size_t l) -> bool {
  11217. (void)d;
  11218. write_count++;
  11219. total_bytes += l;
  11220. offset += l;
  11221. return true;
  11222. };
  11223. sink.is_writable = []() -> bool { return true; };
  11224. while (offset < content_length) {
  11225. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11226. }
  11227. EXPECT_EQ(content_length, total_bytes);
  11228. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11229. // With buffering into 64KB blocks, write_count should be much smaller.
  11230. auto segment_count = 3 * kItemCount + 1;
  11231. EXPECT_LT(write_count, segment_count / 10);
  11232. }
  11233. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11234. // Integration test: send many UploadFormDataItems and verify the server
  11235. // receives all of them correctly (#2410).
  11236. constexpr size_t kItemCount = 500;
  11237. auto handled = false;
  11238. Server svr;
  11239. svr.Post("/upload", [&](const Request &req, Response &res) {
  11240. EXPECT_EQ(kItemCount, req.form.fields.size());
  11241. for (size_t i = 0; i < kItemCount; i++) {
  11242. auto key = "field" + std::to_string(i);
  11243. auto val = "value" + std::to_string(i);
  11244. auto it = req.form.fields.find(key);
  11245. if (it != req.form.fields.end()) {
  11246. EXPECT_EQ(val, it->second.content);
  11247. } else {
  11248. ADD_FAILURE() << "Missing field: " << key;
  11249. }
  11250. }
  11251. res.set_content("ok", "text/plain");
  11252. handled = true;
  11253. });
  11254. auto port = svr.bind_to_any_port(HOST);
  11255. auto t = thread([&] { svr.listen_after_bind(); });
  11256. auto se = detail::scope_exit([&] {
  11257. svr.stop();
  11258. t.join();
  11259. ASSERT_FALSE(svr.is_running());
  11260. ASSERT_TRUE(handled);
  11261. });
  11262. svr.wait_until_ready();
  11263. UploadFormDataItems items;
  11264. items.reserve(kItemCount);
  11265. for (size_t i = 0; i < kItemCount; i++) {
  11266. items.push_back(
  11267. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11268. }
  11269. Client cli(HOST, port);
  11270. auto res = cli.Post("/upload", items);
  11271. ASSERT_TRUE(res);
  11272. EXPECT_EQ(StatusCode::OK_200, res->status);
  11273. }
  11274. TEST(MultipartFormDataTest, MakeFileProvider) {
  11275. // Verify make_file_provider sends a file's contents correctly.
  11276. const std::string file_content(4096, 'Z');
  11277. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11278. {
  11279. std::ofstream ofs(tmp_path, std::ios::binary);
  11280. ofs.write(file_content.data(),
  11281. static_cast<std::streamsize>(file_content.size()));
  11282. }
  11283. auto handled = false;
  11284. Server svr;
  11285. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11286. const ContentReader &content_reader) {
  11287. ASSERT_TRUE(req.is_multipart_form_data());
  11288. std::vector<FormData> items;
  11289. content_reader(
  11290. [&](const FormData &file) {
  11291. items.push_back(file);
  11292. return true;
  11293. },
  11294. [&](const char *data, size_t data_length) {
  11295. items.back().content.append(data, data_length);
  11296. return true;
  11297. });
  11298. ASSERT_EQ(1u, items.size());
  11299. EXPECT_EQ("myfile", items[0].name);
  11300. EXPECT_EQ("data.bin", items[0].filename);
  11301. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11302. EXPECT_EQ(file_content, items[0].content);
  11303. handled = true;
  11304. });
  11305. auto port = svr.bind_to_any_port(HOST);
  11306. auto t = thread([&] { svr.listen_after_bind(); });
  11307. auto se = detail::scope_exit([&] {
  11308. svr.stop();
  11309. t.join();
  11310. ASSERT_FALSE(svr.is_running());
  11311. ASSERT_TRUE(handled);
  11312. std::remove(tmp_path.c_str());
  11313. });
  11314. svr.wait_until_ready();
  11315. FormDataProviderItems providers;
  11316. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11317. "application/octet-stream"));
  11318. Client cli(HOST, port);
  11319. auto res = cli.Post("/upload", {}, {}, providers);
  11320. ASSERT_TRUE(res);
  11321. EXPECT_EQ(StatusCode::OK_200, res->status);
  11322. }
  11323. TEST(MakeFileBodyTest, Basic) {
  11324. const std::string file_content(4096, 'Z');
  11325. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11326. {
  11327. std::ofstream ofs(tmp_path, std::ios::binary);
  11328. ofs.write(file_content.data(),
  11329. static_cast<std::streamsize>(file_content.size()));
  11330. }
  11331. auto handled = false;
  11332. Server svr;
  11333. svr.Post("/upload", [&](const Request &req, Response &res) {
  11334. EXPECT_EQ(file_content, req.body);
  11335. handled = true;
  11336. res.status = StatusCode::OK_200;
  11337. });
  11338. auto port = svr.bind_to_any_port(HOST);
  11339. auto t = thread([&] { svr.listen_after_bind(); });
  11340. auto se = detail::scope_exit([&] {
  11341. svr.stop();
  11342. t.join();
  11343. ASSERT_FALSE(svr.is_running());
  11344. ASSERT_TRUE(handled);
  11345. std::remove(tmp_path.c_str());
  11346. });
  11347. svr.wait_until_ready();
  11348. auto fb = make_file_body(tmp_path);
  11349. ASSERT_GT(fb.first, 0u);
  11350. Client cli(HOST, port);
  11351. auto res =
  11352. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11353. ASSERT_TRUE(res);
  11354. EXPECT_EQ(StatusCode::OK_200, res->status);
  11355. }
  11356. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11357. static constexpr unsigned int number_of_tasks{1000000};
  11358. std::atomic_uint count{0};
  11359. std::unique_ptr<TaskQueue> task_queue{
  11360. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11361. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11362. auto queued = task_queue->enqueue(
  11363. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11364. EXPECT_TRUE(queued);
  11365. }
  11366. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11367. task_queue->shutdown();
  11368. #else
  11369. EXPECT_NO_THROW(task_queue->shutdown());
  11370. #endif
  11371. EXPECT_EQ(number_of_tasks, count.load());
  11372. }
  11373. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11374. static constexpr unsigned int number_of_tasks{1000000};
  11375. static constexpr unsigned int qlimit{2};
  11376. unsigned int queued_count{0};
  11377. std::atomic_uint count{0};
  11378. std::unique_ptr<TaskQueue> task_queue{
  11379. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11380. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11381. if (task_queue->enqueue(
  11382. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11383. queued_count++;
  11384. }
  11385. }
  11386. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11387. task_queue->shutdown();
  11388. #else
  11389. EXPECT_NO_THROW(task_queue->shutdown());
  11390. #endif
  11391. EXPECT_EQ(queued_count, count.load());
  11392. EXPECT_TRUE(queued_count <= number_of_tasks);
  11393. EXPECT_TRUE(queued_count >= qlimit);
  11394. }
  11395. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11396. // Use a short idle timeout so a dynamic thread spawns, times out and
  11397. // exits during the test, and the pool keeps working afterwards.
  11398. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11399. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11400. /*idle_timeout_sec=*/1}};
  11401. std::atomic_uint count{0};
  11402. std::condition_variable cv;
  11403. std::mutex mtx;
  11404. bool release = false;
  11405. // Block the base thread so the second task spawns a dynamic thread.
  11406. EXPECT_TRUE(task_queue->enqueue([&] {
  11407. std::unique_lock<std::mutex> lock(mtx);
  11408. while (!release) {
  11409. cv.wait(lock);
  11410. }
  11411. count++;
  11412. }));
  11413. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11414. // Let the dynamic thread finish its task and exceed the idle timeout.
  11415. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11416. {
  11417. std::unique_lock<std::mutex> lock(mtx);
  11418. release = true;
  11419. }
  11420. cv.notify_all();
  11421. // The pool must still accept and run tasks after the dynamic thread exited.
  11422. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11423. task_queue->shutdown();
  11424. EXPECT_EQ(3u, count.load());
  11425. }
  11426. TEST(TaskQueueTest, MaxQueuedRequests) {
  11427. static constexpr unsigned int qlimit{3};
  11428. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11429. std::condition_variable sem_cv;
  11430. std::mutex sem_mtx;
  11431. int credits = 0;
  11432. bool queued;
  11433. /* Fill up the queue with tasks that will block until we give them credits to
  11434. * complete. */
  11435. for (unsigned int n = 0; n <= qlimit;) {
  11436. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11437. std::unique_lock<std::mutex> lock(sem_mtx);
  11438. while (credits <= 0) {
  11439. sem_cv.wait(lock);
  11440. }
  11441. /* Consume the credit and signal the test code if they are all gone. */
  11442. if (--credits == 0) { sem_cv.notify_one(); }
  11443. });
  11444. if (n < qlimit) {
  11445. /* The first qlimit enqueues must succeed. */
  11446. EXPECT_TRUE(queued);
  11447. } else {
  11448. /* The last one will succeed only when the worker thread
  11449. * starts and dequeues the first blocking task. Although
  11450. * not necessary for the correctness of this test, we sleep for
  11451. * a short while to avoid busy waiting. */
  11452. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11453. }
  11454. if (queued) { n++; }
  11455. }
  11456. /* Further enqueues must fail since the queue is full. */
  11457. for (auto i = 0; i < 4; i++) {
  11458. queued = task_queue->enqueue([] {});
  11459. EXPECT_FALSE(queued);
  11460. }
  11461. /* Give the credits to allow the previous tasks to complete. */
  11462. {
  11463. std::unique_lock<std::mutex> lock(sem_mtx);
  11464. credits += qlimit + 1;
  11465. }
  11466. sem_cv.notify_all();
  11467. /* Wait for all the credits to be consumed. */
  11468. {
  11469. std::unique_lock<std::mutex> lock(sem_mtx);
  11470. while (credits > 0) {
  11471. sem_cv.wait(lock);
  11472. }
  11473. }
  11474. /* Check that we are able again to enqueue at least qlimit tasks. */
  11475. for (unsigned int i = 0; i < qlimit; i++) {
  11476. queued = task_queue->enqueue([] {});
  11477. EXPECT_TRUE(queued);
  11478. }
  11479. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11480. task_queue->shutdown();
  11481. #else
  11482. EXPECT_NO_THROW(task_queue->shutdown());
  11483. #endif
  11484. }
  11485. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11486. Server svr;
  11487. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11488. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11489. });
  11490. svr.Get("/hello", [](const Request &req, Response &res) {
  11491. res.set_content(req.get_param_value("key"), "text/plain");
  11492. });
  11493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11494. auto se = detail::scope_exit([&] {
  11495. svr.stop();
  11496. thread.join();
  11497. ASSERT_FALSE(svr.is_running());
  11498. });
  11499. svr.wait_until_ready();
  11500. {
  11501. Client cli(HOST, PORT);
  11502. cli.set_follow_location(true);
  11503. auto res = cli.Get("/");
  11504. ASSERT_TRUE(res);
  11505. EXPECT_EQ(StatusCode::OK_200, res->status);
  11506. EXPECT_EQ("val&key2=val2", res->body);
  11507. }
  11508. }
  11509. #endif
  11510. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11511. Server svr;
  11512. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11513. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11514. });
  11515. svr.Get("/hello", [](const Request &req, Response &res) {
  11516. res.set_content(req.get_param_value("key"), "text/plain");
  11517. });
  11518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11519. auto se = detail::scope_exit([&] {
  11520. svr.stop();
  11521. thread.join();
  11522. ASSERT_FALSE(svr.is_running());
  11523. });
  11524. svr.wait_until_ready();
  11525. {
  11526. Client cli(HOST, PORT);
  11527. cli.set_follow_location(true);
  11528. auto res = cli.Get("/");
  11529. ASSERT_TRUE(res);
  11530. EXPECT_EQ(StatusCode::OK_200, res->status);
  11531. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11532. }
  11533. }
  11534. TEST(RedirectTest, RedirectWithPlusInPath) {
  11535. Server svr;
  11536. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11537. res.set_redirect("/a+b");
  11538. });
  11539. // Route pattern uses regex; escape + as \\+
  11540. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11541. res.set_content(req.path, "text/plain");
  11542. });
  11543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. {
  11551. Client cli(HOST, PORT);
  11552. cli.set_follow_location(true);
  11553. auto res = cli.Get("/");
  11554. ASSERT_TRUE(res);
  11555. EXPECT_EQ(StatusCode::OK_200, res->status);
  11556. EXPECT_EQ("/a+b", res->body);
  11557. }
  11558. }
  11559. #ifdef CPPHTTPLIB_SSL_ENABLED
  11560. TEST(RedirectTest, Issue2185_Online) {
  11561. SSLClient client("github.com");
  11562. client.set_follow_location(true);
  11563. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11564. "Coollab-Windows.zip");
  11565. ASSERT_TRUE(res);
  11566. EXPECT_EQ(StatusCode::OK_200, res->status);
  11567. EXPECT_EQ(9920427U, res->body.size());
  11568. }
  11569. #endif
  11570. TEST(VulnerabilityTest, CRLFInjection) {
  11571. Server svr;
  11572. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11573. res.set_content("Hello 1", "text/plain");
  11574. });
  11575. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11576. res.set_content("Hello 2", "text/plain");
  11577. });
  11578. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11579. res.set_content("Hello 3", "text/plain");
  11580. });
  11581. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11582. res.set_content("Hello 4", "text/plain");
  11583. });
  11584. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11585. for (const auto &x : req.headers) {
  11586. auto key = x.first;
  11587. EXPECT_STRNE("evil", key.c_str());
  11588. }
  11589. });
  11590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11591. auto se = detail::scope_exit([&] {
  11592. svr.stop();
  11593. thread.join();
  11594. ASSERT_FALSE(svr.is_running());
  11595. });
  11596. svr.wait_until_ready();
  11597. {
  11598. Client cli(HOST, PORT);
  11599. cli.Post("/test1", "A=B",
  11600. "application/x-www-form-urlencoded\r\nevil: hello1");
  11601. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11602. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11603. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11604. }
  11605. }
  11606. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11607. auto server_thread = std::thread([] {
  11608. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11609. default_socket_options(srv);
  11610. sockaddr_in addr{};
  11611. addr.sin_family = AF_INET;
  11612. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11613. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11614. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11615. ::listen(srv, 1);
  11616. sockaddr_in cli_addr{};
  11617. socklen_t cli_len = sizeof(cli_addr);
  11618. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11619. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11620. std::string buf_all;
  11621. char buf[2048];
  11622. ssize_t n;
  11623. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11624. buf_all.append(buf, static_cast<size_t>(n));
  11625. size_t pos;
  11626. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11627. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11628. auto e = request_block.find("\r\n");
  11629. if (e != std::string::npos) {
  11630. auto request_line = request_block.substr(0, e);
  11631. std::string msg =
  11632. "CRLF injection detected in request line: '" + request_line + "'";
  11633. EXPECT_FALSE(true) << msg;
  11634. }
  11635. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11636. ::send(cli,
  11637. #ifdef _WIN32
  11638. static_cast<const char *>(resp.c_str()),
  11639. static_cast<int>(resp.size()),
  11640. #else
  11641. resp.c_str(), resp.size(),
  11642. #endif
  11643. 0);
  11644. buf_all.erase(0, pos + 4);
  11645. }
  11646. }
  11647. detail::close_socket(cli);
  11648. detail::close_socket(srv);
  11649. });
  11650. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11651. auto cli = Client("127.0.0.1", PORT + 1);
  11652. auto headers = Headers{
  11653. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11654. {"Connection", "keep-alive"}};
  11655. auto res = cli.Get("/hi", headers);
  11656. EXPECT_FALSE(res);
  11657. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11658. server_thread.join();
  11659. }
  11660. TEST(PathParamsTest, StaticMatch) {
  11661. const auto pattern = "/users/all";
  11662. detail::PathParamsMatcher matcher(pattern);
  11663. Request request;
  11664. request.path = "/users/all";
  11665. ASSERT_TRUE(matcher.match(request));
  11666. std::unordered_map<std::string, std::string> expected_params = {};
  11667. EXPECT_EQ(request.path_params, expected_params);
  11668. }
  11669. TEST(PathParamsTest, StaticMismatch) {
  11670. const auto pattern = "/users/all";
  11671. detail::PathParamsMatcher matcher(pattern);
  11672. Request request;
  11673. request.path = "/users/1";
  11674. ASSERT_FALSE(matcher.match(request));
  11675. }
  11676. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11677. const auto pattern = "/users/:id/subscriptions";
  11678. detail::PathParamsMatcher matcher(pattern);
  11679. Request request;
  11680. request.path = "/users/42/subscriptions";
  11681. ASSERT_TRUE(matcher.match(request));
  11682. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11683. EXPECT_EQ(request.path_params, expected_params);
  11684. }
  11685. TEST(PathParamsTest, SingleParamInTheEnd) {
  11686. const auto pattern = "/users/:id";
  11687. detail::PathParamsMatcher matcher(pattern);
  11688. Request request;
  11689. request.path = "/users/24";
  11690. ASSERT_TRUE(matcher.match(request));
  11691. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11692. EXPECT_EQ(request.path_params, expected_params);
  11693. }
  11694. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11695. const auto pattern = "/users/:id/";
  11696. detail::PathParamsMatcher matcher(pattern);
  11697. Request request;
  11698. request.path = "/users/42/";
  11699. ASSERT_TRUE(matcher.match(request));
  11700. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11701. EXPECT_EQ(request.path_params, expected_params);
  11702. }
  11703. TEST(PathParamsTest, EmptyParam) {
  11704. const auto pattern = "/users/:id/";
  11705. detail::PathParamsMatcher matcher(pattern);
  11706. Request request;
  11707. request.path = "/users//";
  11708. ASSERT_TRUE(matcher.match(request));
  11709. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11710. EXPECT_EQ(request.path_params, expected_params);
  11711. }
  11712. TEST(PathParamsTest, FragmentMismatch) {
  11713. const auto pattern = "/users/:id/";
  11714. detail::PathParamsMatcher matcher(pattern);
  11715. Request request;
  11716. request.path = "/admins/24/";
  11717. ASSERT_FALSE(matcher.match(request));
  11718. }
  11719. TEST(PathParamsTest, ExtraFragments) {
  11720. const auto pattern = "/users/:id";
  11721. detail::PathParamsMatcher matcher(pattern);
  11722. Request request;
  11723. request.path = "/users/42/subscriptions";
  11724. ASSERT_FALSE(matcher.match(request));
  11725. }
  11726. TEST(PathParamsTest, MissingTrailingParam) {
  11727. const auto pattern = "/users/:id";
  11728. detail::PathParamsMatcher matcher(pattern);
  11729. Request request;
  11730. request.path = "/users";
  11731. ASSERT_FALSE(matcher.match(request));
  11732. }
  11733. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11734. const auto pattern = "/users/:id/subscriptions";
  11735. detail::PathParamsMatcher matcher(pattern);
  11736. Request request;
  11737. request.path = "/users/subscriptions";
  11738. ASSERT_FALSE(matcher.match(request));
  11739. }
  11740. TEST(PathParamsTest, MultipleParams) {
  11741. const auto pattern = "/users/:userid/subscriptions/:subid";
  11742. detail::PathParamsMatcher matcher(pattern);
  11743. Request request;
  11744. request.path = "/users/42/subscriptions/2";
  11745. ASSERT_TRUE(matcher.match(request));
  11746. std::unordered_map<std::string, std::string> expected_params = {
  11747. {"userid", "42"}, {"subid", "2"}};
  11748. EXPECT_EQ(request.path_params, expected_params);
  11749. }
  11750. TEST(PathParamsTest, SequenceOfParams) {
  11751. const auto pattern = "/values/:x/:y/:z";
  11752. detail::PathParamsMatcher matcher(pattern);
  11753. Request request;
  11754. request.path = "/values/1/2/3";
  11755. ASSERT_TRUE(matcher.match(request));
  11756. std::unordered_map<std::string, std::string> expected_params = {
  11757. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11758. EXPECT_EQ(request.path_params, expected_params);
  11759. }
  11760. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11761. const auto pattern = "/prefix:suffix";
  11762. detail::PathParamsMatcher matcher(pattern);
  11763. Request request;
  11764. request.path = "/prefix:suffix";
  11765. ASSERT_TRUE(matcher.match(request));
  11766. const std::unordered_map<std::string, std::string> expected_params = {};
  11767. EXPECT_EQ(request.path_params, expected_params);
  11768. }
  11769. TEST(ParseUrlTest, VariousPatterns) {
  11770. {
  11771. detail::UrlComponents uc;
  11772. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11773. EXPECT_EQ("http", uc.scheme);
  11774. EXPECT_EQ("example.com", uc.host);
  11775. EXPECT_EQ("8080", uc.port);
  11776. EXPECT_EQ("/path", uc.path);
  11777. EXPECT_EQ("?q=1", uc.query);
  11778. }
  11779. {
  11780. detail::UrlComponents uc;
  11781. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11782. EXPECT_EQ("https", uc.scheme);
  11783. EXPECT_EQ("example.com", uc.host);
  11784. EXPECT_TRUE(uc.port.empty());
  11785. EXPECT_EQ("/path", uc.path);
  11786. }
  11787. {
  11788. detail::UrlComponents uc;
  11789. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11790. EXPECT_EQ("::1", uc.host);
  11791. EXPECT_EQ("8080", uc.port);
  11792. EXPECT_EQ("/path", uc.path);
  11793. }
  11794. {
  11795. detail::UrlComponents uc;
  11796. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11797. }
  11798. {
  11799. detail::UrlComponents uc;
  11800. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11801. EXPECT_TRUE(uc.scheme.empty());
  11802. EXPECT_EQ("example.com", uc.host);
  11803. EXPECT_EQ("/path", uc.path);
  11804. EXPECT_EQ("?q=1", uc.query);
  11805. }
  11806. {
  11807. detail::UrlComponents uc;
  11808. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11809. EXPECT_TRUE(uc.host.empty());
  11810. EXPECT_EQ("/path", uc.path);
  11811. EXPECT_EQ("?q=1", uc.query);
  11812. }
  11813. {
  11814. detail::UrlComponents uc;
  11815. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11816. EXPECT_EQ("example.com", uc.host);
  11817. EXPECT_EQ("8080", uc.port);
  11818. }
  11819. {
  11820. // Unix socket path — must not be parsed as host
  11821. detail::UrlComponents uc;
  11822. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11823. EXPECT_TRUE(uc.host.empty());
  11824. }
  11825. {
  11826. detail::UrlComponents uc;
  11827. ASSERT_TRUE(detail::parse_url("", uc));
  11828. EXPECT_TRUE(uc.host.empty());
  11829. EXPECT_TRUE(uc.path.empty());
  11830. }
  11831. {
  11832. detail::UrlComponents uc;
  11833. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11834. }
  11835. {
  11836. detail::UrlComponents uc;
  11837. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11838. }
  11839. {
  11840. // Accepted by parse_url; callers restrict to http/https
  11841. detail::UrlComponents uc;
  11842. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11843. EXPECT_EQ("ftp", uc.scheme);
  11844. }
  11845. {
  11846. detail::UrlComponents uc;
  11847. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11848. }
  11849. {
  11850. detail::UrlComponents uc;
  11851. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11852. }
  11853. }
  11854. TEST(ParseUrlTest, FragmentHandling) {
  11855. {
  11856. detail::UrlComponents uc;
  11857. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11858. EXPECT_EQ("/path", uc.path);
  11859. EXPECT_TRUE(uc.query.empty());
  11860. }
  11861. {
  11862. detail::UrlComponents uc;
  11863. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11864. EXPECT_TRUE(uc.path.empty());
  11865. EXPECT_TRUE(uc.query.empty());
  11866. }
  11867. }
  11868. TEST(ParseUrlTest, UserinfoHandling) {
  11869. // Userinfo with @ but no colon — host includes @
  11870. detail::UrlComponents uc;
  11871. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11872. EXPECT_EQ("user@host.com", uc.host);
  11873. EXPECT_EQ("/path", uc.path);
  11874. }
  11875. TEST(ParseUrlTest, IPv6EdgeCases) {
  11876. {
  11877. detail::UrlComponents uc;
  11878. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11879. EXPECT_TRUE(uc.scheme.empty());
  11880. EXPECT_EQ("::1", uc.host);
  11881. EXPECT_EQ("8080", uc.port);
  11882. }
  11883. {
  11884. // Zone ID '%25' is not in [a-fA-F0-9:]
  11885. detail::UrlComponents uc;
  11886. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11887. }
  11888. }
  11889. TEST(ParseUrlTest, SchemeEdgeCases) {
  11890. {
  11891. detail::UrlComponents uc;
  11892. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11893. }
  11894. {
  11895. detail::UrlComponents uc;
  11896. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11897. }
  11898. {
  11899. detail::UrlComponents uc;
  11900. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11901. }
  11902. }
  11903. TEST(ParseUrlTest, PortEdgeCases) {
  11904. {
  11905. detail::UrlComponents uc;
  11906. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11907. EXPECT_TRUE(uc.port.empty());
  11908. EXPECT_EQ("/path", uc.path);
  11909. }
  11910. {
  11911. // parse_url accepts any port string; validation is done by parse_port
  11912. detail::UrlComponents uc;
  11913. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11914. EXPECT_EQ("abc", uc.port);
  11915. }
  11916. }
  11917. TEST(ParseUrlTest, WebSocketPatterns) {
  11918. {
  11919. detail::UrlComponents uc;
  11920. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11921. EXPECT_EQ("ws", uc.scheme);
  11922. EXPECT_EQ("echo.example.com", uc.host);
  11923. EXPECT_EQ("8080", uc.port);
  11924. EXPECT_EQ("/ws", uc.path);
  11925. }
  11926. {
  11927. detail::UrlComponents uc;
  11928. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11929. EXPECT_EQ("wss", uc.scheme);
  11930. EXPECT_EQ("echo.example.com", uc.host);
  11931. EXPECT_TRUE(uc.port.empty());
  11932. EXPECT_EQ("/ws", uc.path);
  11933. }
  11934. }
  11935. TEST(ParseUrlTest, QueryOnly) {
  11936. detail::UrlComponents uc;
  11937. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11938. EXPECT_TRUE(uc.host.empty());
  11939. EXPECT_TRUE(uc.path.empty());
  11940. EXPECT_EQ("?q=1&r=2", uc.query);
  11941. }
  11942. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11943. detail::UrlComponents uc;
  11944. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11945. EXPECT_TRUE(uc.scheme.empty());
  11946. EXPECT_EQ("example.com", uc.host);
  11947. EXPECT_EQ("443", uc.port);
  11948. EXPECT_EQ("/path", uc.path);
  11949. }
  11950. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11951. // If ipv6 regex working, regex match codepath is taken.
  11952. // else port will default to 80 in Client impl
  11953. int clientImplMagicPort = 80;
  11954. int port = 4321;
  11955. // above ports must be different to avoid false negative
  11956. EXPECT_NE(clientImplMagicPort, port);
  11957. std::string ipV6TestURL = "http://[ff06::c3]";
  11958. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11959. CLIENT_PRIVATE_KEY_FILE);
  11960. EXPECT_EQ(cli.port(), port);
  11961. }
  11962. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11963. auto file_path = "./www/dir/index.html";
  11964. auto dir_path = "./www/dir";
  11965. detail::FileStat stat_file(file_path);
  11966. EXPECT_TRUE(stat_file.is_file());
  11967. EXPECT_FALSE(stat_file.is_dir());
  11968. detail::FileStat stat_dir(dir_path);
  11969. EXPECT_FALSE(stat_dir.is_file());
  11970. EXPECT_TRUE(stat_dir.is_dir());
  11971. }
  11972. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11973. // IPv4 with default HTTP port (80)
  11974. EXPECT_EQ("example.com",
  11975. detail::make_host_and_port_string("example.com", 80, false));
  11976. // IPv4 with default HTTPS port (443)
  11977. EXPECT_EQ("example.com",
  11978. detail::make_host_and_port_string("example.com", 443, true));
  11979. // IPv4 with non-default HTTP port
  11980. EXPECT_EQ("example.com:8080",
  11981. detail::make_host_and_port_string("example.com", 8080, false));
  11982. // IPv4 with non-default HTTPS port
  11983. EXPECT_EQ("example.com:8443",
  11984. detail::make_host_and_port_string("example.com", 8443, true));
  11985. // IPv6 with default HTTP port (80)
  11986. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11987. // IPv6 with default HTTPS port (443)
  11988. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11989. // IPv6 with non-default HTTP port
  11990. EXPECT_EQ("[::1]:8080",
  11991. detail::make_host_and_port_string("::1", 8080, false));
  11992. // IPv6 with non-default HTTPS port
  11993. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11994. // IPv6 full address with default port
  11995. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11996. detail::make_host_and_port_string(
  11997. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11998. // IPv6 full address with non-default port
  11999. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12000. detail::make_host_and_port_string(
  12001. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12002. // IPv6 localhost with non-default port
  12003. EXPECT_EQ("[::1]:3000",
  12004. detail::make_host_and_port_string("::1", 3000, false));
  12005. // IPv6 with zone ID (link-local address) with default port
  12006. EXPECT_EQ("[fe80::1%eth0]",
  12007. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12008. // IPv6 with zone ID (link-local address) with non-default port
  12009. EXPECT_EQ("[fe80::1%eth0]:8080",
  12010. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12011. // Edge case: Port 443 with is_ssl=false (should add port)
  12012. EXPECT_EQ("example.com:443",
  12013. detail::make_host_and_port_string("example.com", 443, false));
  12014. // Edge case: Port 80 with is_ssl=true (should add port)
  12015. EXPECT_EQ("example.com:80",
  12016. detail::make_host_and_port_string("example.com", 80, true));
  12017. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12018. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12019. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12020. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12021. // Security fix: Already bracketed IPv6 should not get double brackets
  12022. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12023. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12024. EXPECT_EQ("[::1]:8080",
  12025. detail::make_host_and_port_string("[::1]", 8080, false));
  12026. EXPECT_EQ("[2001:db8::1]:8080",
  12027. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12028. EXPECT_EQ("[fe80::1%eth0]",
  12029. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12030. EXPECT_EQ("[fe80::1%eth0]:8080",
  12031. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12032. // Edge case: Empty host (should return as-is)
  12033. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12034. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12035. // This is a known limitation but shouldn't crash
  12036. EXPECT_EQ("[host:name]",
  12037. detail::make_host_and_port_string("host:name", 80, false));
  12038. // Port number edge cases (no validation, but should not crash)
  12039. EXPECT_EQ("example.com:0",
  12040. detail::make_host_and_port_string("example.com", 0, false));
  12041. EXPECT_EQ("example.com:-1",
  12042. detail::make_host_and_port_string("example.com", -1, false));
  12043. EXPECT_EQ("example.com:65535",
  12044. detail::make_host_and_port_string("example.com", 65535, false));
  12045. EXPECT_EQ("example.com:65536",
  12046. detail::make_host_and_port_string("example.com", 65536, false));
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12050. httplib::SSLClient cli("roblox.com", 443);
  12051. cli.set_follow_location(true);
  12052. auto res = cli.Get("/");
  12053. ASSERT_TRUE(res);
  12054. EXPECT_EQ(StatusCode::OK_200, res->status);
  12055. }
  12056. #endif
  12057. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12058. Server svr;
  12059. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12060. EXPECT_EQ(res.status, 400);
  12061. });
  12062. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12063. auto se = detail::scope_exit([&] {
  12064. svr.stop();
  12065. thread.join();
  12066. ASSERT_FALSE(svr.is_running());
  12067. });
  12068. svr.wait_until_ready();
  12069. Client cli(HOST, PORT);
  12070. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12071. }
  12072. TEST(InvalidHeaderCharsTest, is_field_name) {
  12073. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12074. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12075. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12076. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12077. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12078. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12079. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12080. EXPECT_FALSE(detail::fields::is_field_name(""));
  12081. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12082. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12083. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12084. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12085. }
  12086. TEST(InvalidHeaderCharsTest, is_field_value) {
  12087. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12088. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12089. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12090. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12091. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12092. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12093. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12094. EXPECT_TRUE(detail::fields::is_field_value(""));
  12095. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12096. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12097. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12098. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12099. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12100. }
  12101. TEST(InvalidHeaderCharsTest, OnServer) {
  12102. Server svr;
  12103. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12104. std::string header = "Not Set";
  12105. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12106. res.set_header(header, "value");
  12107. res.set_content("Page Content Page Content", "text/plain");
  12108. });
  12109. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12110. std::string header = "Not Set";
  12111. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12112. res.set_header("X-Test", header);
  12113. res.set_content("Page Content Page Content", "text/plain");
  12114. });
  12115. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. thread.join();
  12119. ASSERT_FALSE(svr.is_running());
  12120. });
  12121. svr.wait_until_ready();
  12122. Client cli(HOST, PORT);
  12123. {
  12124. auto res = cli.Get(
  12125. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12126. ASSERT_TRUE(res);
  12127. EXPECT_EQ("Page Content Page Content", res->body);
  12128. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12129. }
  12130. {
  12131. auto res = cli.Get(
  12132. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12133. ASSERT_TRUE(res);
  12134. EXPECT_EQ("Page Content Page Content", res->body);
  12135. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12136. }
  12137. }
  12138. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12139. auto handled = false;
  12140. Server svr;
  12141. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12142. thread t = thread([&] { svr.listen(HOST, PORT); });
  12143. auto se = detail::scope_exit([&] {
  12144. svr.stop();
  12145. t.join();
  12146. ASSERT_FALSE(svr.is_running());
  12147. ASSERT_FALSE(handled);
  12148. });
  12149. svr.wait_until_ready();
  12150. auto req = "POST /test HTTP/1.1\r\n"
  12151. "Content-Length: x\r\n"
  12152. "\r\n";
  12153. std::string response;
  12154. ASSERT_TRUE(send_request(1, req, &response));
  12155. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12156. response.substr(0, response.find("\r\n")));
  12157. }
  12158. #ifndef _WIN32
  12159. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12160. static constexpr char reject[] = "Unauthorized";
  12161. static constexpr char accept[] = "Upload accepted";
  12162. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12163. Server svr;
  12164. svr.set_expect_100_continue_handler(
  12165. [](const Request & /*req*/, Response &res) {
  12166. res.status = StatusCode::Unauthorized_401;
  12167. res.set_content(reject, "text/plain");
  12168. return res.status;
  12169. });
  12170. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12171. res.set_content(accept, "text/plain");
  12172. });
  12173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12174. auto se = detail::scope_exit([&] {
  12175. svr.stop();
  12176. thread.join();
  12177. ASSERT_FALSE(svr.is_running());
  12178. });
  12179. svr.wait_until_ready();
  12180. {
  12181. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12182. curl_easy_init(), &curl_easy_cleanup};
  12183. ASSERT_NE(curl, nullptr);
  12184. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12185. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12186. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12187. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12188. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12189. &curl_slist_free_all};
  12190. ASSERT_NE(list, nullptr);
  12191. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12192. struct read_data {
  12193. size_t read_size;
  12194. size_t total_size;
  12195. } data = {0, total_size};
  12196. using read_callback_t =
  12197. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12198. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12199. void *userdata) -> size_t {
  12200. read_data *d = (read_data *)userdata;
  12201. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12202. std::fill_n(ptr, size * nmemb, 'A');
  12203. d->read_size += size * nmemb;
  12204. return size * nmemb;
  12205. };
  12206. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12207. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12208. std::vector<char> buffer;
  12209. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12210. using write_callback_t =
  12211. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12212. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12213. void *userdata) -> size_t {
  12214. std::vector<char> *buf = (std::vector<char> *)userdata;
  12215. buf->reserve(buf->size() + size * nmemb + 1);
  12216. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12217. return size * nmemb;
  12218. };
  12219. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12220. {
  12221. const auto res = curl_easy_perform(curl.get());
  12222. ASSERT_EQ(res, CURLE_OK);
  12223. }
  12224. {
  12225. auto response_code = long{};
  12226. const auto res =
  12227. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12228. ASSERT_EQ(res, CURLE_OK);
  12229. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12230. }
  12231. {
  12232. auto dl = curl_off_t{};
  12233. const auto res =
  12234. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12235. ASSERT_EQ(res, CURLE_OK);
  12236. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12237. }
  12238. {
  12239. buffer.push_back('\0');
  12240. ASSERT_STRCASEEQ(buffer.data(), reject);
  12241. }
  12242. }
  12243. }
  12244. #endif
  12245. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12246. // Regression test for #2458.
  12247. //
  12248. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12249. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12250. // ticket can make the client socket spuriously readable during the
  12251. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12252. // the client withholds the body and then blocks reading a response that never
  12253. // comes, failing with `Failed to read connection`.
  12254. //
  12255. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12256. // within the timeout. This raw OpenSSL server deliberately never sends
  12257. // `100 Continue`; the client must still deliver the body and receive 200.
  12258. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12259. signal(SIGPIPE, SIG_IGN);
  12260. const auto port = PORT + 4;
  12261. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12262. ASSERT_NE(srv, INVALID_SOCKET);
  12263. int opt = 1;
  12264. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12265. sockaddr_in addr{};
  12266. addr.sin_family = AF_INET;
  12267. addr.sin_port = htons(static_cast<uint16_t>(port));
  12268. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12269. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12270. ASSERT_EQ(0, ::listen(srv, 1));
  12271. std::atomic<size_t> server_body_bytes{0};
  12272. auto server_thread = std::thread([&] {
  12273. sockaddr_in cli_addr{};
  12274. socklen_t cli_len = sizeof(cli_addr);
  12275. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12276. if (cli == INVALID_SOCKET) { return; }
  12277. // Bound the lifetime of the server side so a buggy client (which never
  12278. // sends the body) cannot make this thread block forever on join.
  12279. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12280. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12281. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12282. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12283. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12284. SSL *ssl = SSL_new(ctx);
  12285. SSL_set_fd(ssl, static_cast<int>(cli));
  12286. if (SSL_accept(ssl) > 0) {
  12287. // Read the request headers. Reading here also flushes the TLS 1.3
  12288. // session tickets to the client. Deliberately do NOT send
  12289. // `100 Continue`.
  12290. std::string buf;
  12291. char tmp[1024];
  12292. while (buf.find("\r\n\r\n") == std::string::npos) {
  12293. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12294. if (n <= 0) { break; }
  12295. buf.append(tmp, static_cast<size_t>(n));
  12296. }
  12297. // A correct client sends the body now; count what arrives.
  12298. auto pos = buf.find("\r\n\r\n");
  12299. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12300. while (body < 4096) {
  12301. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12302. if (n <= 0) { break; }
  12303. body += static_cast<size_t>(n);
  12304. }
  12305. server_body_bytes = body;
  12306. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12307. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12308. SSL_shutdown(ssl);
  12309. }
  12310. SSL_free(ssl);
  12311. detail::close_socket(cli);
  12312. SSL_CTX_free(ctx);
  12313. });
  12314. auto se = detail::scope_exit([&] {
  12315. server_thread.join();
  12316. detail::close_socket(srv);
  12317. });
  12318. SSLClient cli("127.0.0.1", port);
  12319. cli.enable_server_certificate_verification(false);
  12320. cli.set_connection_timeout(5, 0);
  12321. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12322. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12323. std::string body(4096, 'A');
  12324. auto res = cli.Put("/api/test", body, "application/json");
  12325. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12326. EXPECT_EQ(StatusCode::OK_200, res->status);
  12327. EXPECT_EQ(body.size(), server_body_bytes.load());
  12328. }
  12329. #endif
  12330. template <typename S, typename C>
  12331. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12332. svr.Get("/stream", [&](const Request &, Response &res) {
  12333. auto data = new std::string("01234567890123456789");
  12334. res.set_content_provider(
  12335. data->size(), "text/plain",
  12336. [&, data](size_t offset, size_t length, DataSink &sink) {
  12337. const size_t DATA_CHUNK_SIZE = 4;
  12338. const auto &d = *data;
  12339. std::this_thread::sleep_for(std::chrono::seconds(1));
  12340. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12341. return true;
  12342. },
  12343. [data](bool success) {
  12344. EXPECT_FALSE(success);
  12345. delete data;
  12346. });
  12347. });
  12348. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12349. auto i = new size_t(0);
  12350. res.set_content_provider(
  12351. "text/plain",
  12352. [i](size_t, DataSink &sink) {
  12353. if (*i < 5) {
  12354. std::this_thread::sleep_for(std::chrono::seconds(1));
  12355. sink.write("abcd", 4);
  12356. (*i)++;
  12357. } else {
  12358. sink.done();
  12359. }
  12360. return true;
  12361. },
  12362. [i](bool success) {
  12363. EXPECT_FALSE(success);
  12364. delete i;
  12365. });
  12366. });
  12367. svr.Get("/chunked", [&](const Request &, Response &res) {
  12368. auto i = new size_t(0);
  12369. res.set_chunked_content_provider(
  12370. "text/plain",
  12371. [i](size_t, DataSink &sink) {
  12372. if (*i < 5) {
  12373. std::this_thread::sleep_for(std::chrono::seconds(1));
  12374. sink.os << "abcd";
  12375. (*i)++;
  12376. } else {
  12377. sink.done();
  12378. }
  12379. return true;
  12380. },
  12381. [i](bool success) {
  12382. EXPECT_FALSE(success);
  12383. delete i;
  12384. });
  12385. });
  12386. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. listen_thread.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12394. {
  12395. auto start = std::chrono::steady_clock::now();
  12396. auto res = cli.Get("/stream");
  12397. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12398. std::chrono::steady_clock::now() - start)
  12399. .count();
  12400. ASSERT_FALSE(res);
  12401. EXPECT_EQ(Error::Read, res.error());
  12402. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12403. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12404. }
  12405. {
  12406. auto start = std::chrono::steady_clock::now();
  12407. auto res = cli.Get("/stream_without_length");
  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. auto start = std::chrono::steady_clock::now();
  12418. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12419. EXPECT_EQ("abcd", string(data, data_length));
  12420. return true;
  12421. });
  12422. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12423. std::chrono::steady_clock::now() - start)
  12424. .count();
  12425. ASSERT_FALSE(res);
  12426. EXPECT_EQ(Error::Read, res.error());
  12427. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12428. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12429. }
  12430. }
  12431. TEST(MaxTimeoutTest, ContentStream) {
  12432. time_t timeout = 2000;
  12433. time_t threshold = 200;
  12434. Server svr;
  12435. Client cli("localhost", PORT);
  12436. max_timeout_test(svr, cli, timeout, threshold);
  12437. }
  12438. #ifdef CPPHTTPLIB_SSL_ENABLED
  12439. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12440. time_t timeout = 2000;
  12441. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12443. SSLClient cli("localhost", PORT);
  12444. cli.enable_server_certificate_verification(false);
  12445. max_timeout_test(svr, cli, timeout, threshold);
  12446. }
  12447. #endif
  12448. class EventDispatcher {
  12449. public:
  12450. EventDispatcher() {}
  12451. bool wait_event(DataSink *sink) {
  12452. unique_lock<mutex> lk(m_);
  12453. int id = id_;
  12454. // Wait with timeout to prevent hanging if client disconnects
  12455. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12456. [&] { return cid_ == id; })) {
  12457. return false; // Timeout occurred
  12458. }
  12459. sink->write(message_.data(), message_.size());
  12460. return true;
  12461. }
  12462. void send_event(const string &message) {
  12463. lock_guard<mutex> lk(m_);
  12464. cid_ = id_++;
  12465. message_ = message;
  12466. cv_.notify_all();
  12467. }
  12468. private:
  12469. mutex m_;
  12470. condition_variable cv_;
  12471. atomic_int id_{0};
  12472. atomic_int cid_{-1};
  12473. string message_;
  12474. };
  12475. TEST(ClientInThreadTest, Issue2068) {
  12476. EventDispatcher ed;
  12477. Server svr;
  12478. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12479. res.set_chunked_content_provider("text/event-stream",
  12480. [&](size_t /*offset*/, DataSink &sink) {
  12481. return ed.wait_event(&sink);
  12482. });
  12483. });
  12484. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12485. svr.wait_until_ready();
  12486. thread event_thread([&] {
  12487. int id = 0;
  12488. while (svr.is_running()) {
  12489. this_thread::sleep_for(chrono::milliseconds(500));
  12490. std::stringstream ss;
  12491. ss << "data: " << id << "\n\n";
  12492. ed.send_event(ss.str());
  12493. id++;
  12494. }
  12495. });
  12496. auto se = detail::scope_exit([&] {
  12497. svr.stop();
  12498. listen_thread.join();
  12499. event_thread.join();
  12500. ASSERT_FALSE(svr.is_running());
  12501. });
  12502. {
  12503. auto client = detail::make_unique<Client>(HOST, PORT);
  12504. client->set_read_timeout(std::chrono::minutes(10));
  12505. std::atomic<bool> stop{false};
  12506. std::thread t([&] {
  12507. client->Get("/event1",
  12508. [&](const char *, size_t) -> bool { return !stop; });
  12509. });
  12510. std::this_thread::sleep_for(std::chrono::seconds(2));
  12511. stop = true;
  12512. client->stop();
  12513. t.join();
  12514. // Reset client after thread has finished
  12515. client.reset();
  12516. }
  12517. }
  12518. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12519. auto handled = false;
  12520. Server svr;
  12521. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12523. auto se = detail::scope_exit([&] {
  12524. svr.stop();
  12525. t.join();
  12526. ASSERT_FALSE(svr.is_running());
  12527. ASSERT_FALSE(handled);
  12528. });
  12529. svr.wait_until_ready();
  12530. // Two Content-Length headers with different values — must be rejected
  12531. auto req = "POST /test HTTP/1.1\r\n"
  12532. "Content-Length: 5\r\n"
  12533. "Content-Length: 10\r\n"
  12534. "\r\n"
  12535. "hello";
  12536. std::string response;
  12537. ASSERT_TRUE(send_request(1, req, &response));
  12538. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12539. response.substr(0, response.find("\r\n")));
  12540. }
  12541. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12542. auto handled = false;
  12543. Server svr;
  12544. svr.Post("/test", [&](const Request &, Response &res) {
  12545. handled = true;
  12546. res.set_content("ok", "text/plain");
  12547. });
  12548. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12549. auto se = detail::scope_exit([&] {
  12550. svr.stop();
  12551. t.join();
  12552. ASSERT_FALSE(svr.is_running());
  12553. ASSERT_TRUE(handled);
  12554. });
  12555. svr.wait_until_ready();
  12556. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12557. auto req = "POST /test HTTP/1.1\r\n"
  12558. "Content-Length: 5\r\n"
  12559. "Content-Length: 5\r\n"
  12560. "\r\n"
  12561. "hello";
  12562. std::string response;
  12563. ASSERT_TRUE(send_request(1, req, &response));
  12564. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12565. }
  12566. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12567. Server svr;
  12568. svr.Get("/", [](const Request &req, Response &res) {
  12569. EXPECT_EQ(2U, req.trailers.size());
  12570. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12571. // Denied
  12572. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12573. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12574. // Accepted
  12575. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12576. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12577. EXPECT_TRUE(req.has_trailer("X-World"));
  12578. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12579. res.set_content("ok", "text/plain");
  12580. });
  12581. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12582. auto se = detail::scope_exit([&] {
  12583. svr.stop();
  12584. t.join();
  12585. ASSERT_FALSE(svr.is_running());
  12586. });
  12587. svr.wait_until_ready();
  12588. const std::string req = "GET / HTTP/1.1\r\n"
  12589. "Transfer-Encoding: chunked\r\n"
  12590. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12591. "\r\n"
  12592. "0\r\n"
  12593. "Content-Length: 10\r\n"
  12594. "Host: internal.local\r\n"
  12595. "Content-Type: malicious/content\r\n"
  12596. "Cookie: any\r\n"
  12597. "Set-Cookie: any\r\n"
  12598. "X-Forwarded-For: attacker.com\r\n"
  12599. "X-Real-Ip: 1.1.1.1\r\n"
  12600. "X-Hello: hello\r\n"
  12601. "X-World: world\r\n"
  12602. "\r\n";
  12603. std::string res;
  12604. ASSERT_TRUE(send_request(1, req, &res));
  12605. }
  12606. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12607. Server svr;
  12608. std::string observed_remote_addr;
  12609. std::string observed_xff;
  12610. svr.Get("/ip", [&](const Request &req, Response &res) {
  12611. observed_remote_addr = req.remote_addr;
  12612. observed_xff = req.get_header_value("X-Forwarded-For");
  12613. res.set_content("ok", "text/plain");
  12614. });
  12615. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12616. auto se = detail::scope_exit([&] {
  12617. svr.stop();
  12618. t.join();
  12619. ASSERT_FALSE(svr.is_running());
  12620. });
  12621. svr.wait_until_ready();
  12622. Client cli(HOST, PORT);
  12623. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12624. ASSERT_TRUE(res);
  12625. EXPECT_EQ(StatusCode::OK_200, res->status);
  12626. EXPECT_EQ(observed_xff, "203.0.113.66");
  12627. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12628. observed_remote_addr == "127.0.0.1");
  12629. }
  12630. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12631. Server svr;
  12632. svr.set_trusted_proxies({"203.0.113.66"});
  12633. std::string observed_remote_addr;
  12634. std::string observed_xff;
  12635. svr.Get("/ip", [&](const Request &req, Response &res) {
  12636. observed_remote_addr = req.remote_addr;
  12637. observed_xff = req.get_header_value("X-Forwarded-For");
  12638. res.set_content("ok", "text/plain");
  12639. });
  12640. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12641. auto se = detail::scope_exit([&] {
  12642. svr.stop();
  12643. t.join();
  12644. ASSERT_FALSE(svr.is_running());
  12645. });
  12646. svr.wait_until_ready();
  12647. Client cli(HOST, PORT);
  12648. auto res = cli.Get("/ip");
  12649. ASSERT_TRUE(res);
  12650. EXPECT_EQ(StatusCode::OK_200, res->status);
  12651. EXPECT_EQ(observed_xff, "");
  12652. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12653. observed_remote_addr == "127.0.0.1");
  12654. }
  12655. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12656. Server svr;
  12657. svr.set_trusted_proxies({"203.0.113.66"});
  12658. std::string observed_remote_addr;
  12659. std::string observed_xff;
  12660. svr.Get("/ip", [&](const Request &req, Response &res) {
  12661. observed_remote_addr = req.remote_addr;
  12662. observed_xff = req.get_header_value("X-Forwarded-For");
  12663. res.set_content("ok", "text/plain");
  12664. });
  12665. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12666. auto se = detail::scope_exit([&] {
  12667. svr.stop();
  12668. t.join();
  12669. ASSERT_FALSE(svr.is_running());
  12670. });
  12671. svr.wait_until_ready();
  12672. Client cli(HOST, PORT);
  12673. auto res = cli.Get(
  12674. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12675. ASSERT_TRUE(res);
  12676. EXPECT_EQ(StatusCode::OK_200, res->status);
  12677. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12678. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12679. }
  12680. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12681. Server svr;
  12682. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12683. std::string observed_remote_addr;
  12684. std::string observed_xff;
  12685. svr.Get("/ip", [&](const Request &req, Response &res) {
  12686. observed_remote_addr = req.remote_addr;
  12687. observed_xff = req.get_header_value("X-Forwarded-For");
  12688. res.set_content("ok", "text/plain");
  12689. });
  12690. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12691. auto se = detail::scope_exit([&] {
  12692. svr.stop();
  12693. t.join();
  12694. ASSERT_FALSE(svr.is_running());
  12695. });
  12696. svr.wait_until_ready();
  12697. Client cli(HOST, PORT);
  12698. auto res = cli.Get(
  12699. "/ip",
  12700. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12701. ASSERT_TRUE(res);
  12702. EXPECT_EQ(StatusCode::OK_200, res->status);
  12703. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12704. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12705. }
  12706. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12707. Server svr;
  12708. svr.set_trusted_proxies({"192.0.2.45"});
  12709. std::string observed_remote_addr;
  12710. std::string observed_xff;
  12711. svr.Get("/ip", [&](const Request &req, Response &res) {
  12712. observed_remote_addr = req.remote_addr;
  12713. observed_xff = req.get_header_value("X-Forwarded-For");
  12714. res.set_content("ok", "text/plain");
  12715. });
  12716. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12717. auto se = detail::scope_exit([&] {
  12718. svr.stop();
  12719. t.join();
  12720. ASSERT_FALSE(svr.is_running());
  12721. });
  12722. svr.wait_until_ready();
  12723. Client cli(HOST, PORT);
  12724. auto res = cli.Get(
  12725. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12726. ASSERT_TRUE(res);
  12727. EXPECT_EQ(StatusCode::OK_200, res->status);
  12728. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12729. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12730. }
  12731. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12732. Server svr;
  12733. svr.set_trusted_proxies({"192.0.2.45"});
  12734. std::string observed_remote_addr;
  12735. std::string observed_xff;
  12736. svr.Get("/ip", [&](const Request &req, Response &res) {
  12737. observed_remote_addr = req.remote_addr;
  12738. observed_xff = req.get_header_value("X-Forwarded-For");
  12739. res.set_content("ok", "text/plain");
  12740. });
  12741. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12742. auto se = detail::scope_exit([&] {
  12743. svr.stop();
  12744. t.join();
  12745. ASSERT_FALSE(svr.is_running());
  12746. });
  12747. svr.wait_until_ready();
  12748. Client cli(HOST, PORT);
  12749. auto res = cli.Get(
  12750. "/ip",
  12751. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12752. ASSERT_TRUE(res);
  12753. EXPECT_EQ(StatusCode::OK_200, res->status);
  12754. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12755. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12756. }
  12757. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12758. Server svr;
  12759. svr.set_trusted_proxies({"192.0.2.45"});
  12760. std::string observed_remote_addr;
  12761. std::string observed_xff;
  12762. svr.Get("/ip", [&](const Request &req, Response &res) {
  12763. observed_remote_addr = req.remote_addr;
  12764. observed_xff = req.get_header_value("X-Forwarded-For");
  12765. res.set_content("ok", "text/plain");
  12766. });
  12767. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. t.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. std::string raw_req =
  12775. "GET /ip HTTP/1.1\r\n"
  12776. "Host: localhost\r\n"
  12777. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12778. "Connection: close\r\n"
  12779. "\r\n";
  12780. std::string out;
  12781. ASSERT_TRUE(send_request(5, raw_req, &out));
  12782. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12783. // Header parser trims surrounding whitespace of the header value
  12784. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12785. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12786. }
  12787. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12788. // crash the server (it used to call front() on an empty vector inside
  12789. // get_client_ip). The connection-level remote address must be retained instead.
  12790. static void run_malformed_xff_test(const std::string &xff_value) {
  12791. Server svr;
  12792. svr.set_trusted_proxies({"192.0.2.45"});
  12793. std::string observed_remote_addr;
  12794. svr.Get("/ip", [&](const Request &req, Response &res) {
  12795. observed_remote_addr = req.remote_addr;
  12796. res.set_content("ok", "text/plain");
  12797. });
  12798. int port = 0;
  12799. thread t = thread([&]() {
  12800. port = svr.bind_to_any_port(HOST);
  12801. svr.listen_after_bind();
  12802. });
  12803. auto se = detail::scope_exit([&] {
  12804. svr.stop();
  12805. t.join();
  12806. ASSERT_FALSE(svr.is_running());
  12807. });
  12808. svr.wait_until_ready();
  12809. Client cli(HOST, port);
  12810. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  12811. ASSERT_TRUE(res);
  12812. EXPECT_EQ(StatusCode::OK_200, res->status);
  12813. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12814. observed_remote_addr == "127.0.0.1");
  12815. }
  12816. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12817. run_malformed_xff_test("");
  12818. }
  12819. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12820. run_malformed_xff_test(",");
  12821. }
  12822. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12823. run_malformed_xff_test(", , ,");
  12824. }
  12825. #ifndef _WIN32
  12826. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12827. Server svr;
  12828. svr.Post("/post", [&](const Request &req, Response &res) {
  12829. res.set_content(req.body, "text/plain");
  12830. });
  12831. svr.Put("/put", [&](const Request &req, Response &res) {
  12832. res.set_content(req.body, "text/plain");
  12833. });
  12834. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12835. res.set_content(req.body, "text/plain");
  12836. });
  12837. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12838. res.set_content(req.body, "text/plain");
  12839. });
  12840. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12841. auto se = detail::scope_exit([&] {
  12842. svr.stop();
  12843. t.join();
  12844. ASSERT_FALSE(svr.is_running());
  12845. });
  12846. svr.wait_until_ready();
  12847. std::string resp;
  12848. // POST without Content-Length
  12849. ASSERT_TRUE(send_request(5,
  12850. "POST /post HTTP/1.1\r\n"
  12851. "Host: localhost\r\n"
  12852. "Connection: close\r\n"
  12853. "\r\n",
  12854. &resp));
  12855. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12856. // PUT without Content-Length
  12857. resp.clear();
  12858. ASSERT_TRUE(send_request(5,
  12859. "PUT /put HTTP/1.1\r\n"
  12860. "Host: localhost\r\n"
  12861. "Connection: close\r\n"
  12862. "\r\n",
  12863. &resp));
  12864. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12865. // PATCH without Content-Length
  12866. resp.clear();
  12867. ASSERT_TRUE(send_request(5,
  12868. "PATCH /patch HTTP/1.1\r\n"
  12869. "Host: localhost\r\n"
  12870. "Connection: close\r\n"
  12871. "\r\n",
  12872. &resp));
  12873. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12874. // DELETE without Content-Length
  12875. resp.clear();
  12876. ASSERT_TRUE(send_request(5,
  12877. "DELETE /delete HTTP/1.1\r\n"
  12878. "Host: localhost\r\n"
  12879. "Connection: close\r\n"
  12880. "\r\n",
  12881. &resp));
  12882. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12883. }
  12884. #endif
  12885. //==============================================================================
  12886. // open_stream() Tests
  12887. //==============================================================================
  12888. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12889. std::string result;
  12890. char buf[8192];
  12891. ssize_t n;
  12892. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12893. result.append(buf, static_cast<size_t>(n));
  12894. }
  12895. return result;
  12896. }
  12897. // Mock stream for unit tests
  12898. class MockStream : public Stream {
  12899. public:
  12900. std::string data;
  12901. size_t pos = 0;
  12902. ssize_t error_after = -1; // -1 = no error
  12903. explicit MockStream(const std::string &d, ssize_t err = -1)
  12904. : data(d), error_after(err) {}
  12905. bool is_readable() const override { return true; }
  12906. bool wait_readable() const override { return true; }
  12907. bool wait_writable() const override { return true; }
  12908. ssize_t read(char *ptr, size_t size) override {
  12909. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12910. if (pos >= data.size()) return 0;
  12911. size_t limit =
  12912. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12913. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12914. std::memcpy(ptr, data.data() + pos, to_read);
  12915. pos += to_read;
  12916. return static_cast<ssize_t>(to_read);
  12917. }
  12918. ssize_t write(const char *, size_t) override { return -1; }
  12919. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12920. ip = "127.0.0.1";
  12921. port = 0;
  12922. }
  12923. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12924. ip = "127.0.0.1";
  12925. port = 0;
  12926. }
  12927. socket_t socket() const override { return INVALID_SOCKET; }
  12928. time_t duration() const override { return 0; }
  12929. };
  12930. TEST(StreamHandleTest, Basic) {
  12931. ClientImpl::StreamHandle handle;
  12932. EXPECT_FALSE(handle.is_valid());
  12933. handle.response = detail::make_unique<Response>();
  12934. handle.error = Error::Connection;
  12935. EXPECT_FALSE(handle.is_valid());
  12936. handle.error = Error::Success;
  12937. EXPECT_TRUE(handle.is_valid());
  12938. }
  12939. TEST(BodyReaderTest, Basic) {
  12940. MockStream stream("Hello, World!");
  12941. detail::BodyReader reader;
  12942. reader.stream = &stream;
  12943. reader.content_length = 13;
  12944. char buf[32];
  12945. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12946. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12947. EXPECT_TRUE(reader.eof);
  12948. }
  12949. TEST(BodyReaderTest, NoStream) {
  12950. detail::BodyReader reader;
  12951. char buf[32];
  12952. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12953. EXPECT_EQ(Error::Connection, reader.last_error);
  12954. }
  12955. TEST(BodyReaderTest, Error) {
  12956. MockStream stream("Hello, World!", 5);
  12957. detail::BodyReader reader;
  12958. reader.stream = &stream;
  12959. reader.content_length = 13;
  12960. char buf[32];
  12961. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12962. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12963. EXPECT_EQ(Error::Read, reader.last_error);
  12964. }
  12965. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12966. // Mock-based StreamHandle tests relying on private internals are removed.
  12967. class OpenStreamTest : public ::testing::Test {
  12968. protected:
  12969. void SetUp() override {
  12970. svr_.Get("/hello", [](const Request &, Response &res) {
  12971. res.set_content("Hello World!", "text/plain");
  12972. });
  12973. svr_.Get("/large", [](const Request &, Response &res) {
  12974. res.set_content(std::string(10000, 'X'), "text/plain");
  12975. });
  12976. svr_.Get("/chunked", [](const Request &, Response &res) {
  12977. res.set_chunked_content_provider("text/plain",
  12978. [](size_t offset, DataSink &sink) {
  12979. if (offset < 15) {
  12980. sink.write("chunk", 5);
  12981. return true;
  12982. }
  12983. sink.done();
  12984. return true;
  12985. });
  12986. });
  12987. svr_.Get("/compressible", [](const Request &, Response &res) {
  12988. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12989. DataSink &sink) {
  12990. if (offset < 100 * 1024) {
  12991. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12992. sink.write(chunk.data(), chunk.size());
  12993. return true;
  12994. }
  12995. sink.done();
  12996. return true;
  12997. });
  12998. });
  12999. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13000. [](const Request & /*req*/, Response &res) {
  13001. auto i = new int(0);
  13002. res.set_header("Trailer", "Content-Length, X-Allowed");
  13003. res.set_chunked_content_provider(
  13004. "text/plain",
  13005. [i](size_t /*offset*/, DataSink &sink) {
  13006. switch (*i) {
  13007. case 0: sink.os << "123"; break;
  13008. case 1: sink.os << "456"; break;
  13009. case 2: sink.os << "789"; break;
  13010. case 3: {
  13011. sink.done_with_trailer(
  13012. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13013. } break;
  13014. }
  13015. (*i)++;
  13016. return true;
  13017. },
  13018. [i](bool success) {
  13019. EXPECT_TRUE(success);
  13020. delete i;
  13021. });
  13022. });
  13023. // Echo headers endpoint for header-related tests
  13024. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13025. std::string body;
  13026. for (const auto &h : req.headers) {
  13027. body.append(h.first);
  13028. body.push_back(':');
  13029. body.append(h.second);
  13030. body.push_back('\n');
  13031. }
  13032. res.set_content(body, "text/plain");
  13033. });
  13034. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13035. std::string body;
  13036. for (const auto &h : req.headers) {
  13037. body.append(h.first);
  13038. body.push_back(':');
  13039. body.append(h.second);
  13040. body.push_back('\n');
  13041. }
  13042. res.set_content(body, "text/plain");
  13043. });
  13044. port_ = svr_.bind_to_any_port("127.0.0.1");
  13045. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13046. svr_.wait_until_ready();
  13047. }
  13048. void TearDown() override {
  13049. svr_.stop();
  13050. if (thread_.joinable()) thread_.join();
  13051. }
  13052. Server svr_;
  13053. std::thread thread_;
  13054. int port_ = 0;
  13055. };
  13056. TEST_F(OpenStreamTest, Basic) {
  13057. Client cli("127.0.0.1", port_);
  13058. auto handle = cli.open_stream("GET", "/hello");
  13059. EXPECT_TRUE(handle.is_valid());
  13060. EXPECT_EQ("Hello World!", read_all(handle));
  13061. }
  13062. TEST_F(OpenStreamTest, SmallBuffer) {
  13063. Client cli("127.0.0.1", port_);
  13064. auto handle = cli.open_stream("GET", "/hello");
  13065. std::string result;
  13066. char buf[4];
  13067. ssize_t n;
  13068. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13069. result.append(buf, static_cast<size_t>(n));
  13070. EXPECT_EQ("Hello World!", result);
  13071. }
  13072. TEST_F(OpenStreamTest, DefaultHeaders) {
  13073. Client cli("127.0.0.1", port_);
  13074. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13075. {
  13076. auto handle = cli.open_stream("GET", "/echo-headers");
  13077. ASSERT_TRUE(handle.is_valid());
  13078. auto body = read_all(handle);
  13079. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13080. std::string::npos);
  13081. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13082. std::string::npos);
  13083. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13084. }
  13085. // open_stream POST with body and no explicit content_type should NOT add
  13086. // text/plain Content-Type (behavior differs from non-streaming path), but
  13087. // should include Content-Length
  13088. {
  13089. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13090. ASSERT_TRUE(handle.is_valid());
  13091. auto body = read_all(handle);
  13092. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13093. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13094. }
  13095. // open_stream POST with explicit Content-Type should preserve it
  13096. {
  13097. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13098. {{"Content-Type", "application/custom"}},
  13099. "{}", "application/custom");
  13100. ASSERT_TRUE(handle.is_valid());
  13101. auto body = read_all(handle);
  13102. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13103. }
  13104. // User-specified User-Agent must not be overwritten for stream API
  13105. {
  13106. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13107. {{"User-Agent", "MyAgent/1.2"}});
  13108. ASSERT_TRUE(handle.is_valid());
  13109. auto body = read_all(handle);
  13110. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13111. }
  13112. }
  13113. TEST_F(OpenStreamTest, Large) {
  13114. Client cli("127.0.0.1", port_);
  13115. auto handle = cli.open_stream("GET", "/large");
  13116. EXPECT_EQ(10000u, read_all(handle).size());
  13117. }
  13118. TEST_F(OpenStreamTest, ConnectionError) {
  13119. Client cli("127.0.0.1", 9999);
  13120. auto handle = cli.open_stream("GET", "/hello");
  13121. EXPECT_FALSE(handle.is_valid());
  13122. }
  13123. TEST_F(OpenStreamTest, Chunked) {
  13124. Client cli("127.0.0.1", port_);
  13125. auto handle = cli.open_stream("GET", "/chunked");
  13126. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13127. "Transfer-Encoding") == "chunked");
  13128. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13129. }
  13130. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13131. Client cli("127.0.0.1", port_);
  13132. auto handle =
  13133. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13134. ASSERT_TRUE(handle.is_valid());
  13135. // Consume body to allow trailers to be received/parsed
  13136. auto body = read_all(handle);
  13137. // Explicitly parse trailers (ensure trailers are available for assertion)
  13138. handle.parse_trailers_if_needed();
  13139. EXPECT_EQ(std::string("123456789"), body);
  13140. // The response should include a Trailer header declaring both names
  13141. ASSERT_TRUE(handle.response);
  13142. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13143. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13144. handle.response->get_header_value("Trailer"));
  13145. // Prohibited trailer must not be present
  13146. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13147. // Allowed trailer should be present
  13148. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13149. EXPECT_EQ(std::string("yes"),
  13150. handle.response->get_trailer_value("X-Allowed"));
  13151. // Verify trailers are NOT present as regular headers
  13152. EXPECT_EQ(std::string(""),
  13153. handle.response->get_header_value("Content-Length"));
  13154. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13155. }
  13156. static std::thread serve_single_response(std::promise<int> &port_promise,
  13157. const std::string &response) {
  13158. return std::thread([&port_promise, response] {
  13159. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13160. default_socket_options(srv);
  13161. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13162. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13163. sockaddr_in addr{};
  13164. addr.sin_family = AF_INET;
  13165. addr.sin_port = htons(0); // Let OS assign a free port
  13166. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13167. int opt = 1;
  13168. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13169. #ifdef _WIN32
  13170. reinterpret_cast<const char *>(&opt),
  13171. #else
  13172. &opt,
  13173. #endif
  13174. sizeof(opt));
  13175. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13176. ::listen(srv, 1) != 0) {
  13177. port_promise.set_value(-1);
  13178. detail::close_socket(srv);
  13179. return;
  13180. }
  13181. socklen_t addr_len = sizeof(addr);
  13182. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13183. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13184. sockaddr_in cli_addr{};
  13185. socklen_t cli_len = sizeof(cli_addr);
  13186. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13187. if (cli != INVALID_SOCKET) {
  13188. // Read the complete HTTP request (until the blank line that terminates
  13189. // headers) before sending the response. If the server closes the socket
  13190. // while the client's request data is still unread in the kernel receive
  13191. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13192. // connection on both sides: it discards the client's receive buffer
  13193. // (which already holds our response) and causes any in-progress write on
  13194. // the client to fail with ECONNRESET. Reading all request data first
  13195. // ensures close() emits a graceful FIN.
  13196. {
  13197. char rbuf[256];
  13198. std::string req;
  13199. while (req.find("\r\n\r\n") == std::string::npos) {
  13200. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13201. if (n <= 0) { break; }
  13202. req.append(rbuf, static_cast<size_t>(n));
  13203. }
  13204. }
  13205. ::send(cli,
  13206. #ifdef _WIN32
  13207. static_cast<const char *>(response.c_str()),
  13208. static_cast<int>(response.size()),
  13209. #else
  13210. response.c_str(), response.size(),
  13211. #endif
  13212. 0);
  13213. detail::close_socket(cli);
  13214. }
  13215. detail::close_socket(srv);
  13216. });
  13217. }
  13218. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13219. #ifndef _WIN32
  13220. signal(SIGPIPE, SIG_IGN);
  13221. #endif
  13222. std::promise<int> port_promise;
  13223. auto port_future = port_promise.get_future();
  13224. auto server_thread =
  13225. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13226. "Content-Type: text/plain\r\n"
  13227. "Content-Length: not-a-number\r\n"
  13228. "Connection: close\r\n"
  13229. "\r\n"
  13230. "hello");
  13231. auto port = port_future.get();
  13232. ASSERT_GT(port, 0);
  13233. Client cli("127.0.0.1", port);
  13234. auto handle = cli.open_stream("GET", "/");
  13235. EXPECT_FALSE(handle.is_valid());
  13236. server_thread.join();
  13237. }
  13238. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13239. #ifndef _WIN32
  13240. signal(SIGPIPE, SIG_IGN);
  13241. #endif
  13242. std::promise<int> port_promise;
  13243. auto port_future = port_promise.get_future();
  13244. auto server_thread = serve_single_response(
  13245. port_promise, "HTTP/1.1 200 OK\r\n"
  13246. "Content-Type: text/plain\r\n"
  13247. "Content-Length: 99999999999999999999999999\r\n"
  13248. "Connection: close\r\n"
  13249. "\r\n"
  13250. "hello");
  13251. auto port = port_future.get();
  13252. ASSERT_GT(port, 0);
  13253. // Before the fix, std::stoull would throw std::out_of_range here and
  13254. // crash the process. After the fix, strtoull silently clamps to
  13255. // ULLONG_MAX so the stream opens without crashing. The important thing
  13256. // is that the process does NOT terminate.
  13257. Client cli("127.0.0.1", port);
  13258. auto handle = cli.open_stream("GET", "/");
  13259. EXPECT_TRUE(handle.is_valid());
  13260. server_thread.join();
  13261. }
  13262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13263. TEST_F(OpenStreamTest, Gzip) {
  13264. Client cli("127.0.0.1", port_);
  13265. auto handle = cli.open_stream("GET", "/compressible", {},
  13266. {{"Accept-Encoding", "gzip"}});
  13267. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13268. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13269. }
  13270. #endif
  13271. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13272. TEST_F(OpenStreamTest, Brotli) {
  13273. Client cli("127.0.0.1", port_);
  13274. auto handle =
  13275. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13276. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13277. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13278. }
  13279. #endif
  13280. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13281. TEST_F(OpenStreamTest, Zstd) {
  13282. Client cli("127.0.0.1", port_);
  13283. auto handle = cli.open_stream("GET", "/compressible", {},
  13284. {{"Accept-Encoding", "zstd"}});
  13285. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13286. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13287. }
  13288. #endif
  13289. #ifdef CPPHTTPLIB_SSL_ENABLED
  13290. class SSLOpenStreamTest : public ::testing::Test {
  13291. protected:
  13292. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13293. void SetUp() override {
  13294. svr_.Get("/hello", [](const Request &, Response &res) {
  13295. res.set_content("Hello SSL World!", "text/plain");
  13296. });
  13297. svr_.Get("/chunked", [](const Request &, Response &res) {
  13298. res.set_chunked_content_provider("text/plain",
  13299. [](size_t offset, DataSink &sink) {
  13300. if (offset < 15) {
  13301. sink.write("chunk", 5);
  13302. return true;
  13303. }
  13304. sink.done();
  13305. return true;
  13306. });
  13307. });
  13308. svr_.Post("/echo", [](const Request &req, Response &res) {
  13309. res.set_content(req.body, req.get_header_value("Content-Type"));
  13310. });
  13311. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13312. std::string body = req.body;
  13313. res.set_chunked_content_provider(
  13314. "text/plain", [body](size_t offset, DataSink &sink) {
  13315. if (offset < body.size()) {
  13316. sink.write(body.data() + offset, body.size() - offset);
  13317. }
  13318. sink.done();
  13319. return true;
  13320. });
  13321. });
  13322. port_ = svr_.bind_to_any_port("127.0.0.1");
  13323. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13324. svr_.wait_until_ready();
  13325. }
  13326. void TearDown() override {
  13327. svr_.stop();
  13328. if (thread_.joinable()) thread_.join();
  13329. }
  13330. SSLServer svr_;
  13331. std::thread thread_;
  13332. int port_ = 0;
  13333. };
  13334. TEST_F(SSLOpenStreamTest, Basic) {
  13335. SSLClient cli("127.0.0.1", port_);
  13336. cli.enable_server_certificate_verification(false);
  13337. auto handle = cli.open_stream("GET", "/hello");
  13338. ASSERT_TRUE(handle.is_valid());
  13339. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13340. }
  13341. TEST_F(SSLOpenStreamTest, Chunked) {
  13342. SSLClient cli("127.0.0.1", port_);
  13343. cli.enable_server_certificate_verification(false);
  13344. auto handle = cli.open_stream("GET", "/chunked");
  13345. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13346. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13347. "Transfer-Encoding") == "chunked");
  13348. auto body = read_all(handle);
  13349. EXPECT_EQ("chunkchunkchunk", body);
  13350. }
  13351. TEST_F(SSLOpenStreamTest, Post) {
  13352. SSLClient cli("127.0.0.1", port_);
  13353. cli.enable_server_certificate_verification(false);
  13354. auto handle =
  13355. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13356. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13357. EXPECT_EQ(200, handle.response->status);
  13358. auto body = read_all(handle);
  13359. EXPECT_EQ("Hello SSL POST", body);
  13360. }
  13361. TEST_F(SSLOpenStreamTest, PostChunked) {
  13362. SSLClient cli("127.0.0.1", port_);
  13363. cli.enable_server_certificate_verification(false);
  13364. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13365. "Chunked SSL Data", "text/plain");
  13366. ASSERT_TRUE(handle.is_valid());
  13367. EXPECT_EQ(200, handle.response->status);
  13368. auto body = read_all(handle);
  13369. EXPECT_EQ("Chunked SSL Data", body);
  13370. }
  13371. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13372. // Content-Length is terminated by the server closing the connection. When the
  13373. // SSL peer sends a close_notify after the body, the client must treat it as a
  13374. // clean EOF and return a successful response rather than an error.
  13375. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13377. ASSERT_TRUE(svr.is_valid());
  13378. svr.set_keep_alive_max_count(1);
  13379. const std::string expected_body = "Hello from connection-close response!";
  13380. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13381. res.set_content_provider("text/plain",
  13382. [&](size_t offset, DataSink &sink) -> bool {
  13383. if (offset < expected_body.size()) {
  13384. sink.write(expected_body.data() + offset,
  13385. expected_body.size() - offset);
  13386. }
  13387. sink.done();
  13388. return true;
  13389. });
  13390. });
  13391. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13392. auto se = detail::scope_exit([&] {
  13393. svr.stop();
  13394. listen_thread.join();
  13395. ASSERT_FALSE(svr.is_running());
  13396. });
  13397. svr.wait_until_ready();
  13398. SSLClient cli(HOST, PORT);
  13399. cli.enable_server_certificate_verification(false);
  13400. auto res = cli.Get("/no-content-length");
  13401. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13402. EXPECT_EQ(StatusCode::OK_200, res->status);
  13403. EXPECT_EQ(expected_body, res->body);
  13404. }
  13405. #endif // CPPHTTPLIB_SSL_ENABLED
  13406. //==============================================================================
  13407. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13408. // results for various scenarios.
  13409. //==============================================================================
  13410. TEST(ParityTest, GetVsOpenStream) {
  13411. Server svr;
  13412. const std::string path = "/parity";
  13413. const std::string content = "Parity test content: hello world";
  13414. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13415. res.set_content(content, "text/plain");
  13416. });
  13417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13418. auto se = detail::scope_exit([&] {
  13419. svr.stop();
  13420. t.join();
  13421. ASSERT_FALSE(svr.is_running());
  13422. });
  13423. svr.wait_until_ready();
  13424. Client cli(HOST, PORT);
  13425. // Non-stream path
  13426. auto r1 = cli.Get(path);
  13427. ASSERT_TRUE(r1);
  13428. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13429. // Stream path
  13430. auto h = cli.open_stream("GET", path);
  13431. ASSERT_TRUE(h.is_valid());
  13432. EXPECT_EQ(r1->body, read_all(h));
  13433. }
  13434. // Helper to compress data with provided compressor type T
  13435. template <typename Compressor>
  13436. static std::string compress_payload_for_parity(const std::string &in) {
  13437. std::string out;
  13438. Compressor compressor;
  13439. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13440. [&](const char *data, size_t n) {
  13441. out.append(data, n);
  13442. return true;
  13443. });
  13444. EXPECT_TRUE(ok);
  13445. return out;
  13446. }
  13447. // Helper function for compression parity tests
  13448. template <typename Compressor>
  13449. static void test_compression_parity(const std::string &original,
  13450. const std::string &path,
  13451. const std::string &encoding) {
  13452. const std::string compressed =
  13453. compress_payload_for_parity<Compressor>(original);
  13454. Server svr;
  13455. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13456. res.set_content(compressed, "application/octet-stream");
  13457. res.set_header("Content-Encoding", encoding);
  13458. });
  13459. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13460. auto se = detail::scope_exit([&] {
  13461. svr.stop();
  13462. t.join();
  13463. ASSERT_FALSE(svr.is_running());
  13464. });
  13465. svr.wait_until_ready();
  13466. Client cli(HOST, PORT);
  13467. // Non-streaming
  13468. {
  13469. auto res = cli.Get(path);
  13470. ASSERT_TRUE(res);
  13471. EXPECT_EQ(StatusCode::OK_200, res->status);
  13472. EXPECT_EQ(original, res->body);
  13473. }
  13474. // Streaming
  13475. {
  13476. auto h = cli.open_stream("GET", path);
  13477. ASSERT_TRUE(h.is_valid());
  13478. EXPECT_EQ(original, read_all(h));
  13479. }
  13480. }
  13481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13482. TEST(ParityTest, Gzip) {
  13483. test_compression_parity<detail::gzip_compressor>(
  13484. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13485. }
  13486. #endif
  13487. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13488. TEST(ParityTest, Brotli) {
  13489. test_compression_parity<detail::brotli_compressor>(
  13490. "Hello, brotli parity test payload", "/parity-br", "br");
  13491. }
  13492. #endif
  13493. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13494. TEST(ParityTest, Zstd) {
  13495. test_compression_parity<detail::zstd_compressor>(
  13496. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13497. }
  13498. #endif
  13499. //==============================================================================
  13500. // New Stream API Tests
  13501. //==============================================================================
  13502. inline std::string read_body(httplib::stream::Result &result) {
  13503. std::string body;
  13504. while (result.next()) {
  13505. body.append(result.data(), result.size());
  13506. }
  13507. return body;
  13508. }
  13509. TEST(ClientConnectionTest, Basic) {
  13510. httplib::ClientConnection conn;
  13511. EXPECT_FALSE(conn.is_open());
  13512. conn.sock = 1;
  13513. EXPECT_TRUE(conn.is_open());
  13514. httplib::ClientConnection conn2(std::move(conn));
  13515. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13516. conn2.sock = INVALID_SOCKET;
  13517. }
  13518. // Unified test server for all stream::* tests
  13519. class StreamApiTest : public ::testing::Test {
  13520. protected:
  13521. void SetUp() override {
  13522. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13523. res.set_content("Hello World!", "text/plain");
  13524. });
  13525. svr_.Get("/echo-params",
  13526. [](const httplib::Request &req, httplib::Response &res) {
  13527. std::string r;
  13528. for (const auto &p : req.params) {
  13529. if (!r.empty()) r += "&";
  13530. r += p.first + "=" + p.second;
  13531. }
  13532. res.set_content(r, "text/plain");
  13533. });
  13534. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13535. res.set_content(req.body, req.get_header_value("Content-Type"));
  13536. });
  13537. svr_.Post("/echo-headers",
  13538. [](const httplib::Request &req, httplib::Response &res) {
  13539. std::string r;
  13540. for (const auto &h : req.headers)
  13541. r += h.first + ": " + h.second + "\n";
  13542. res.set_content(r, "text/plain");
  13543. });
  13544. svr_.Post("/echo-params",
  13545. [](const httplib::Request &req, httplib::Response &res) {
  13546. std::string r = "params:";
  13547. for (const auto &p : req.params)
  13548. r += p.first + "=" + p.second + ";";
  13549. res.set_content(r + " body:" + req.body, "text/plain");
  13550. });
  13551. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13552. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13553. });
  13554. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13555. res.set_content("PUT:" + req.body, "text/plain");
  13556. });
  13557. svr_.Patch("/echo",
  13558. [](const httplib::Request &req, httplib::Response &res) {
  13559. res.set_content("PATCH:" + req.body, "text/plain");
  13560. });
  13561. svr_.Delete(
  13562. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13563. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13564. "text/plain");
  13565. });
  13566. svr_.Get("/head-test",
  13567. [](const httplib::Request &, httplib::Response &res) {
  13568. res.set_content("body for HEAD", "text/plain");
  13569. });
  13570. svr_.Options("/options",
  13571. [](const httplib::Request &, httplib::Response &res) {
  13572. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13573. });
  13574. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13575. svr_.wait_until_ready();
  13576. }
  13577. void TearDown() override {
  13578. svr_.stop();
  13579. if (thread_.joinable()) thread_.join();
  13580. }
  13581. httplib::Server svr_;
  13582. std::thread thread_;
  13583. };
  13584. // stream::Get tests
  13585. TEST_F(StreamApiTest, GetBasic) {
  13586. httplib::Client cli(HOST, PORT);
  13587. auto result = httplib::stream::Get(cli, "/hello");
  13588. ASSERT_TRUE(result.is_valid());
  13589. EXPECT_EQ(200, result.status());
  13590. EXPECT_EQ("Hello World!", read_body(result));
  13591. }
  13592. TEST_F(StreamApiTest, GetWithParams) {
  13593. httplib::Client cli(HOST, PORT);
  13594. httplib::Params params{{"foo", "bar"}};
  13595. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13596. ASSERT_TRUE(result.is_valid());
  13597. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13598. }
  13599. TEST_F(StreamApiTest, GetConnectionError) {
  13600. httplib::Client cli(HOST, 9999);
  13601. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13602. }
  13603. TEST_F(StreamApiTest, Get404) {
  13604. httplib::Client cli(HOST, PORT);
  13605. auto result = httplib::stream::Get(cli, "/nonexistent");
  13606. EXPECT_TRUE(result.is_valid());
  13607. EXPECT_EQ(404, result.status());
  13608. }
  13609. // stream::Post tests
  13610. TEST_F(StreamApiTest, PostBasic) {
  13611. httplib::Client cli(HOST, PORT);
  13612. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13613. "application/json");
  13614. ASSERT_TRUE(result.is_valid());
  13615. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13616. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13617. }
  13618. TEST_F(StreamApiTest, PostWithHeaders) {
  13619. httplib::Client cli(HOST, PORT);
  13620. httplib::Headers headers{{"X-Custom", "value"}};
  13621. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13622. "text/plain");
  13623. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13624. }
  13625. TEST_F(StreamApiTest, PostWithParams) {
  13626. httplib::Client cli(HOST, PORT);
  13627. httplib::Params params{{"k", "v"}};
  13628. auto result =
  13629. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13630. auto body = read_body(result);
  13631. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13632. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13633. }
  13634. TEST_F(StreamApiTest, PostLarge) {
  13635. httplib::Client cli(HOST, PORT);
  13636. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13637. size_t total = 0;
  13638. while (result.next()) {
  13639. total += result.size();
  13640. }
  13641. EXPECT_EQ(100u * 1024u, total);
  13642. }
  13643. // stream::Put/Patch tests
  13644. TEST_F(StreamApiTest, PutAndPatch) {
  13645. httplib::Client cli(HOST, PORT);
  13646. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13647. EXPECT_EQ("PUT:test", read_body(put));
  13648. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13649. EXPECT_EQ("PATCH:test", read_body(patch));
  13650. }
  13651. // stream::Delete tests
  13652. TEST_F(StreamApiTest, Delete) {
  13653. httplib::Client cli(HOST, PORT);
  13654. auto del1 = httplib::stream::Delete(cli, "/resource");
  13655. EXPECT_EQ("Deleted", read_body(del1));
  13656. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13657. EXPECT_EQ("Deleted:data", read_body(del2));
  13658. }
  13659. // stream::Head/Options tests
  13660. TEST_F(StreamApiTest, HeadAndOptions) {
  13661. httplib::Client cli(HOST, PORT);
  13662. auto head = httplib::stream::Head(cli, "/head-test");
  13663. EXPECT_TRUE(head.is_valid());
  13664. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13665. auto opts = httplib::stream::Options(cli, "/options");
  13666. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13667. }
  13668. // SSL stream::* tests
  13669. #ifdef CPPHTTPLIB_SSL_ENABLED
  13670. class SSLStreamApiTest : public ::testing::Test {
  13671. protected:
  13672. void SetUp() override {
  13673. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13674. res.set_content("Hello SSL!", "text/plain");
  13675. });
  13676. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13677. res.set_content(req.body, "text/plain");
  13678. });
  13679. port_ = svr_.bind_to_any_port("127.0.0.1");
  13680. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13681. svr_.wait_until_ready();
  13682. }
  13683. void TearDown() override {
  13684. svr_.stop();
  13685. if (thread_.joinable()) thread_.join();
  13686. }
  13687. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13688. std::thread thread_;
  13689. int port_ = 0;
  13690. };
  13691. TEST_F(SSLStreamApiTest, GetAndPost) {
  13692. httplib::SSLClient cli("127.0.0.1", port_);
  13693. cli.enable_server_certificate_verification(false);
  13694. auto get = httplib::stream::Get(cli, "/hello");
  13695. EXPECT_EQ("Hello SSL!", read_body(get));
  13696. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13697. EXPECT_EQ("test", read_body(post));
  13698. }
  13699. #endif
  13700. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13701. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13702. // BodyReader
  13703. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13704. // Test that read timeout during streaming is detected
  13705. // Use a large content-length response where server delays mid-stream
  13706. Server svr;
  13707. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13708. // Send a large response with delay in the middle
  13709. res.set_content_provider(
  13710. 1000, // content_length
  13711. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13712. if (offset < 100) {
  13713. // Send first 100 bytes immediately
  13714. std::string data(100, 'A');
  13715. sink.write(data.c_str(), data.size());
  13716. return true;
  13717. }
  13718. // Then delay longer than client timeout
  13719. std::this_thread::sleep_for(std::chrono::seconds(3));
  13720. std::string data(900, 'B');
  13721. sink.write(data.c_str(), data.size());
  13722. return true;
  13723. });
  13724. });
  13725. auto port = 8091;
  13726. std::thread t([&]() { svr.listen("localhost", port); });
  13727. svr.wait_until_ready();
  13728. Client cli("localhost", port);
  13729. cli.set_read_timeout(1, 0); // 1 second timeout
  13730. auto handle = cli.open_stream("GET", "/slow-stream");
  13731. ASSERT_TRUE(handle.is_valid());
  13732. char buf[256];
  13733. ssize_t total = 0;
  13734. ssize_t n;
  13735. bool got_error = false;
  13736. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13737. total += n;
  13738. }
  13739. if (n < 0) {
  13740. got_error = true;
  13741. // Should be timeout or read error
  13742. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13743. handle.get_read_error() == Error::Read)
  13744. << "Actual error: " << to_string(handle.get_read_error());
  13745. }
  13746. // Either we got an error, or we got less data than expected
  13747. EXPECT_TRUE(got_error || total < 1000)
  13748. << "Expected timeout but got all " << total << " bytes";
  13749. svr.stop();
  13750. t.join();
  13751. }
  13752. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13753. // Test connection closed detection via BodyReader
  13754. Server svr;
  13755. std::atomic<bool> close_now{false};
  13756. svr.Get("/will-close", [&](const Request &, Response &res) {
  13757. res.set_content_provider(
  13758. 10000, // Large content_length that we won't fully send
  13759. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13760. if (offset < 100) {
  13761. std::string data(100, 'X');
  13762. sink.write(data.c_str(), data.size());
  13763. return true;
  13764. }
  13765. // Wait for signal then abort
  13766. while (!close_now) {
  13767. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13768. }
  13769. return false; // Abort - server will close connection
  13770. });
  13771. });
  13772. auto port = 8092;
  13773. std::thread t([&]() { svr.listen("localhost", port); });
  13774. svr.wait_until_ready();
  13775. Client cli("localhost", port);
  13776. auto handle = cli.open_stream("GET", "/will-close");
  13777. ASSERT_TRUE(handle.is_valid());
  13778. char buf[256];
  13779. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13780. EXPECT_GT(n, 0) << "First read should succeed";
  13781. // Signal server to close
  13782. close_now = true;
  13783. // Keep reading until error or EOF
  13784. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13785. // Keep reading
  13786. }
  13787. // Should get an error since content_length wasn't satisfied
  13788. if (n < 0) {
  13789. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13790. handle.get_read_error() == Error::Read)
  13791. << "Actual error: " << to_string(handle.get_read_error());
  13792. }
  13793. svr.stop();
  13794. t.join();
  13795. }
  13796. #ifdef CPPHTTPLIB_SSL_ENABLED
  13797. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13798. // Test that read timeout during SSL streaming is detected
  13799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13800. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13801. res.set_content_provider(
  13802. 1000, "text/plain",
  13803. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13804. if (offset < 100) {
  13805. std::string data(100, 'A');
  13806. sink.write(data.c_str(), data.size());
  13807. return true;
  13808. }
  13809. std::this_thread::sleep_for(std::chrono::seconds(3));
  13810. std::string data(900, 'B');
  13811. sink.write(data.c_str(), data.size());
  13812. return true;
  13813. });
  13814. });
  13815. auto port = 8093;
  13816. std::thread t([&]() { svr.listen("localhost", port); });
  13817. svr.wait_until_ready();
  13818. SSLClient cli("localhost", port);
  13819. cli.enable_server_certificate_verification(false);
  13820. cli.set_read_timeout(1, 0); // 1 second timeout
  13821. auto handle = cli.open_stream("GET", "/slow-stream");
  13822. ASSERT_TRUE(handle.is_valid());
  13823. char buf[256];
  13824. ssize_t total = 0;
  13825. ssize_t n;
  13826. bool got_error = false;
  13827. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13828. total += n;
  13829. }
  13830. if (n < 0) {
  13831. got_error = true;
  13832. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13833. handle.get_read_error() == Error::Read)
  13834. << "Actual error: " << to_string(handle.get_read_error());
  13835. }
  13836. EXPECT_TRUE(got_error || total < 1000)
  13837. << "Expected timeout but got all " << total << " bytes";
  13838. svr.stop();
  13839. t.join();
  13840. }
  13841. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13842. // Test SSL connection closed detection
  13843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13844. std::atomic<bool> close_now{false};
  13845. svr.Get("/will-close", [&](const Request &, Response &res) {
  13846. res.set_content_provider(
  13847. 10000, "text/plain",
  13848. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13849. if (offset < 100) {
  13850. std::string data(100, 'X');
  13851. sink.write(data.c_str(), data.size());
  13852. return true;
  13853. }
  13854. while (!close_now) {
  13855. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13856. }
  13857. return false;
  13858. });
  13859. });
  13860. auto port = 8094;
  13861. std::thread t([&]() { svr.listen("localhost", port); });
  13862. svr.wait_until_ready();
  13863. SSLClient cli("localhost", port);
  13864. cli.enable_server_certificate_verification(false);
  13865. auto handle = cli.open_stream("GET", "/will-close");
  13866. ASSERT_TRUE(handle.is_valid());
  13867. char buf[256];
  13868. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13869. EXPECT_GT(n, 0);
  13870. // Signal server to close
  13871. close_now = true;
  13872. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13873. // Keep reading
  13874. }
  13875. if (n < 0) {
  13876. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13877. handle.get_read_error() == Error::Read)
  13878. << "Actual error: " << to_string(handle.get_read_error());
  13879. }
  13880. svr.stop();
  13881. t.join();
  13882. }
  13883. #endif
  13884. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13885. using namespace httplib;
  13886. // Create a test file
  13887. const char *fname = "etag_testfile.txt";
  13888. const char *content = "etag-content";
  13889. {
  13890. std::ofstream ofs(fname);
  13891. ofs << content;
  13892. ASSERT_TRUE(ofs.good());
  13893. }
  13894. Server svr;
  13895. svr.set_mount_point("/static", ".");
  13896. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13897. svr.wait_until_ready();
  13898. Client cli(HOST, PORT);
  13899. // First request: should get 200 with ETag header
  13900. auto res1 = cli.Get("/static/etag_testfile.txt");
  13901. ASSERT_TRUE(res1);
  13902. ASSERT_EQ(200, res1->status);
  13903. ASSERT_TRUE(res1->has_header("ETag"));
  13904. std::string etag = res1->get_header_value("ETag");
  13905. EXPECT_FALSE(etag.empty());
  13906. // Verify ETag format: W/"hex-hex"
  13907. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13908. EXPECT_EQ('W', etag[0]);
  13909. EXPECT_EQ('/', etag[1]);
  13910. EXPECT_EQ('"', etag[2]);
  13911. EXPECT_EQ('"', etag.back());
  13912. // Exact match: expect 304 Not Modified
  13913. Headers h2 = {{"If-None-Match", etag}};
  13914. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13915. ASSERT_TRUE(res2);
  13916. EXPECT_EQ(304, res2->status);
  13917. // Wildcard match: expect 304 Not Modified
  13918. Headers h3 = {{"If-None-Match", "*"}};
  13919. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13920. ASSERT_TRUE(res3);
  13921. EXPECT_EQ(304, res3->status);
  13922. // Non-matching ETag: expect 200
  13923. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13924. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13925. ASSERT_TRUE(res4);
  13926. EXPECT_EQ(200, res4->status);
  13927. // Multiple ETags with one matching: expect 304
  13928. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13929. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13930. ASSERT_TRUE(res5);
  13931. EXPECT_EQ(304, res5->status);
  13932. svr.stop();
  13933. t.join();
  13934. std::remove(fname);
  13935. }
  13936. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13937. using namespace httplib;
  13938. Server svr;
  13939. svr.set_mount_point("/static", ".");
  13940. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13941. svr.wait_until_ready();
  13942. Client cli(HOST, PORT);
  13943. // Send If-None-Match: * to a non-existent file
  13944. Headers h = {{"If-None-Match", "*"}};
  13945. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13946. ASSERT_TRUE(res);
  13947. EXPECT_EQ(404, res->status);
  13948. svr.stop();
  13949. t.join();
  13950. }
  13951. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13952. using namespace httplib;
  13953. // Create a test file
  13954. const char *fname = "etag_boundary_testfile.txt";
  13955. const char *content = "boundary-test";
  13956. {
  13957. std::ofstream ofs(fname);
  13958. ofs << content;
  13959. ASSERT_TRUE(ofs.good());
  13960. }
  13961. Server svr;
  13962. svr.set_mount_point("/static", ".");
  13963. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13964. svr.wait_until_ready();
  13965. Client cli(HOST, PORT);
  13966. // Get the actual ETag
  13967. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13968. ASSERT_TRUE(res1);
  13969. ASSERT_EQ(200, res1->status);
  13970. ASSERT_TRUE(res1->has_header("ETag"));
  13971. std::string etag = res1->get_header_value("ETag");
  13972. // Test 1: Very long ETag value (longer than actual ETag)
  13973. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13974. Headers h1 = {{"If-None-Match", "W/"
  13975. "\"very-long-etag-value-that-is-much-longer-"
  13976. "than-the-actual-etag-value\""}};
  13977. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13978. ASSERT_TRUE(res2);
  13979. EXPECT_EQ(200, res2->status); // Should not match
  13980. // Test 2: Long string followed by wildcard
  13981. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13982. // string)
  13983. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13984. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13985. ASSERT_TRUE(res3);
  13986. EXPECT_EQ(304, res3->status); // Should match on "*"
  13987. // Test 3: Wildcard followed by long string
  13988. // Should match on "*" immediately and return 304
  13989. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13990. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13991. ASSERT_TRUE(res4);
  13992. EXPECT_EQ(304, res4->status); // Should match on "*"
  13993. // Test 4: Multiple long non-matching values
  13994. // Should NOT match and return 200 (test that all comparisons are safe)
  13995. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13996. "W/\"second-long-non-matching-value\", "
  13997. "W/\"third-long-non-matching-value\""}};
  13998. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13999. ASSERT_TRUE(res5);
  14000. EXPECT_EQ(200, res5->status); // Should not match
  14001. // Test 5: Single character that is not "*" (edge case)
  14002. Headers h5 = {{"If-None-Match", "X"}};
  14003. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14004. ASSERT_TRUE(res6);
  14005. EXPECT_EQ(200, res6->status); // Should not match
  14006. svr.stop();
  14007. t.join();
  14008. std::remove(fname);
  14009. }
  14010. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14011. using namespace httplib;
  14012. // Create a test file
  14013. const char *fname = "ims_testfile.txt";
  14014. const char *content = "if-modified-since-test";
  14015. {
  14016. std::ofstream ofs(fname);
  14017. ofs << content;
  14018. ASSERT_TRUE(ofs.good());
  14019. }
  14020. Server svr;
  14021. svr.set_mount_point("/static", ".");
  14022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14023. svr.wait_until_ready();
  14024. Client cli(HOST, PORT);
  14025. // First request: should get 200 with Last-Modified header
  14026. auto res1 = cli.Get("/static/ims_testfile.txt");
  14027. ASSERT_TRUE(res1);
  14028. ASSERT_EQ(200, res1->status);
  14029. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14030. std::string last_modified = res1->get_header_value("Last-Modified");
  14031. EXPECT_FALSE(last_modified.empty());
  14032. // If-Modified-Since with same time: expect 304
  14033. Headers h2 = {{"If-Modified-Since", last_modified}};
  14034. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14035. ASSERT_TRUE(res2);
  14036. EXPECT_EQ(304, res2->status);
  14037. // If-Modified-Since with future time: expect 304
  14038. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14039. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14040. ASSERT_TRUE(res3);
  14041. EXPECT_EQ(304, res3->status);
  14042. // If-Modified-Since with past time: expect 200
  14043. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14044. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14045. ASSERT_TRUE(res4);
  14046. EXPECT_EQ(200, res4->status);
  14047. // If-None-Match takes precedence over If-Modified-Since
  14048. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14049. ASSERT_TRUE(res1->has_header("ETag"));
  14050. std::string etag = res1->get_header_value("ETag");
  14051. Headers h5 = {{"If-None-Match", etag},
  14052. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14053. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14054. ASSERT_TRUE(res5);
  14055. EXPECT_EQ(304, res5->status);
  14056. svr.stop();
  14057. t.join();
  14058. std::remove(fname);
  14059. }
  14060. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14061. using namespace httplib;
  14062. Server svr;
  14063. // Endpoint that returns compressible content
  14064. svr.Get("/compressible", [](const Request &, Response &res) {
  14065. // Return a large enough body to trigger compression
  14066. std::string body(1000, 'a');
  14067. res.set_content(body, "text/plain");
  14068. });
  14069. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14070. svr.wait_until_ready();
  14071. Client cli(HOST, PORT);
  14072. // Request with gzip support: should get Vary header when compressed
  14073. cli.set_compress(true);
  14074. auto res1 = cli.Get("/compressible");
  14075. ASSERT_TRUE(res1);
  14076. EXPECT_EQ(200, res1->status);
  14077. // If Content-Encoding is set, Vary should also be set
  14078. if (res1->has_header("Content-Encoding")) {
  14079. EXPECT_TRUE(res1->has_header("Vary"));
  14080. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14081. }
  14082. // Request without Accept-Encoding header: should not have compression
  14083. Headers h_no_compress;
  14084. auto res2 = cli.Get("/compressible", h_no_compress);
  14085. ASSERT_TRUE(res2);
  14086. EXPECT_EQ(200, res2->status);
  14087. // Verify Vary header is present when compression is applied
  14088. // (the exact behavior depends on server configuration)
  14089. svr.stop();
  14090. t.join();
  14091. }
  14092. TEST(ETagTest, IfRangeWithETag) {
  14093. using namespace httplib;
  14094. // Create a test file with known content
  14095. const char *fname = "if_range_testfile.txt";
  14096. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14097. {
  14098. std::ofstream ofs(fname);
  14099. ofs << content;
  14100. ASSERT_TRUE(ofs.good());
  14101. }
  14102. Server svr;
  14103. svr.set_mount_point("/static", ".");
  14104. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14105. svr.wait_until_ready();
  14106. Client cli(HOST, PORT);
  14107. // First request: get ETag
  14108. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14109. ASSERT_TRUE(res1);
  14110. ASSERT_EQ(200, res1->status);
  14111. ASSERT_TRUE(res1->has_header("ETag"));
  14112. std::string etag = res1->get_header_value("ETag");
  14113. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14114. // Since our server generates weak ETags (W/"..."), If-Range with our
  14115. // ETag should NOT result in partial content - it should return full content.
  14116. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14117. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14118. ASSERT_TRUE(res2);
  14119. // Weak ETag in If-Range -> full content (200), not partial (206)
  14120. EXPECT_EQ(200, res2->status);
  14121. EXPECT_EQ(content, res2->body);
  14122. EXPECT_FALSE(res2->has_header("Content-Range"));
  14123. // Range request with non-matching If-Range (ETag): should get 200 (full
  14124. // content)
  14125. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14126. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14127. ASSERT_TRUE(res3);
  14128. EXPECT_EQ(200, res3->status);
  14129. EXPECT_EQ(content, res3->body);
  14130. EXPECT_FALSE(res3->has_header("Content-Range"));
  14131. // Range request with strong ETag (hypothetical - our server doesn't generate
  14132. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14133. // should return full content)
  14134. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14135. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14136. ASSERT_TRUE(res4);
  14137. EXPECT_EQ(200, res4->status);
  14138. EXPECT_EQ(content, res4->body);
  14139. EXPECT_FALSE(res4->has_header("Content-Range"));
  14140. svr.stop();
  14141. t.join();
  14142. std::remove(fname);
  14143. }
  14144. TEST(ETagTest, IfRangeWithDate) {
  14145. using namespace httplib;
  14146. // Create a test file
  14147. const char *fname = "if_range_date_testfile.txt";
  14148. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14149. {
  14150. std::ofstream ofs(fname);
  14151. ofs << content;
  14152. ASSERT_TRUE(ofs.good());
  14153. }
  14154. Server svr;
  14155. svr.set_mount_point("/static", ".");
  14156. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14157. svr.wait_until_ready();
  14158. Client cli(HOST, PORT);
  14159. // First request: get Last-Modified
  14160. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14161. ASSERT_TRUE(res1);
  14162. ASSERT_EQ(200, res1->status);
  14163. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14164. std::string last_modified = res1->get_header_value("Last-Modified");
  14165. // Range request with matching If-Range (date): should get 206
  14166. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14167. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14168. ASSERT_TRUE(res2);
  14169. EXPECT_EQ(206, res2->status);
  14170. EXPECT_EQ("FGHIJ", res2->body);
  14171. // Range request with old If-Range date: should get 200 (full content)
  14172. Headers h3 = {{"Range", "bytes=5-9"},
  14173. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14174. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14175. ASSERT_TRUE(res3);
  14176. EXPECT_EQ(200, res3->status);
  14177. EXPECT_EQ(content, res3->body);
  14178. // Range request with future If-Range date: should get 206
  14179. Headers h4 = {{"Range", "bytes=0-4"},
  14180. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14181. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14182. ASSERT_TRUE(res4);
  14183. EXPECT_EQ(206, res4->status);
  14184. EXPECT_EQ("ABCDE", res4->body);
  14185. svr.stop();
  14186. t.join();
  14187. std::remove(fname);
  14188. }
  14189. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14190. using namespace httplib;
  14191. const char *fname = "etag_malformed.txt";
  14192. const char *content = "malformed-etag";
  14193. {
  14194. std::ofstream ofs(fname);
  14195. ofs << content;
  14196. ASSERT_TRUE(ofs.good());
  14197. }
  14198. Server svr;
  14199. svr.set_mount_point("/static", ".");
  14200. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14201. svr.wait_until_ready();
  14202. Client cli(HOST, PORT);
  14203. // baseline: should get 200 and an ETag
  14204. auto res1 = cli.Get("/static/etag_malformed.txt");
  14205. ASSERT_TRUE(res1);
  14206. ASSERT_EQ(200, res1->status);
  14207. ASSERT_TRUE(res1->has_header("ETag"));
  14208. // Malformed ETag value (missing quotes) should be treated as non-matching
  14209. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14210. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14211. ASSERT_TRUE(res_bad);
  14212. EXPECT_EQ(200, res_bad->status);
  14213. // Whitespace-only header value should be considered invalid / non-matching
  14214. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14215. "Host: localhost\r\n"
  14216. "If-None-Match: \r\n"
  14217. "Connection: close\r\n"
  14218. "\r\n";
  14219. std::string out;
  14220. ASSERT_TRUE(send_request(5, raw_req, &out));
  14221. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14222. svr.stop();
  14223. t.join();
  14224. std::remove(fname);
  14225. }
  14226. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14227. using namespace httplib;
  14228. const char *fname = "ims_invalid_format.txt";
  14229. const char *content = "ims-bad-format";
  14230. {
  14231. std::ofstream ofs(fname);
  14232. ofs << content;
  14233. ASSERT_TRUE(ofs.good());
  14234. }
  14235. Server svr;
  14236. svr.set_mount_point("/static", ".");
  14237. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14238. svr.wait_until_ready();
  14239. Client cli(HOST, PORT);
  14240. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14241. ASSERT_TRUE(res1);
  14242. ASSERT_EQ(200, res1->status);
  14243. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14244. // If-Modified-Since with invalid format should not result in 304
  14245. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14246. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14247. ASSERT_TRUE(res_bad);
  14248. EXPECT_EQ(200, res_bad->status);
  14249. // If-Range with invalid date format should be treated as mismatch -> full
  14250. // content (200)
  14251. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14252. {"If-Range", "invalid-date"}};
  14253. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14254. ASSERT_TRUE(res_ifrange);
  14255. EXPECT_EQ(200, res_ifrange->status);
  14256. svr.stop();
  14257. t.join();
  14258. std::remove(fname);
  14259. }
  14260. TEST(ETagTest, IfRangeWithMalformedETag) {
  14261. using namespace httplib;
  14262. const char *fname = "ifrange_malformed.txt";
  14263. const std::string content = "0123456789";
  14264. {
  14265. std::ofstream ofs(fname);
  14266. ofs << content;
  14267. ASSERT_TRUE(ofs.good());
  14268. }
  14269. Server svr;
  14270. svr.set_mount_point("/static", ".");
  14271. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14272. svr.wait_until_ready();
  14273. Client cli(HOST, PORT);
  14274. // First request: get ETag
  14275. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14276. ASSERT_TRUE(res1);
  14277. ASSERT_EQ(200, res1->status);
  14278. ASSERT_TRUE(res1->has_header("ETag"));
  14279. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14280. // full content (200)
  14281. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14282. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14283. ASSERT_TRUE(res2);
  14284. EXPECT_EQ(200, res2->status);
  14285. EXPECT_EQ(content, res2->body);
  14286. svr.stop();
  14287. t.join();
  14288. std::remove(fname);
  14289. }
  14290. TEST(ETagTest, ExtremeLargeDateValues) {
  14291. using namespace httplib;
  14292. const char *fname = "ims_extreme_date.txt";
  14293. const char *content = "ims-extreme-date";
  14294. {
  14295. std::ofstream ofs(fname);
  14296. ofs << content;
  14297. ASSERT_TRUE(ofs.good());
  14298. }
  14299. Server svr;
  14300. svr.set_mount_point("/static", ".");
  14301. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14302. svr.wait_until_ready();
  14303. Client cli(HOST, PORT);
  14304. auto res1 = cli.Get(std::string("/static/") + fname);
  14305. ASSERT_TRUE(res1);
  14306. ASSERT_EQ(200, res1->status);
  14307. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14308. // Extremely large year that may overflow date parsing routines.
  14309. Headers h_large_date = {
  14310. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14311. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14312. ASSERT_TRUE(res_bad);
  14313. // Expect server to treat this as invalid/mismatch and return full content
  14314. EXPECT_EQ(200, res_bad->status);
  14315. // If-Range with extremely large date should be treated as mismatch -> full
  14316. // content (200)
  14317. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14318. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14319. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14320. ASSERT_TRUE(res_ifrange);
  14321. EXPECT_EQ(200, res_ifrange->status);
  14322. svr.stop();
  14323. t.join();
  14324. std::remove(fname);
  14325. }
  14326. TEST(ETagTest, NegativeFileModificationTime) {
  14327. using namespace httplib;
  14328. const char *fname = "ims_negative_mtime.txt";
  14329. const std::string content = "negative-mtime";
  14330. {
  14331. std::ofstream ofs(fname);
  14332. ofs << content;
  14333. ASSERT_TRUE(ofs.good());
  14334. }
  14335. // Try to set file mtime to a negative value. This may fail on some
  14336. // platforms/filesystems; if it fails, the test will still verify server
  14337. // behaves safely by performing a regular conditional request.
  14338. #if defined(__APPLE__) || defined(__linux__)
  14339. bool set_negative = false;
  14340. do {
  14341. struct timeval times[2];
  14342. // access time: now
  14343. times[0].tv_sec = time(nullptr);
  14344. times[0].tv_usec = 0;
  14345. // modification time: negative (e.g., -1)
  14346. times[1].tv_sec = -1;
  14347. times[1].tv_usec = 0;
  14348. if (utimes(fname, times) == 0) { set_negative = true; }
  14349. } while (0);
  14350. #else
  14351. bool set_negative = false;
  14352. #endif
  14353. Server svr;
  14354. svr.set_mount_point("/static", ".");
  14355. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14356. svr.wait_until_ready();
  14357. Client cli(HOST, PORT);
  14358. auto res1 = cli.Get(std::string("/static/") + fname);
  14359. ASSERT_TRUE(res1);
  14360. ASSERT_EQ(200, res1->status);
  14361. bool has_last_modified = res1->has_header("Last-Modified");
  14362. std::string last_modified;
  14363. if (has_last_modified) {
  14364. last_modified = res1->get_header_value("Last-Modified");
  14365. }
  14366. if (set_negative) {
  14367. // If we successfully set a negative mtime, ensure server returns a
  14368. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14369. // with an old date and ensure server handles it without crash.
  14370. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14371. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14372. ASSERT_TRUE(res2);
  14373. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14374. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14375. } else {
  14376. // Could not set negative mtime on this platform; fall back to verifying
  14377. // that normal invalid/malformed dates are treated safely (non-304).
  14378. Headers h_bad_date = {
  14379. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14380. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14381. ASSERT_TRUE(res_bad);
  14382. EXPECT_EQ(200, res_bad->status);
  14383. }
  14384. svr.stop();
  14385. t.join();
  14386. std::remove(fname);
  14387. }
  14388. //==============================================================================
  14389. // SSE Parsing Tests
  14390. //==============================================================================
  14391. class SSEParsingTest : public ::testing::Test {
  14392. protected:
  14393. // Test helper that mimics SSE parsing behavior
  14394. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14395. int &retry_ms) {
  14396. // Blank line signals end of event
  14397. if (line.empty() || line == "\r") { return true; }
  14398. // Lines starting with ':' are comments (ignored)
  14399. if (!line.empty() && line[0] == ':') { return false; }
  14400. // Find the colon separator
  14401. auto colon_pos = line.find(':');
  14402. if (colon_pos == std::string::npos) {
  14403. // Line with no colon is treated as field name with empty value
  14404. return false;
  14405. }
  14406. std::string field = line.substr(0, colon_pos);
  14407. std::string value;
  14408. // Value starts after colon, skip optional single space
  14409. if (colon_pos + 1 < line.size()) {
  14410. size_t value_start = colon_pos + 1;
  14411. if (line[value_start] == ' ') { value_start++; }
  14412. value = line.substr(value_start);
  14413. // Remove trailing \r if present
  14414. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14415. }
  14416. // Handle known fields
  14417. if (field == "event") {
  14418. msg.event = value;
  14419. } else if (field == "data") {
  14420. // Multiple data lines are concatenated with newlines
  14421. if (!msg.data.empty()) { msg.data += "\n"; }
  14422. msg.data += value;
  14423. } else if (field == "id") {
  14424. // Empty id is valid (clears the last event ID)
  14425. msg.id = value;
  14426. } else if (field == "retry") {
  14427. // Parse retry interval in milliseconds
  14428. {
  14429. int v = 0;
  14430. auto res =
  14431. detail::from_chars(value.data(), value.data() + value.size(), v);
  14432. if (res.ec == std::errc{}) { retry_ms = v; }
  14433. }
  14434. }
  14435. // Unknown fields are ignored per SSE spec
  14436. return false;
  14437. }
  14438. };
  14439. // Test: Single-line data
  14440. TEST_F(SSEParsingTest, SingleLineData) {
  14441. sse::SSEMessage msg;
  14442. int retry_ms = 3000;
  14443. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14444. EXPECT_EQ(msg.data, "hello");
  14445. EXPECT_EQ(msg.event, "message");
  14446. // Blank line ends event
  14447. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14448. }
  14449. // Test: Multi-line data
  14450. TEST_F(SSEParsingTest, MultiLineData) {
  14451. sse::SSEMessage msg;
  14452. int retry_ms = 3000;
  14453. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14454. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14455. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14456. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14457. }
  14458. // Test: Custom event types
  14459. TEST_F(SSEParsingTest, CustomEventType) {
  14460. sse::SSEMessage msg;
  14461. int retry_ms = 3000;
  14462. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14463. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14464. EXPECT_EQ(msg.event, "update");
  14465. EXPECT_EQ(msg.data, "payload");
  14466. }
  14467. // Test: Event ID handling
  14468. TEST_F(SSEParsingTest, EventIdHandling) {
  14469. sse::SSEMessage msg;
  14470. int retry_ms = 3000;
  14471. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14472. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14473. EXPECT_EQ(msg.id, "12345");
  14474. }
  14475. // Test: Empty event ID (clears last event ID)
  14476. TEST_F(SSEParsingTest, EmptyEventId) {
  14477. sse::SSEMessage msg;
  14478. msg.id = "previous";
  14479. int retry_ms = 3000;
  14480. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14481. EXPECT_EQ(msg.id, "");
  14482. }
  14483. // Test: Retry field parsing
  14484. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14485. sse::SSEMessage msg;
  14486. int retry_ms = 3000;
  14487. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14488. EXPECT_EQ(retry_ms, 5000);
  14489. }
  14490. // Test: Invalid retry value
  14491. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14492. sse::SSEMessage msg;
  14493. int retry_ms = 3000;
  14494. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14495. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14496. }
  14497. // Test: Comments (lines starting with :)
  14498. TEST_F(SSEParsingTest, CommentsIgnored) {
  14499. sse::SSEMessage msg;
  14500. int retry_ms = 3000;
  14501. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14502. EXPECT_EQ(msg.data, "");
  14503. EXPECT_EQ(msg.event, "message");
  14504. }
  14505. // Test: Colon in value
  14506. TEST_F(SSEParsingTest, ColonInValue) {
  14507. sse::SSEMessage msg;
  14508. int retry_ms = 3000;
  14509. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14510. EXPECT_EQ(msg.data, "hello:world:test");
  14511. }
  14512. // Test: Line with no colon (field name only)
  14513. TEST_F(SSEParsingTest, FieldNameOnly) {
  14514. sse::SSEMessage msg;
  14515. int retry_ms = 3000;
  14516. // According to SSE spec, this is treated as field name with empty value
  14517. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14518. // Since we don't recognize "data" without colon, data should be empty
  14519. EXPECT_EQ(msg.data, "");
  14520. }
  14521. // Test: Trailing \r handling
  14522. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14523. sse::SSEMessage msg;
  14524. int retry_ms = 3000;
  14525. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14526. EXPECT_EQ(msg.data, "hello");
  14527. }
  14528. // Test: Unknown fields ignored
  14529. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14530. sse::SSEMessage msg;
  14531. int retry_ms = 3000;
  14532. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14533. EXPECT_EQ(msg.data, "");
  14534. EXPECT_EQ(msg.event, "message");
  14535. }
  14536. // Test: Space after colon is optional
  14537. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14538. sse::SSEMessage msg1, msg2;
  14539. int retry_ms = 3000;
  14540. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14541. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14542. EXPECT_EQ(msg1.data, "hello");
  14543. EXPECT_EQ(msg2.data, "hello");
  14544. }
  14545. // Test: SSEMessage clear
  14546. TEST_F(SSEParsingTest, MessageClear) {
  14547. sse::SSEMessage msg;
  14548. msg.event = "custom";
  14549. msg.data = "some data";
  14550. msg.id = "123";
  14551. msg.clear();
  14552. EXPECT_EQ(msg.event, "message");
  14553. EXPECT_EQ(msg.data, "");
  14554. EXPECT_EQ(msg.id, "");
  14555. }
  14556. // Test: Complete event parsing
  14557. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14558. sse::SSEMessage msg;
  14559. int retry_ms = 3000;
  14560. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14561. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14562. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14563. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14564. // Blank line ends event
  14565. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14566. EXPECT_EQ(msg.event, "notification");
  14567. EXPECT_EQ(msg.id, "evt-42");
  14568. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14569. EXPECT_EQ(retry_ms, 1000);
  14570. }
  14571. //==============================================================================
  14572. // Integration Tests with Server
  14573. //==============================================================================
  14574. class SSEIntegrationTest : public ::testing::Test {
  14575. protected:
  14576. void SetUp() override {
  14577. stop_server_.store(false);
  14578. events_.clear();
  14579. server_ = httplib::detail::make_unique<Server>();
  14580. setup_server();
  14581. start_server();
  14582. }
  14583. void TearDown() override {
  14584. stop_server_.store(true);
  14585. event_cv_.notify_all();
  14586. server_->stop();
  14587. if (server_thread_.joinable()) { server_thread_.join(); }
  14588. }
  14589. void setup_server() {
  14590. // Simple SSE endpoint
  14591. server_->Get("/events", [this](const Request &req, Response &res) {
  14592. auto last_id = req.get_header_value("Last-Event-ID");
  14593. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14594. res.set_chunked_content_provider(
  14595. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14596. std::unique_lock<std::mutex> lock(event_mutex_);
  14597. if (event_cv_.wait_for(
  14598. lock, std::chrono::milliseconds(200), [this] {
  14599. return !events_.empty() || stop_server_.load();
  14600. })) {
  14601. if (stop_server_.load()) { return false; }
  14602. if (!events_.empty()) {
  14603. std::string event = events_.front();
  14604. events_.erase(events_.begin());
  14605. sink.write(event.data(), event.size());
  14606. return true;
  14607. }
  14608. }
  14609. return !stop_server_.load();
  14610. });
  14611. });
  14612. // Endpoint that returns error
  14613. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14614. res.status = 500;
  14615. res.set_content("Internal Server Error", "text/plain");
  14616. });
  14617. // Endpoint for custom event types
  14618. server_->Get("/custom-events", [](const Request &, Response &res) {
  14619. res.set_chunked_content_provider(
  14620. "text/event-stream", [](size_t offset, DataSink &sink) {
  14621. if (offset == 0) {
  14622. std::string event = "event: update\ndata: updated\n\n"
  14623. "event: delete\ndata: deleted\n\n";
  14624. sink.write(event.data(), event.size());
  14625. }
  14626. return false; // End stream after sending
  14627. });
  14628. });
  14629. }
  14630. void start_server() {
  14631. port_ = server_->bind_to_any_port(HOST);
  14632. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14633. // Wait for server to start
  14634. while (!server_->is_running()) {
  14635. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14636. }
  14637. }
  14638. int get_port() const { return port_; }
  14639. void send_event(const std::string &event) {
  14640. std::lock_guard<std::mutex> lock(event_mutex_);
  14641. events_.push_back(event);
  14642. event_cv_.notify_all();
  14643. }
  14644. std::unique_ptr<Server> server_;
  14645. std::thread server_thread_;
  14646. std::mutex event_mutex_;
  14647. std::condition_variable event_cv_;
  14648. std::vector<std::string> events_;
  14649. std::atomic<bool> stop_server_{false};
  14650. std::string last_received_event_id_;
  14651. int port_ = 0;
  14652. };
  14653. // Test: Successful connection and on_open callback
  14654. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14655. // Add a simple endpoint that sends one event and closes
  14656. server_->Get("/simple-event", [](const Request &, Response &res) {
  14657. res.set_chunked_content_provider(
  14658. "text/event-stream", [](size_t offset, DataSink &sink) {
  14659. if (offset == 0) {
  14660. std::string event = "data: hello\n\n";
  14661. sink.write(event.data(), event.size());
  14662. }
  14663. return false; // Close stream after sending
  14664. });
  14665. });
  14666. Client client("localhost", get_port());
  14667. sse::SSEClient sse(client, "/simple-event");
  14668. std::atomic<bool> open_called{false};
  14669. std::atomic<bool> message_received{false};
  14670. sse.on_open([&open_called]() { open_called.store(true); });
  14671. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14672. if (msg.data == "hello") { message_received.store(true); }
  14673. });
  14674. sse.set_reconnect_interval(100);
  14675. sse.set_max_reconnect_attempts(1);
  14676. // Start async
  14677. sse.start_async();
  14678. // Wait for message to be processed
  14679. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14680. sse.stop();
  14681. EXPECT_TRUE(open_called.load());
  14682. EXPECT_TRUE(message_received.load());
  14683. }
  14684. // Test: on_message callback
  14685. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14686. // Endpoint that sends multiple events then closes
  14687. server_->Get("/multi-event", [](const Request &, Response &res) {
  14688. res.set_chunked_content_provider(
  14689. "text/event-stream", [](size_t offset, DataSink &sink) {
  14690. if (offset == 0) {
  14691. std::string events = "data: message1\n\ndata: message2\n\n";
  14692. sink.write(events.data(), events.size());
  14693. }
  14694. return false;
  14695. });
  14696. });
  14697. Client client("localhost", get_port());
  14698. sse::SSEClient sse(client, "/multi-event");
  14699. std::vector<std::string> received_messages;
  14700. std::mutex messages_mutex;
  14701. sse.on_message([&](const sse::SSEMessage &msg) {
  14702. std::lock_guard<std::mutex> lock(messages_mutex);
  14703. received_messages.push_back(msg.data);
  14704. });
  14705. sse.set_reconnect_interval(100);
  14706. sse.set_max_reconnect_attempts(1);
  14707. sse.start_async();
  14708. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14709. sse.stop();
  14710. std::lock_guard<std::mutex> lock(messages_mutex);
  14711. EXPECT_GE(received_messages.size(), 2u);
  14712. if (received_messages.size() >= 2) {
  14713. EXPECT_EQ(received_messages[0], "message1");
  14714. EXPECT_EQ(received_messages[1], "message2");
  14715. }
  14716. }
  14717. // Test: on_event for specific types
  14718. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14719. Client client("localhost", get_port());
  14720. sse::SSEClient sse(client, "/custom-events");
  14721. std::atomic<bool> update_received{false};
  14722. std::atomic<bool> delete_received{false};
  14723. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14724. if (msg.data == "updated") { update_received.store(true); }
  14725. });
  14726. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14727. if (msg.data == "deleted") { delete_received.store(true); }
  14728. });
  14729. sse.set_max_reconnect_attempts(1);
  14730. sse.start_async();
  14731. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14732. sse.stop();
  14733. EXPECT_TRUE(update_received.load());
  14734. EXPECT_TRUE(delete_received.load());
  14735. }
  14736. // Test: on_error callback on connection failure
  14737. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14738. // Connect to a non-existent port
  14739. Client client("localhost", 59999);
  14740. sse::SSEClient sse(client, "/events");
  14741. std::atomic<bool> error_called{false};
  14742. Error received_error = Error::Success;
  14743. sse.on_error([&](Error err) {
  14744. error_called.store(true);
  14745. received_error = err;
  14746. });
  14747. sse.set_reconnect_interval(50);
  14748. sse.set_max_reconnect_attempts(1);
  14749. sse.start_async();
  14750. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14751. sse.stop();
  14752. EXPECT_TRUE(error_called.load());
  14753. EXPECT_NE(received_error, Error::Success);
  14754. }
  14755. // Test: Last-Event-ID header sent on reconnect
  14756. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14757. // Endpoint that sends event with ID
  14758. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14759. res.set_chunked_content_provider(
  14760. "text/event-stream", [](size_t offset, DataSink &sink) {
  14761. if (offset == 0) {
  14762. std::string event = "id: evt-123\ndata: test\n\n";
  14763. sink.write(event.data(), event.size());
  14764. }
  14765. return false;
  14766. });
  14767. });
  14768. Client client("localhost", get_port());
  14769. sse::SSEClient sse(client, "/event-with-id");
  14770. std::atomic<bool> id_received{false};
  14771. sse.on_message([&](const sse::SSEMessage &msg) {
  14772. if (!msg.id.empty()) { id_received.store(true); }
  14773. });
  14774. sse.set_reconnect_interval(100);
  14775. sse.set_max_reconnect_attempts(1);
  14776. sse.start_async();
  14777. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14778. sse.stop();
  14779. EXPECT_TRUE(id_received.load());
  14780. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14781. }
  14782. // Test: Manual stop
  14783. TEST_F(SSEIntegrationTest, ManualStop) {
  14784. // Endpoint that sends one event and stays open briefly
  14785. std::atomic<bool> handler_running{true};
  14786. server_->Get("/stay-open", [&handler_running](const Request &,
  14787. Response &res) {
  14788. res.set_chunked_content_provider(
  14789. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14790. if (offset == 0) {
  14791. std::string event = "data: connected\n\n";
  14792. sink.write(event.data(), event.size());
  14793. }
  14794. // Keep connection open while handler_running is true
  14795. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14796. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14797. }
  14798. return false;
  14799. });
  14800. });
  14801. Client client("localhost", get_port());
  14802. sse::SSEClient sse(client, "/stay-open");
  14803. std::atomic<bool> connected{false};
  14804. sse.on_open([&connected]() { connected.store(true); });
  14805. sse.set_reconnect_interval(100);
  14806. sse.set_max_reconnect_attempts(1);
  14807. sse.start_async();
  14808. // Wait for connection to establish
  14809. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14810. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14811. }
  14812. EXPECT_TRUE(connected.load());
  14813. EXPECT_TRUE(sse.is_connected());
  14814. // Signal handler to stop
  14815. handler_running.store(false);
  14816. // Stop SSE client
  14817. sse.stop();
  14818. EXPECT_FALSE(sse.is_connected());
  14819. }
  14820. // Test: SSEClient with custom headers
  14821. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14822. // Setup a server endpoint that checks for custom header
  14823. std::atomic<bool> header_received{false};
  14824. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14825. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14826. header_received.store(true);
  14827. }
  14828. res.set_chunked_content_provider("text/event-stream",
  14829. [](size_t, DataSink &) { return false; });
  14830. });
  14831. Client client("localhost", get_port());
  14832. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14833. sse::SSEClient sse(client, "/header-check", headers);
  14834. sse.set_max_reconnect_attempts(1);
  14835. sse.start_async();
  14836. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14837. sse.stop();
  14838. EXPECT_TRUE(header_received.load());
  14839. }
  14840. // Test: Reconnect interval configuration
  14841. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14842. Client client("localhost", get_port());
  14843. sse::SSEClient sse(client, "/events");
  14844. auto &result = sse.set_reconnect_interval(500);
  14845. // Builder pattern should return reference to self
  14846. EXPECT_EQ(&result, &sse);
  14847. }
  14848. // Test: Max reconnect attempts
  14849. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14850. // Connect to non-existent port to force reconnects
  14851. Client client("localhost", 59998);
  14852. sse::SSEClient sse(client, "/events");
  14853. std::atomic<int> error_count{0};
  14854. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14855. sse.set_reconnect_interval(50);
  14856. sse.set_max_reconnect_attempts(2);
  14857. auto start = std::chrono::steady_clock::now();
  14858. sse.start(); // Blocking call
  14859. auto end = std::chrono::steady_clock::now();
  14860. // Should have stopped after 2 failed attempts
  14861. EXPECT_GE(error_count.load(), 2);
  14862. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14863. auto duration =
  14864. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14865. #ifdef _WIN32
  14866. // Windows is much slower for socket connection failures
  14867. EXPECT_LT(duration.count(), 7000);
  14868. #else
  14869. EXPECT_LT(duration.count(), 1000);
  14870. #endif
  14871. }
  14872. // Test: Multi-line data in integration
  14873. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14874. // Endpoint with multi-line data
  14875. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14876. res.set_chunked_content_provider(
  14877. "text/event-stream", [](size_t offset, DataSink &sink) {
  14878. if (offset == 0) {
  14879. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14880. sink.write(event.data(), event.size());
  14881. }
  14882. return false;
  14883. });
  14884. });
  14885. Client client("localhost", get_port());
  14886. sse::SSEClient sse(client, "/multiline-data");
  14887. std::string received_data;
  14888. std::mutex data_mutex;
  14889. sse.on_message([&](const sse::SSEMessage &msg) {
  14890. std::lock_guard<std::mutex> lock(data_mutex);
  14891. received_data = msg.data;
  14892. });
  14893. sse.set_reconnect_interval(100);
  14894. sse.set_max_reconnect_attempts(1);
  14895. sse.start_async();
  14896. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14897. sse.stop();
  14898. std::lock_guard<std::mutex> lock(data_mutex);
  14899. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14900. }
  14901. // Test: Auto-reconnect after server disconnection
  14902. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14903. std::atomic<int> connection_count{0};
  14904. std::atomic<int> message_count{0};
  14905. // Endpoint that sends one event and closes, forcing reconnect
  14906. server_->Get("/reconnect-test",
  14907. [&connection_count](const Request &, Response &res) {
  14908. connection_count.fetch_add(1);
  14909. res.set_chunked_content_provider(
  14910. "text/event-stream", [](size_t offset, DataSink &sink) {
  14911. if (offset == 0) {
  14912. std::string event = "data: hello\n\n";
  14913. sink.write(event.data(), event.size());
  14914. }
  14915. return false; // Close connection after sending
  14916. });
  14917. });
  14918. Client client("localhost", get_port());
  14919. sse::SSEClient sse(client, "/reconnect-test");
  14920. sse.on_message([&message_count](const sse::SSEMessage &) {
  14921. message_count.fetch_add(1);
  14922. });
  14923. sse.set_reconnect_interval(100);
  14924. sse.set_max_reconnect_attempts(3);
  14925. sse.start_async();
  14926. // Wait long enough for multiple reconnects
  14927. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14928. sse.stop();
  14929. // Should have connected multiple times (initial + reconnects)
  14930. EXPECT_GE(connection_count.load(), 2);
  14931. // Should have received messages from multiple connections
  14932. EXPECT_GE(message_count.load(), 2);
  14933. }
  14934. // Test: Last-Event-ID sent on reconnect
  14935. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14936. std::atomic<int> connection_count{0};
  14937. std::vector<std::string> received_last_event_ids;
  14938. std::mutex id_mutex;
  14939. // Endpoint that checks Last-Event-ID header and sends event with ID
  14940. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14941. int conn = connection_count.fetch_add(1);
  14942. // Capture the Last-Event-ID header from each connection
  14943. {
  14944. std::lock_guard<std::mutex> lock(id_mutex);
  14945. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14946. }
  14947. res.set_chunked_content_provider(
  14948. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14949. if (offset == 0) {
  14950. std::string event =
  14951. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14952. sink.write(event.data(), event.size());
  14953. }
  14954. return false;
  14955. });
  14956. });
  14957. Client client("localhost", get_port());
  14958. sse::SSEClient sse(client, "/reconnect-with-id");
  14959. sse.set_reconnect_interval(100);
  14960. sse.set_max_reconnect_attempts(3);
  14961. sse.start_async();
  14962. // Wait for at least 2 connections
  14963. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14964. sse.stop();
  14965. // Verify behavior
  14966. std::lock_guard<std::mutex> lock(id_mutex);
  14967. EXPECT_GE(received_last_event_ids.size(), 2u);
  14968. // First connection should have no Last-Event-ID
  14969. if (!received_last_event_ids.empty()) {
  14970. EXPECT_EQ(received_last_event_ids[0], "");
  14971. }
  14972. // Second connection should have Last-Event-ID from first connection
  14973. if (received_last_event_ids.size() >= 2) {
  14974. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14975. }
  14976. }
  14977. // Test: set_headers updates headers used on reconnect
  14978. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14979. std::vector<std::string> received_tokens;
  14980. std::mutex token_mutex;
  14981. // Endpoint that captures Authorization header
  14982. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14983. {
  14984. std::lock_guard<std::mutex> lock(token_mutex);
  14985. received_tokens.push_back(req.get_header_value("Authorization"));
  14986. }
  14987. res.set_chunked_content_provider(
  14988. "text/event-stream", [](size_t offset, DataSink &sink) {
  14989. if (offset == 0) {
  14990. std::string event = "data: hello\n\n";
  14991. sink.write(event.data(), event.size());
  14992. }
  14993. return false; // Close connection to trigger reconnect
  14994. });
  14995. });
  14996. Client client("localhost", get_port());
  14997. Headers headers = {{"Authorization", "Bearer old-token"}};
  14998. sse::SSEClient sse(client, "/auth-check", headers);
  14999. // Update headers on each successful connection
  15000. sse.on_open(
  15001. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15002. sse.set_reconnect_interval(100);
  15003. sse.set_max_reconnect_attempts(3);
  15004. sse.start_async();
  15005. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15006. sse.stop();
  15007. std::lock_guard<std::mutex> lock(token_mutex);
  15008. ASSERT_GE(received_tokens.size(), 2u);
  15009. // First connection uses original header
  15010. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15011. // Second connection uses updated header from set_headers
  15012. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15013. }
  15014. // Test: 401 allows reconnection (so on_error can refresh headers)
  15015. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15016. std::atomic<int> connection_count{0};
  15017. // Endpoint: returns 401 on first attempt, 200 on second
  15018. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15019. int conn = connection_count.fetch_add(1);
  15020. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15021. res.status = StatusCode::Unauthorized_401;
  15022. res.set_content("Unauthorized", "text/plain");
  15023. return;
  15024. }
  15025. res.set_chunked_content_provider(
  15026. "text/event-stream", [](size_t offset, DataSink &sink) {
  15027. if (offset == 0) {
  15028. std::string event = "data: authenticated\n\n";
  15029. sink.write(event.data(), event.size());
  15030. }
  15031. return false;
  15032. });
  15033. });
  15034. Client client("localhost", get_port());
  15035. Headers headers = {{"Authorization", "Bearer expired"}};
  15036. sse::SSEClient sse(client, "/auth-retry", headers);
  15037. std::atomic<bool> message_received{false};
  15038. // Refresh token on error
  15039. sse.on_error(
  15040. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15041. sse.on_message([&](const sse::SSEMessage &msg) {
  15042. if (msg.data == "authenticated") { message_received.store(true); }
  15043. });
  15044. sse.set_reconnect_interval(100);
  15045. sse.set_max_reconnect_attempts(3);
  15046. sse.start_async();
  15047. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15048. sse.stop();
  15049. // Should have reconnected after 401 and succeeded with new token
  15050. EXPECT_GE(connection_count.load(), 2);
  15051. EXPECT_TRUE(message_received.load());
  15052. }
  15053. TEST(Issue2318Test, EmptyHostString) {
  15054. {
  15055. httplib::Client cli_empty("", PORT);
  15056. auto res = cli_empty.Get("/");
  15057. ASSERT_FALSE(res);
  15058. EXPECT_EQ(httplib::Error::Connection, res.error());
  15059. }
  15060. {
  15061. httplib::Client cli(" ", PORT);
  15062. auto res = cli.Get("/");
  15063. ASSERT_FALSE(res);
  15064. EXPECT_EQ(httplib::Error::Connection, res.error());
  15065. }
  15066. }
  15067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15068. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15069. Server svr;
  15070. // Set a small payload limit (1KB)
  15071. svr.set_payload_max_length(1024);
  15072. svr.Post("/test", [&](const Request &req, Response &res) {
  15073. res.set_content("Body size: " + std::to_string(req.body.size()),
  15074. "text/plain");
  15075. });
  15076. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15077. auto se = detail::scope_exit([&] {
  15078. svr.stop();
  15079. listen_thread.join();
  15080. });
  15081. svr.wait_until_ready();
  15082. // Create data that compresses well but exceeds limit when decompressed
  15083. // 8KB of repeated null bytes compresses to a very small size
  15084. std::string original_data(8 * 1024, '\0');
  15085. // Compress the data using gzip
  15086. std::string compressed_data;
  15087. detail::gzip_compressor compressor;
  15088. compressor.compress(original_data.data(), original_data.size(), true,
  15089. [&](const char *data, size_t size) {
  15090. compressed_data.append(data, size);
  15091. return true;
  15092. });
  15093. // Verify compression worked (compressed should be much smaller)
  15094. ASSERT_LT(compressed_data.size(), original_data.size());
  15095. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15096. // Send compressed data with Content-Encoding: gzip
  15097. Client cli(HOST, PORT);
  15098. Headers headers = {{"Content-Encoding", "gzip"}};
  15099. auto res =
  15100. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15101. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15102. ASSERT_TRUE(res);
  15103. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15104. }
  15105. #endif
  15106. // ============================================================================
  15107. // OpenSSL-Specific Tests
  15108. // ============================================================================
  15109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15110. X509 *readCertificate(const std::string &strFileName) {
  15111. std::ifstream inStream(strFileName);
  15112. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15113. std::istreambuf_iterator<char>());
  15114. if (strCertPEM.empty()) return (nullptr);
  15115. BIO *pbCert = BIO_new(BIO_s_mem());
  15116. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15117. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15118. BIO_free(pbCert);
  15119. return (pCert);
  15120. }
  15121. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15122. std::ifstream inStream(strFileName);
  15123. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15124. std::istreambuf_iterator<char>());
  15125. if (strPrivateKeyPEM.empty()) return (nullptr);
  15126. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15127. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15128. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15129. BIO_free(pbPrivKey);
  15130. return (pPrivateKey);
  15131. }
  15132. TEST(BindServerTest, UpdateCerts) {
  15133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15134. int port = svr.bind_to_any_port("0.0.0.0");
  15135. ASSERT_TRUE(svr.is_valid());
  15136. ASSERT_TRUE(port > 0);
  15137. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15138. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15139. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15140. ASSERT_TRUE(cert != nullptr);
  15141. ASSERT_TRUE(ca_cert != nullptr);
  15142. ASSERT_TRUE(key != nullptr);
  15143. X509_STORE *cert_store = X509_STORE_new();
  15144. X509_STORE_add_cert(cert_store, ca_cert);
  15145. // svr.update_certs(cert, key, cert_store); // deprecated
  15146. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15147. CLIENT_CA_CERT_FILE);
  15148. ASSERT_TRUE(svr.is_valid());
  15149. svr.stop();
  15150. X509_STORE_free(cert_store);
  15151. X509_free(cert);
  15152. X509_free(ca_cert);
  15153. EVP_PKEY_free(key);
  15154. }
  15155. // Test that update_certs() updates client CA list correctly
  15156. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15157. // Start with file-based constructor
  15158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15159. ASSERT_TRUE(svr.is_valid());
  15160. // Initially no client CA list should be set
  15161. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15162. ASSERT_TRUE(ssl_ctx != nullptr);
  15163. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15164. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15165. EXPECT_EQ(0, count_before);
  15166. // Now update with client CA (PEM string)
  15167. std::string cert_pem, key_pem, ca_pem;
  15168. read_file(SERVER_CERT_FILE, cert_pem);
  15169. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15170. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15171. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15172. ASSERT_TRUE(svr.is_valid());
  15173. // Now client CA list should be set
  15174. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15175. ASSERT_TRUE(ca_list_after != nullptr);
  15176. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15177. }
  15178. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15179. // Test that the file-path SSLServer constructor properly sets the client CA
  15180. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15182. ASSERT_TRUE(svr.is_valid());
  15183. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15184. ASSERT_TRUE(ssl_ctx != nullptr);
  15185. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15186. ASSERT_TRUE(ca_list != nullptr);
  15187. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15188. }
  15189. #endif
  15190. // ============================================================================
  15191. // MbedTLS-Specific Tests
  15192. // ============================================================================
  15193. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15194. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15195. using namespace httplib::tls;
  15196. // Track if callback was invoked
  15197. bool callback_invoked = false;
  15198. // The callback receives void* ctx which is actually MbedTlsContext*
  15199. // We can access the mbedtls_ssl_config via the context
  15200. auto setup_callback = [&callback_invoked](void *ctx) {
  15201. callback_invoked = true;
  15202. // Cast to MbedTlsContext* to access the ssl config
  15203. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15204. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15205. // Use static variables to hold certificate data (simplified for test)
  15206. static mbedtls_x509_crt own_cert;
  15207. static mbedtls_pk_context own_key;
  15208. static mbedtls_x509_crt ca_chain;
  15209. static bool initialized = false;
  15210. if (!initialized) {
  15211. mbedtls_x509_crt_init(&own_cert);
  15212. mbedtls_pk_init(&own_key);
  15213. mbedtls_x509_crt_init(&ca_chain);
  15214. // Load server certificate
  15215. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15216. return false;
  15217. }
  15218. // Load server private key
  15219. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15220. #if MBEDTLS_VERSION_MAJOR >= 3
  15221. ,
  15222. mbedtls_ctr_drbg_random, nullptr
  15223. #endif
  15224. ) != 0) {
  15225. return false;
  15226. }
  15227. // Load CA chain for client verification
  15228. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15229. return false;
  15230. }
  15231. initialized = true;
  15232. }
  15233. // Configure the SSL config
  15234. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15235. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15236. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15237. // Set minimum TLS version using mbedTLS native API
  15238. #if MBEDTLS_VERSION_MAJOR >= 3
  15239. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15240. #else
  15241. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15242. MBEDTLS_SSL_MINOR_VERSION_3);
  15243. #endif
  15244. return true;
  15245. };
  15246. SSLServer svr(setup_callback);
  15247. ASSERT_TRUE(svr.is_valid());
  15248. ASSERT_TRUE(callback_invoked);
  15249. svr.Get("/test", [&](const Request &req, Response &res) {
  15250. res.set_content("test", "text/plain");
  15251. auto cert = req.peer_cert();
  15252. ASSERT_TRUE(static_cast<bool>(cert));
  15253. auto common_name = cert.subject_cn();
  15254. EXPECT_EQ("Common Name", common_name);
  15255. });
  15256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15257. auto se = detail::scope_exit([&] {
  15258. svr.stop();
  15259. t.join();
  15260. ASSERT_FALSE(svr.is_running());
  15261. });
  15262. svr.wait_until_ready();
  15263. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15264. cli.enable_server_certificate_verification(false);
  15265. cli.set_connection_timeout(30);
  15266. auto res = cli.Get("/test");
  15267. ASSERT_TRUE(res);
  15268. ASSERT_EQ(StatusCode::OK_200, res->status);
  15269. }
  15270. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15271. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15272. // keep-alive SSL session, which reads through that config in
  15273. // mbedtls_ssl_close_notify.
  15274. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15276. ASSERT_TRUE(svr.is_valid());
  15277. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15278. res.set_content("test", "text/plain");
  15279. });
  15280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15281. auto se = detail::scope_exit([&] {
  15282. svr.stop();
  15283. t.join();
  15284. ASSERT_FALSE(svr.is_running());
  15285. });
  15286. svr.wait_until_ready();
  15287. {
  15288. SSLClient cli(HOST, PORT);
  15289. cli.enable_server_certificate_verification(false);
  15290. cli.set_keep_alive(true);
  15291. auto res = cli.Get("/test");
  15292. ASSERT_TRUE(res);
  15293. ASSERT_EQ(StatusCode::OK_200, res->status);
  15294. // cli is destructed here with the keep-alive SSL session still open.
  15295. }
  15296. }
  15297. #endif
  15298. // WebSocket Tests
  15299. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15300. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15301. // defining the meaning of these bits has been negotiated.
  15302. auto make_frame = [](uint8_t first_byte) {
  15303. std::string frame;
  15304. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15305. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15306. frame += "Hello";
  15307. return frame;
  15308. };
  15309. // RSV1 set (0x40)
  15310. {
  15311. detail::BufferStream strm;
  15312. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15313. ws::Opcode opcode;
  15314. std::string payload;
  15315. bool fin;
  15316. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15317. false, 1024));
  15318. }
  15319. // RSV2 set (0x20)
  15320. {
  15321. detail::BufferStream strm;
  15322. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15323. ws::Opcode opcode;
  15324. std::string payload;
  15325. bool fin;
  15326. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15327. false, 1024));
  15328. }
  15329. // RSV3 set (0x10)
  15330. {
  15331. detail::BufferStream strm;
  15332. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15333. ws::Opcode opcode;
  15334. std::string payload;
  15335. bool fin;
  15336. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15337. false, 1024));
  15338. }
  15339. // No RSV bits set - should succeed
  15340. {
  15341. detail::BufferStream strm;
  15342. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15343. ws::Opcode opcode;
  15344. std::string payload;
  15345. bool fin;
  15346. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15347. false, 1024));
  15348. EXPECT_EQ(ws::Opcode::Text, opcode);
  15349. EXPECT_EQ("Hello", payload);
  15350. EXPECT_TRUE(fin);
  15351. }
  15352. }
  15353. TEST(WebSocketTest, ControlFrameValidation) {
  15354. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15355. // payload length <= 125.
  15356. // Ping with FIN=0 - must be rejected
  15357. {
  15358. detail::BufferStream strm;
  15359. std::string frame;
  15360. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15361. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15362. strm.write(frame.data(), frame.size());
  15363. ws::Opcode opcode;
  15364. std::string payload;
  15365. bool fin;
  15366. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15367. false, 1024));
  15368. }
  15369. // Close with FIN=0 - must be rejected
  15370. {
  15371. detail::BufferStream strm;
  15372. std::string frame;
  15373. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15374. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15375. strm.write(frame.data(), frame.size());
  15376. ws::Opcode opcode;
  15377. std::string payload;
  15378. bool fin;
  15379. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15380. false, 1024));
  15381. }
  15382. // Ping with payload_len=126 (extended length) - must be rejected
  15383. {
  15384. detail::BufferStream strm;
  15385. std::string frame;
  15386. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15387. frame += static_cast<char>(126); // payload_len=126 (>125)
  15388. frame += static_cast<char>(0x00); // extended length high byte
  15389. frame += static_cast<char>(126); // extended length low byte
  15390. frame += std::string(126, 'x');
  15391. strm.write(frame.data(), frame.size());
  15392. ws::Opcode opcode;
  15393. std::string payload;
  15394. bool fin;
  15395. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15396. false, 1024));
  15397. }
  15398. // Ping with FIN=1 and payload_len=125 - should succeed
  15399. {
  15400. detail::BufferStream strm;
  15401. std::string frame;
  15402. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15403. frame += static_cast<char>(125); // payload_len=125
  15404. frame += std::string(125, 'x');
  15405. strm.write(frame.data(), frame.size());
  15406. ws::Opcode opcode;
  15407. std::string payload;
  15408. bool fin;
  15409. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15410. false, 1024));
  15411. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15412. EXPECT_EQ(125u, payload.size());
  15413. EXPECT_TRUE(fin);
  15414. }
  15415. }
  15416. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15417. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15418. // length MUST be 0.
  15419. // MSB set - must be rejected
  15420. {
  15421. detail::BufferStream strm;
  15422. std::string frame;
  15423. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15424. frame += static_cast<char>(127); // 64-bit extended length
  15425. frame += static_cast<char>(0x80); // MSB set (invalid)
  15426. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15427. strm.write(frame.data(), frame.size());
  15428. ws::Opcode opcode;
  15429. std::string payload;
  15430. bool fin;
  15431. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15432. false, 1024));
  15433. }
  15434. // MSB clear - should pass length parsing (will be rejected by max_len,
  15435. // but that's a different check; use a small length to verify)
  15436. {
  15437. detail::BufferStream strm;
  15438. std::string frame;
  15439. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15440. frame += static_cast<char>(127); // 64-bit extended length
  15441. frame += std::string(7, '\0'); // high bytes = 0
  15442. frame += static_cast<char>(0x03); // length = 3
  15443. frame += "abc";
  15444. strm.write(frame.data(), frame.size());
  15445. ws::Opcode opcode;
  15446. std::string payload;
  15447. bool fin;
  15448. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15449. false, 1024));
  15450. EXPECT_EQ(ws::Opcode::Text, opcode);
  15451. EXPECT_EQ("abc", payload);
  15452. }
  15453. }
  15454. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15455. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15456. // Valid UTF-8
  15457. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15458. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15459. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15460. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15461. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15462. // Invalid UTF-8
  15463. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15464. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15465. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15466. EXPECT_FALSE(
  15467. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15468. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15469. }
  15470. TEST(WebSocketTest, ConnectAndDisconnect) {
  15471. Server svr;
  15472. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15473. std::string msg;
  15474. while (ws.read(msg)) {}
  15475. });
  15476. auto port = svr.bind_to_any_port(HOST);
  15477. std::thread t([&]() { svr.listen_after_bind(); });
  15478. svr.wait_until_ready();
  15479. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15480. ASSERT_TRUE(client.connect());
  15481. EXPECT_TRUE(client.is_open());
  15482. client.close();
  15483. EXPECT_FALSE(client.is_open());
  15484. svr.stop();
  15485. t.join();
  15486. }
  15487. TEST(WebSocketTest, ValidURL) {
  15488. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15489. EXPECT_TRUE(ws1.is_valid());
  15490. ws::WebSocketClient ws2("ws://example.com/path");
  15491. EXPECT_TRUE(ws2.is_valid());
  15492. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15493. EXPECT_TRUE(ws3.is_valid());
  15494. #ifdef CPPHTTPLIB_SSL_ENABLED
  15495. ws::WebSocketClient wss1("wss://example.com/path");
  15496. EXPECT_TRUE(wss1.is_valid());
  15497. ws::WebSocketClient wss2("wss://example.com:443/path");
  15498. EXPECT_TRUE(wss2.is_valid());
  15499. #endif
  15500. }
  15501. TEST(WebSocketTest, InvalidURL) {
  15502. // No scheme
  15503. ws::WebSocketClient ws1("localhost:8080/path");
  15504. EXPECT_FALSE(ws1.is_valid());
  15505. // No path
  15506. ws::WebSocketClient ws2("ws://localhost:8080");
  15507. EXPECT_FALSE(ws2.is_valid());
  15508. // Empty string
  15509. ws::WebSocketClient ws3("");
  15510. EXPECT_FALSE(ws3.is_valid());
  15511. // Missing host
  15512. ws::WebSocketClient ws4("ws://:8080/path");
  15513. EXPECT_FALSE(ws4.is_valid());
  15514. // Port number overflow — should not crash
  15515. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15516. EXPECT_FALSE(ws5.is_valid());
  15517. // Port out of range
  15518. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15519. EXPECT_FALSE(ws6.is_valid());
  15520. }
  15521. TEST(WebSocketTest, UnsupportedScheme) {
  15522. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15523. ws::WebSocketClient ws1("http://localhost:8080/path");
  15524. EXPECT_FALSE(ws1.is_valid());
  15525. ws::WebSocketClient ws2("https://localhost:8080/path");
  15526. EXPECT_FALSE(ws2.is_valid());
  15527. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15528. EXPECT_FALSE(ws3.is_valid());
  15529. #else
  15530. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15531. std::invalid_argument);
  15532. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15533. std::invalid_argument);
  15534. #endif
  15535. }
  15536. TEST(WebSocketTest, ConnectWhenInvalid) {
  15537. ws::WebSocketClient ws("not a valid url");
  15538. EXPECT_FALSE(ws.is_valid());
  15539. EXPECT_FALSE(ws.connect());
  15540. }
  15541. TEST(WebSocketTest, DefaultPort) {
  15542. ws::WebSocketClient ws1("ws://example.com/path");
  15543. EXPECT_TRUE(ws1.is_valid());
  15544. // ws:// defaults to port 80 (verified by successful parse)
  15545. #ifdef CPPHTTPLIB_SSL_ENABLED
  15546. ws::WebSocketClient ws2("wss://example.com/path");
  15547. EXPECT_TRUE(ws2.is_valid());
  15548. // wss:// defaults to port 443 (verified by successful parse)
  15549. #endif
  15550. }
  15551. TEST(WebSocketTest, IPv6LiteralAddress) {
  15552. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15553. EXPECT_TRUE(ws1.is_valid());
  15554. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15555. EXPECT_TRUE(ws2.is_valid());
  15556. }
  15557. TEST(WebSocketTest, ComplexPath) {
  15558. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15559. EXPECT_TRUE(ws1.is_valid());
  15560. ws::WebSocketClient ws2("ws://localhost:8080/");
  15561. EXPECT_TRUE(ws2.is_valid());
  15562. }
  15563. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15564. Server svr;
  15565. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15566. std::string msg;
  15567. while (ws.read(msg)) {}
  15568. });
  15569. auto port = svr.bind_to_any_port(HOST);
  15570. std::thread t([&]() { svr.listen_after_bind(); });
  15571. svr.wait_until_ready();
  15572. auto another_host = "example.com";
  15573. auto wrong_ip = "192.0.2.1";
  15574. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15575. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15576. ASSERT_TRUE(client.connect());
  15577. EXPECT_TRUE(client.is_open());
  15578. client.close();
  15579. svr.stop();
  15580. t.join();
  15581. }
  15582. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15583. Server svr;
  15584. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15585. std::string msg;
  15586. while (ws.read(msg)) {}
  15587. });
  15588. auto port = svr.bind_to_any_port(HOST);
  15589. std::thread t([&]() { svr.listen_after_bind(); });
  15590. svr.wait_until_ready();
  15591. auto wrong_ip = "192.0.2.1";
  15592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15593. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15594. client.set_connection_timeout(1);
  15595. client.set_read_timeout(1);
  15596. client.set_write_timeout(1);
  15597. EXPECT_FALSE(client.connect());
  15598. EXPECT_FALSE(client.is_open());
  15599. svr.stop();
  15600. t.join();
  15601. }
  15602. class WebSocketIntegrationTest : public ::testing::Test {
  15603. protected:
  15604. void SetUp() override {
  15605. server_ = httplib::detail::make_unique<Server>();
  15606. setup_server();
  15607. start_server();
  15608. }
  15609. void TearDown() override {
  15610. server_->stop();
  15611. if (server_thread_.joinable()) { server_thread_.join(); }
  15612. }
  15613. void setup_server() {
  15614. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15615. std::string msg;
  15616. ws::ReadResult ret;
  15617. while ((ret = ws.read(msg))) {
  15618. if (ret == ws::Binary) {
  15619. ws.send(msg.data(), msg.size());
  15620. } else {
  15621. ws.send(msg);
  15622. }
  15623. }
  15624. });
  15625. server_->WebSocket("/ws-echo-string",
  15626. [](const Request &, ws::WebSocket &ws) {
  15627. std::string msg;
  15628. while (ws.read(msg)) {
  15629. ws.send("echo: " + msg);
  15630. }
  15631. });
  15632. server_->WebSocket(
  15633. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15634. // Echo back request metadata
  15635. ws.send("path:" + req.path);
  15636. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15637. std::string msg;
  15638. while (ws.read(msg)) {}
  15639. });
  15640. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15641. std::string msg;
  15642. ws.read(msg); // wait for a message
  15643. ws.close();
  15644. });
  15645. server_->WebSocket("/ws-close-status",
  15646. [](const Request &, ws::WebSocket &ws) {
  15647. std::string msg;
  15648. ws.read(msg); // wait for a message
  15649. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15650. });
  15651. server_->WebSocket(
  15652. "/ws-subprotocol",
  15653. [](const Request &, ws::WebSocket &ws) {
  15654. std::string msg;
  15655. while (ws.read(msg)) {
  15656. ws.send(msg);
  15657. }
  15658. },
  15659. [](const std::vector<std::string> &protocols) -> std::string {
  15660. for (const auto &p : protocols) {
  15661. if (p == "graphql-ws") { return p; }
  15662. }
  15663. return "";
  15664. });
  15665. }
  15666. void start_server() {
  15667. port_ = server_->bind_to_any_port(HOST);
  15668. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15669. server_->wait_until_ready();
  15670. }
  15671. std::unique_ptr<Server> server_;
  15672. std::thread server_thread_;
  15673. int port_ = 0;
  15674. };
  15675. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15676. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15677. "/ws-echo");
  15678. ASSERT_TRUE(client.connect());
  15679. ASSERT_TRUE(client.is_open());
  15680. ASSERT_TRUE(client.send("Hello WebSocket"));
  15681. std::string msg;
  15682. EXPECT_EQ(ws::Text, client.read(msg));
  15683. EXPECT_EQ("Hello WebSocket", msg);
  15684. client.close();
  15685. }
  15686. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15688. "/ws-echo");
  15689. ASSERT_TRUE(client.connect());
  15690. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15691. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15692. std::string msg;
  15693. EXPECT_EQ(ws::Binary, client.read(msg));
  15694. EXPECT_EQ(binary_data, msg);
  15695. client.close();
  15696. }
  15697. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15699. "/ws-echo");
  15700. ASSERT_TRUE(client.connect());
  15701. for (int i = 0; i < 10; i++) {
  15702. auto text = "message " + std::to_string(i);
  15703. ASSERT_TRUE(client.send(text));
  15704. std::string msg;
  15705. ASSERT_TRUE(client.read(msg));
  15706. EXPECT_EQ(text, msg);
  15707. }
  15708. client.close();
  15709. }
  15710. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15712. "/ws-close");
  15713. ASSERT_TRUE(client.connect());
  15714. // Send a message to trigger the server to close
  15715. ASSERT_TRUE(client.send("trigger close"));
  15716. // The server will close, so read should return false
  15717. std::string msg;
  15718. EXPECT_FALSE(client.read(msg));
  15719. EXPECT_FALSE(client.is_open());
  15720. }
  15721. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15723. "/ws-echo");
  15724. ASSERT_TRUE(client.connect());
  15725. // 128KB message
  15726. std::string large_data(128 * 1024, 'X');
  15727. ASSERT_TRUE(client.send(large_data));
  15728. std::string msg;
  15729. ASSERT_TRUE(client.read(msg));
  15730. EXPECT_EQ(large_data, msg);
  15731. client.close();
  15732. }
  15733. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15734. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15735. "/ws-echo");
  15736. ASSERT_TRUE(client.connect());
  15737. const int num_threads = 4;
  15738. std::vector<std::thread> threads;
  15739. std::atomic<int> send_count{0};
  15740. for (int t = 0; t < num_threads; t++) {
  15741. threads.emplace_back([&client, &send_count, t]() {
  15742. for (int i = 0; i < 5; i++) {
  15743. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15744. if (client.send(text)) { send_count++; }
  15745. }
  15746. });
  15747. }
  15748. for (auto &th : threads) {
  15749. th.join();
  15750. }
  15751. int received = 0;
  15752. std::string msg;
  15753. while (received < send_count.load()) {
  15754. if (!client.read(msg)) { break; }
  15755. received++;
  15756. }
  15757. EXPECT_EQ(send_count.load(), received);
  15758. client.close();
  15759. }
  15760. TEST_F(WebSocketIntegrationTest, ReadString) {
  15761. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15762. "/ws-echo-string");
  15763. ASSERT_TRUE(client.connect());
  15764. ASSERT_TRUE(client.send("hello"));
  15765. std::string msg;
  15766. ASSERT_TRUE(client.read(msg));
  15767. EXPECT_EQ("echo: hello", msg);
  15768. ASSERT_TRUE(client.send("world"));
  15769. ASSERT_TRUE(client.read(msg));
  15770. EXPECT_EQ("echo: world", msg);
  15771. client.close();
  15772. }
  15773. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15774. Headers headers = {{"X-Test-Header", "test-value"}};
  15775. ws::WebSocketClient client(
  15776. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15777. ASSERT_TRUE(client.connect());
  15778. std::string msg;
  15779. ASSERT_TRUE(client.read(msg));
  15780. EXPECT_EQ("path:/ws-request-info", msg);
  15781. ASSERT_TRUE(client.read(msg));
  15782. EXPECT_EQ("header:test-value", msg);
  15783. client.close();
  15784. }
  15785. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15787. "/ws-echo");
  15788. client.set_read_timeout(1, 0); // 1 second
  15789. ASSERT_TRUE(client.connect());
  15790. // Don't send anything — server echo handler waits for a message,
  15791. // so read() should time out and return false.
  15792. std::string msg;
  15793. EXPECT_FALSE(client.read(msg));
  15794. }
  15795. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15796. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15797. "/ws-echo");
  15798. client.set_read_timeout(5, 0);
  15799. ASSERT_TRUE(client.connect());
  15800. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15801. // The server should reject it and close the connection.
  15802. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15803. client.send(oversized);
  15804. // The server's read() should have failed due to payload limit,
  15805. // so our read() should return false (connection closed).
  15806. std::string msg;
  15807. EXPECT_FALSE(client.read(msg));
  15808. }
  15809. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15810. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15811. "/ws-echo");
  15812. client.set_read_timeout(10, 0);
  15813. ASSERT_TRUE(client.connect());
  15814. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15815. // This should succeed.
  15816. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15817. ASSERT_TRUE(client.send(at_limit));
  15818. std::string msg;
  15819. ASSERT_TRUE(client.read(msg));
  15820. EXPECT_EQ(at_limit.size(), msg.size());
  15821. client.close();
  15822. }
  15823. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15825. "/nonexistent");
  15826. EXPECT_FALSE(client.connect());
  15827. EXPECT_FALSE(client.is_open());
  15828. }
  15829. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15831. "/ws-echo");
  15832. ASSERT_TRUE(client.connect());
  15833. ASSERT_TRUE(client.send(""));
  15834. std::string msg;
  15835. EXPECT_EQ(ws::Text, client.read(msg));
  15836. EXPECT_EQ("", msg);
  15837. client.close();
  15838. }
  15839. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15841. "/ws-echo");
  15842. // First connection
  15843. ASSERT_TRUE(client.connect());
  15844. ASSERT_TRUE(client.send("first"));
  15845. std::string msg;
  15846. ASSERT_TRUE(client.read(msg));
  15847. EXPECT_EQ("first", msg);
  15848. client.close();
  15849. EXPECT_FALSE(client.is_open());
  15850. // Reconnect using the same client object
  15851. ASSERT_TRUE(client.connect());
  15852. ASSERT_TRUE(client.is_open());
  15853. ASSERT_TRUE(client.send("second"));
  15854. ASSERT_TRUE(client.read(msg));
  15855. EXPECT_EQ("second", msg);
  15856. client.close();
  15857. }
  15858. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15859. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15860. "/ws-close-status");
  15861. ASSERT_TRUE(client.connect());
  15862. // Trigger the server to close with GoingAway status
  15863. ASSERT_TRUE(client.send("trigger"));
  15864. // read() should return false after receiving the close frame
  15865. std::string msg;
  15866. EXPECT_FALSE(client.read(msg));
  15867. EXPECT_FALSE(client.is_open());
  15868. }
  15869. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15870. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15871. "/ws-echo");
  15872. ASSERT_TRUE(client.connect());
  15873. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15874. EXPECT_FALSE(client.is_open());
  15875. }
  15876. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15877. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15878. ws::WebSocketClient client(
  15879. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15880. ASSERT_TRUE(client.connect());
  15881. // Server should have selected graphql-ws
  15882. EXPECT_EQ("graphql-ws", client.subprotocol());
  15883. client.close();
  15884. }
  15885. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15886. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15887. ws::WebSocketClient client(
  15888. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15889. ASSERT_TRUE(client.connect());
  15890. // Server should not have selected any subprotocol
  15891. EXPECT_TRUE(client.subprotocol().empty());
  15892. client.close();
  15893. }
  15894. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15895. // Connect without requesting any subprotocol
  15896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15897. "/ws-subprotocol");
  15898. ASSERT_TRUE(client.connect());
  15899. EXPECT_TRUE(client.subprotocol().empty());
  15900. client.close();
  15901. }
  15902. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15904. "/ws-echo");
  15905. client.set_tcp_nodelay(true);
  15906. client.set_connection_timeout(3, 0);
  15907. bool socket_options_called = false;
  15908. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15909. ASSERT_TRUE(client.connect());
  15910. ASSERT_TRUE(client.is_open());
  15911. EXPECT_TRUE(socket_options_called);
  15912. ASSERT_TRUE(client.send("hello"));
  15913. std::string msg;
  15914. auto result = client.read(msg);
  15915. EXPECT_EQ(result, ws::ReadResult::Text);
  15916. EXPECT_EQ(msg, "hello");
  15917. client.close();
  15918. }
  15919. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15920. Server svr;
  15921. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15922. if (!req.has_header("Authorization")) {
  15923. res.status = StatusCode::Unauthorized_401;
  15924. res.set_content("Unauthorized", "text/plain");
  15925. return Server::HandlerResponse::Handled;
  15926. }
  15927. return Server::HandlerResponse::Unhandled;
  15928. });
  15929. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15930. std::string msg;
  15931. while (ws.read(msg)) {
  15932. ws.send(msg);
  15933. }
  15934. });
  15935. auto port = svr.bind_to_any_port("localhost");
  15936. std::thread t([&]() { svr.listen_after_bind(); });
  15937. svr.wait_until_ready();
  15938. // Without Authorization header - should be rejected before upgrade
  15939. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15940. EXPECT_FALSE(client1.connect());
  15941. // With Authorization header - should succeed
  15942. Headers headers = {{"Authorization", "Bearer token123"}};
  15943. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15944. headers);
  15945. ASSERT_TRUE(client2.connect());
  15946. ASSERT_TRUE(client2.send("hello"));
  15947. std::string msg;
  15948. ASSERT_TRUE(client2.read(msg));
  15949. EXPECT_EQ("hello", msg);
  15950. client2.close();
  15951. svr.stop();
  15952. t.join();
  15953. }
  15954. TEST(WebSocketTest, QueryStringInHandshake) {
  15955. Server svr;
  15956. std::mutex mtx;
  15957. std::string received_target;
  15958. std::string received_token;
  15959. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15960. {
  15961. std::lock_guard<std::mutex> lock(mtx);
  15962. received_target = req.target;
  15963. if (req.has_param("token")) {
  15964. received_token = req.get_param_value("token");
  15965. }
  15966. }
  15967. std::string msg;
  15968. while (ws.read(msg)) {
  15969. ws.send(msg);
  15970. }
  15971. });
  15972. auto port = svr.bind_to_any_port("localhost");
  15973. std::thread t([&]() { svr.listen_after_bind(); });
  15974. svr.wait_until_ready();
  15975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15976. "/ws?token=ABC&session=123");
  15977. ASSERT_TRUE(client.connect());
  15978. // Round-trip ensures the handler has run and captured the request.
  15979. ASSERT_TRUE(client.send("hello"));
  15980. std::string msg;
  15981. ASSERT_TRUE(client.read(msg));
  15982. EXPECT_EQ("hello", msg);
  15983. client.close();
  15984. {
  15985. std::lock_guard<std::mutex> lock(mtx);
  15986. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15987. EXPECT_EQ("ABC", received_token);
  15988. }
  15989. svr.stop();
  15990. t.join();
  15991. }
  15992. TEST(WebSocketTest, HostHeaderInHandshake) {
  15993. Server svr;
  15994. std::mutex mtx;
  15995. std::string received_host;
  15996. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15997. {
  15998. std::lock_guard<std::mutex> lock(mtx);
  15999. received_host = req.get_header_value("Host");
  16000. }
  16001. std::string msg;
  16002. while (ws.read(msg)) {
  16003. ws.send(msg);
  16004. }
  16005. });
  16006. auto port = svr.bind_to_any_port("localhost");
  16007. std::thread t([&]() { svr.listen_after_bind(); });
  16008. svr.wait_until_ready();
  16009. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16010. ASSERT_TRUE(client.connect());
  16011. // Round-trip ensures the handler has run and captured the request.
  16012. ASSERT_TRUE(client.send("hello"));
  16013. std::string msg;
  16014. ASSERT_TRUE(client.read(msg));
  16015. client.close();
  16016. {
  16017. std::lock_guard<std::mutex> lock(mtx);
  16018. // Non-default port must be present in the Host header. Default ports
  16019. // (80/443) are omitted; that logic is covered by
  16020. // MakeHostAndPortStringTest.
  16021. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16022. }
  16023. svr.stop();
  16024. t.join();
  16025. }
  16026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16027. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16028. protected:
  16029. void SetUp() override {
  16030. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16031. SERVER_PRIVATE_KEY_FILE);
  16032. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16033. std::string msg;
  16034. ws::ReadResult ret;
  16035. while ((ret = ws.read(msg))) {
  16036. if (ret == ws::Binary) {
  16037. ws.send(msg.data(), msg.size());
  16038. } else {
  16039. ws.send(msg);
  16040. }
  16041. }
  16042. });
  16043. port_ = server_->bind_to_any_port(HOST);
  16044. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16045. server_->wait_until_ready();
  16046. }
  16047. void TearDown() override {
  16048. server_->stop();
  16049. if (server_thread_.joinable()) { server_thread_.join(); }
  16050. }
  16051. std::unique_ptr<SSLServer> server_;
  16052. std::thread server_thread_;
  16053. int port_ = 0;
  16054. };
  16055. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16056. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16057. "/ws-echo");
  16058. client.enable_server_certificate_verification(false);
  16059. ASSERT_TRUE(client.connect());
  16060. ASSERT_TRUE(client.is_open());
  16061. ASSERT_TRUE(client.send("Hello WSS"));
  16062. std::string msg;
  16063. EXPECT_EQ(ws::Text, client.read(msg));
  16064. EXPECT_EQ("Hello WSS", msg);
  16065. client.close();
  16066. }
  16067. #endif
  16068. #ifdef CPPHTTPLIB_SSL_ENABLED
  16069. class WebSocketSSLCATest : public ::testing::Test {
  16070. protected:
  16071. void SetUp() override {
  16072. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16073. SERVER_PRIVATE_KEY_FILE);
  16074. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16075. std::string msg;
  16076. while (ws.read(msg)) {
  16077. ws.send(msg);
  16078. }
  16079. });
  16080. port_ = server_->bind_to_any_port("127.0.0.1");
  16081. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16082. server_->wait_until_ready();
  16083. }
  16084. void TearDown() override {
  16085. server_->stop();
  16086. if (server_thread_.joinable()) { server_thread_.join(); }
  16087. }
  16088. std::string url() const {
  16089. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16090. }
  16091. std::unique_ptr<SSLServer> server_;
  16092. std::thread server_thread_;
  16093. int port_ = 0;
  16094. };
  16095. // A custom CA loaded as PEM verifies the server with full certificate
  16096. // verification enabled
  16097. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16098. ws::WebSocketClient client(url());
  16099. std::string cert;
  16100. read_file(SERVER_CERT2_FILE, cert);
  16101. client.load_ca_cert_store(cert.c_str(), cert.size());
  16102. ASSERT_TRUE(client.connect());
  16103. ASSERT_TRUE(client.send("hello"));
  16104. std::string msg;
  16105. EXPECT_EQ(ws::Text, client.read(msg));
  16106. EXPECT_EQ("hello", msg);
  16107. client.close();
  16108. }
  16109. // A custom CA that does not cover the server must fail verification (the
  16110. // custom CA is exclusive; system certs are not loaded alongside it)
  16111. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16112. ws::WebSocketClient client(url());
  16113. std::string cert;
  16114. read_file(CLIENT_CA_CERT_FILE, cert);
  16115. client.load_ca_cert_store(cert.c_str(), cert.size());
  16116. ASSERT_FALSE(client.connect());
  16117. }
  16118. // Regression test: reconnecting with a native custom CA store used to reuse
  16119. // a store handle the previous TLS context had already freed (use-after-free
  16120. // under the OpenSSL backend). The context now lives as long as the client.
  16121. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16122. ws::WebSocketClient client(url());
  16123. std::string cert;
  16124. read_file(SERVER_CERT2_FILE, cert);
  16125. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16126. ASSERT_TRUE(client.connect());
  16127. client.close();
  16128. ASSERT_TRUE(client.connect());
  16129. ASSERT_TRUE(client.send("again"));
  16130. std::string msg;
  16131. EXPECT_EQ(ws::Text, client.read(msg));
  16132. EXPECT_EQ("again", msg);
  16133. client.close();
  16134. }
  16135. // Regression test: a certificate with a trusted chain but no identity match
  16136. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16137. // verification entirely for IP hosts, so this connection succeeded there.
  16138. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16139. // chain verification while the identity check must still fail.
  16140. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16142. ASSERT_TRUE(svr.is_valid());
  16143. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16144. std::string msg;
  16145. while (ws.read(msg)) {
  16146. ws.send(msg);
  16147. }
  16148. });
  16149. auto port = svr.bind_to_any_port("127.0.0.1");
  16150. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16151. auto se = detail::scope_exit([&] {
  16152. svr.stop();
  16153. t.join();
  16154. });
  16155. svr.wait_until_ready();
  16156. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16157. "/echo");
  16158. std::string cert;
  16159. read_file(SERVER_CERT_FILE, cert);
  16160. client.load_ca_cert_store(cert.c_str(), cert.size());
  16161. ASSERT_FALSE(client.connect());
  16162. }
  16163. #endif
  16164. #if !defined(_WIN32)
  16165. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16166. auto secret_dir = std::string("./symlink_test_secret");
  16167. auto served_dir = std::string("./symlink_test_served");
  16168. auto secret_file = secret_dir + "/secret.txt";
  16169. auto symlink_path = served_dir + "/escape";
  16170. // Setup: create directories and files
  16171. mkdir(secret_dir.c_str(), 0755);
  16172. mkdir(served_dir.c_str(), 0755);
  16173. {
  16174. std::ofstream ofs(secret_file);
  16175. ofs << "SECRET_DATA";
  16176. }
  16177. // Create symlink using absolute path so it resolves correctly
  16178. #ifdef PATH_MAX
  16179. char abs_secret[PATH_MAX];
  16180. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16181. #else
  16182. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16183. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16184. ASSERT_NE(nullptr, abs_secret);
  16185. #endif
  16186. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16187. auto se = detail::scope_exit([&] {
  16188. unlink(symlink_path.c_str());
  16189. unlink(secret_file.c_str());
  16190. rmdir(served_dir.c_str());
  16191. rmdir(secret_dir.c_str());
  16192. });
  16193. Server svr;
  16194. svr.set_mount_point("/", served_dir);
  16195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16196. auto se2 = detail::scope_exit([&] {
  16197. svr.stop();
  16198. listen_thread.join();
  16199. });
  16200. svr.wait_until_ready();
  16201. Client cli("localhost", PORT);
  16202. // Symlink pointing outside base dir should be blocked
  16203. auto res = cli.Get("/escape/secret.txt");
  16204. ASSERT_TRUE(res);
  16205. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16206. }
  16207. #endif
  16208. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16209. // A GET request with Content-Length to a static file handler must have its
  16210. // body drained before the keep-alive connection is reused. Otherwise the
  16211. // unread body bytes are interpreted as the next HTTP request.
  16212. //
  16213. // The body is sent AFTER receiving the first response (as in the original
  16214. // PoC) so that the stream_line_reader cannot buffer it together with the
  16215. // headers of the first request.
  16216. Server svr;
  16217. svr.set_mount_point("/", "./www");
  16218. std::atomic<int> smuggled_count(0);
  16219. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16220. smuggled_count++;
  16221. res.set_content("oops", "text/plain");
  16222. });
  16223. auto port = svr.bind_to_any_port("localhost");
  16224. thread t = thread([&] { svr.listen_after_bind(); });
  16225. auto se = detail::scope_exit([&] {
  16226. svr.stop();
  16227. t.join();
  16228. });
  16229. svr.wait_until_ready();
  16230. auto error = Error::Success;
  16231. auto sock = detail::create_client_socket(
  16232. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16233. /*connection_timeout_sec=*/2, 0,
  16234. /*read_timeout_sec=*/2, 0,
  16235. /*write_timeout_sec=*/2, 0, std::string(), error);
  16236. ASSERT_NE(INVALID_SOCKET, sock);
  16237. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16238. // The "smuggled" request will be sent as the body of the outer GET
  16239. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16240. "Host: localhost\r\n"
  16241. "Connection: close\r\n"
  16242. "\r\n";
  16243. // Step 1: Send only the outer request headers (no body yet)
  16244. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16245. "Host: localhost\r\n"
  16246. "Content-Length: " +
  16247. std::to_string(smuggled.size()) +
  16248. "\r\n"
  16249. "\r\n";
  16250. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16251. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16252. // Step 2: Read the first response (server serves file without reading body)
  16253. std::string first_response;
  16254. char buf[4096];
  16255. for (;;) {
  16256. auto n = recv(sock, buf, sizeof(buf), 0);
  16257. if (n <= 0) break;
  16258. first_response.append(buf, static_cast<size_t>(n));
  16259. // Stop once we have a complete response (headers + body)
  16260. auto hdr_end = first_response.find("\r\n\r\n");
  16261. if (hdr_end != std::string::npos) {
  16262. // Check for Content-Length to know when the body is complete
  16263. auto cl_pos = first_response.find("Content-Length:");
  16264. if (cl_pos != std::string::npos) {
  16265. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16266. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16267. auto cl = std::stoul(
  16268. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16269. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16270. } else {
  16271. break; // No Content-Length, assume headers-only response
  16272. }
  16273. }
  16274. }
  16275. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16276. // Step 3: Now send the body, which looks like a new HTTP request.
  16277. // On a vulnerable server the keep-alive loop reads this as a second request.
  16278. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16279. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16280. // Step 4: Try to read a second response (should NOT exist after fix)
  16281. std::string second_response;
  16282. for (;;) {
  16283. auto n = recv(sock, buf, sizeof(buf), 0);
  16284. if (n <= 0) break;
  16285. second_response.append(buf, static_cast<size_t>(n));
  16286. }
  16287. // The smuggled request must NOT have been processed
  16288. EXPECT_EQ(0, smuggled_count.load());
  16289. }
  16290. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16291. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16292. // must be rejected with 400 Bad Request.
  16293. Server svr;
  16294. svr.Post("/test", [&](const Request &, Response &res) {
  16295. res.set_content("ok", "text/plain");
  16296. });
  16297. thread t = thread([&] { svr.listen(HOST, PORT); });
  16298. auto se = detail::scope_exit([&] {
  16299. svr.stop();
  16300. t.join();
  16301. ASSERT_FALSE(svr.is_running());
  16302. });
  16303. svr.wait_until_ready();
  16304. // Exact "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: 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. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16319. {
  16320. auto req = "POST /test HTTP/1.1\r\n"
  16321. "Host: localhost\r\n"
  16322. "Content-Length: 5\r\n"
  16323. "Transfer-Encoding: gzip, chunked\r\n"
  16324. "Connection: close\r\n"
  16325. "\r\n"
  16326. "hello";
  16327. std::string response;
  16328. ASSERT_TRUE(send_request(1, req, &response));
  16329. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16330. response.substr(0, response.find("\r\n")));
  16331. }
  16332. }
  16333. // Regression for issue #2450: a DELETE without Content-Length on a
  16334. // keep-alive connection must not let the post-response drain consume the
  16335. // next request's bytes.
  16336. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16337. Server svr;
  16338. std::atomic<int> delete_count(0);
  16339. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16340. delete_count++;
  16341. res.status = StatusCode::NoContent_204;
  16342. });
  16343. auto port = svr.bind_to_any_port(HOST);
  16344. thread t = thread([&] { svr.listen_after_bind(); });
  16345. auto se = detail::scope_exit([&] {
  16346. svr.stop();
  16347. t.join();
  16348. });
  16349. svr.wait_until_ready();
  16350. auto error = Error::Success;
  16351. auto sock = detail::create_client_socket(
  16352. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16353. /*connection_timeout_sec=*/2, 0,
  16354. /*read_timeout_sec=*/2, 0,
  16355. /*write_timeout_sec=*/2, 0, std::string(), error);
  16356. ASSERT_NE(INVALID_SOCKET, sock);
  16357. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16358. auto send_request_and_read_response = [&](const std::string &req,
  16359. std::string &out) -> bool {
  16360. auto sent = send(sock, req.data(), req.size(), 0);
  16361. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16362. char buf[4096];
  16363. for (;;) {
  16364. auto n = recv(sock, buf, sizeof(buf), 0);
  16365. if (n <= 0) { return !out.empty(); }
  16366. out.append(buf, static_cast<size_t>(n));
  16367. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16368. }
  16369. };
  16370. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16371. "Host: localhost\r\n"
  16372. "\r\n";
  16373. std::string resp1;
  16374. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16375. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16376. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16377. "Host: localhost\r\n"
  16378. "Connection: close\r\n"
  16379. "\r\n";
  16380. std::string resp2;
  16381. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16382. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16383. EXPECT_EQ(2, delete_count.load());
  16384. }
  16385. namespace no_proxy_test {
  16386. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16387. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16388. // calling listen().
  16389. class ScopedServer {
  16390. public:
  16391. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16392. ~ScopedServer() {
  16393. svr_.stop();
  16394. if (th_.joinable()) { th_.join(); }
  16395. }
  16396. Server &svr() { return svr_; }
  16397. int port() const { return port_; }
  16398. void listen() {
  16399. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16400. svr_.wait_until_ready();
  16401. }
  16402. private:
  16403. Server svr_;
  16404. std::thread th_;
  16405. int port_ = 0;
  16406. };
  16407. class ProxyAndTargetServers {
  16408. public:
  16409. ProxyAndTargetServers() {
  16410. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16411. proxy_hits_++;
  16412. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16413. res.set_content("via-proxy", "text/plain");
  16414. });
  16415. target_.Get(".*", [this](const Request &req, Response &res) {
  16416. target_hits_++;
  16417. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16418. res.set_content("direct", "text/plain");
  16419. });
  16420. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16421. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16422. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16423. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16424. proxy_mock_.wait_until_ready();
  16425. target_.wait_until_ready();
  16426. }
  16427. ~ProxyAndTargetServers() {
  16428. proxy_mock_.stop();
  16429. target_.stop();
  16430. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16431. if (target_thread_.joinable()) { target_thread_.join(); }
  16432. }
  16433. Server &proxy_mock() { return proxy_mock_; }
  16434. Server &target() { return target_; }
  16435. int proxy_port() const { return proxy_port_; }
  16436. int target_port() const { return target_port_; }
  16437. int proxy_hits() const { return proxy_hits_.load(); }
  16438. int target_hits() const { return target_hits_.load(); }
  16439. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16440. void reset_counters() {
  16441. proxy_hits_ = 0;
  16442. target_hits_ = 0;
  16443. last_had_proxy_authz_ = false;
  16444. }
  16445. private:
  16446. Server proxy_mock_;
  16447. Server target_;
  16448. std::thread proxy_thread_;
  16449. std::thread target_thread_;
  16450. int proxy_port_ = 0;
  16451. int target_port_ = 0;
  16452. std::atomic<int> proxy_hits_{0};
  16453. std::atomic<int> target_hits_{0};
  16454. std::atomic<bool> last_had_proxy_authz_{false};
  16455. };
  16456. inline std::unique_ptr<Client> make_client(const std::string &host,
  16457. ProxyAndTargetServers &s) {
  16458. auto cli = detail::make_unique<Client>(host, s.target_port());
  16459. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16460. cli->set_proxy("127.0.0.1", s.proxy_port());
  16461. return cli;
  16462. }
  16463. } // namespace no_proxy_test
  16464. using no_proxy_test::make_client;
  16465. using no_proxy_test::ProxyAndTargetServers;
  16466. TEST(NoProxyTest, ExactHostnameBypasses) {
  16467. ProxyAndTargetServers s;
  16468. auto cli = make_client("example.com", s);
  16469. cli->set_no_proxy({"example.com"});
  16470. auto res = cli->Get("/");
  16471. ASSERT_TRUE(res);
  16472. EXPECT_EQ(0, s.proxy_hits());
  16473. EXPECT_EQ(1, s.target_hits());
  16474. }
  16475. TEST(NoProxyTest, SubdomainBypasses) {
  16476. ProxyAndTargetServers s;
  16477. auto cli = make_client("foo.example.com", s);
  16478. cli->set_no_proxy({"example.com"});
  16479. auto res = cli->Get("/");
  16480. ASSERT_TRUE(res);
  16481. EXPECT_EQ(0, s.proxy_hits());
  16482. EXPECT_EQ(1, s.target_hits());
  16483. }
  16484. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16485. // Regression guard: "evilexample.com" must not be considered a subdomain
  16486. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16487. // check would let traffic bypass the proxy and leak credentials direct
  16488. // to the attacker host.
  16489. ProxyAndTargetServers s;
  16490. auto cli = make_client("evilexample.com", s);
  16491. cli->set_no_proxy({"example.com"});
  16492. auto res = cli->Get("/");
  16493. ASSERT_TRUE(res);
  16494. EXPECT_GE(s.proxy_hits(), 1);
  16495. EXPECT_EQ(0, s.target_hits());
  16496. }
  16497. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16498. ProxyAndTargetServers s;
  16499. auto cli = make_client("example.com.evil.com", s);
  16500. cli->set_no_proxy({"example.com"});
  16501. auto res = cli->Get("/");
  16502. ASSERT_TRUE(res);
  16503. EXPECT_GE(s.proxy_hits(), 1);
  16504. EXPECT_EQ(0, s.target_hits());
  16505. }
  16506. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16507. ProxyAndTargetServers s;
  16508. auto cli = make_client("example.com", s);
  16509. cli->set_no_proxy({".example.com"});
  16510. auto res = cli->Get("/");
  16511. ASSERT_TRUE(res);
  16512. EXPECT_EQ(0, s.proxy_hits());
  16513. EXPECT_EQ(1, s.target_hits());
  16514. }
  16515. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16516. ProxyAndTargetServers s;
  16517. auto cli = make_client("Example.COM", s);
  16518. cli->set_no_proxy({"EXAMPLE.com"});
  16519. auto res = cli->Get("/");
  16520. ASSERT_TRUE(res);
  16521. EXPECT_EQ(0, s.proxy_hits());
  16522. EXPECT_EQ(1, s.target_hits());
  16523. }
  16524. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16525. ProxyAndTargetServers s;
  16526. auto cli = make_client("example.com.", s);
  16527. cli->set_no_proxy({"example.com"});
  16528. auto res = cli->Get("/");
  16529. ASSERT_TRUE(res);
  16530. EXPECT_EQ(0, s.proxy_hits());
  16531. EXPECT_EQ(1, s.target_hits());
  16532. }
  16533. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16534. // Trailing dots must be normalized on BOTH sides — host and entry.
  16535. // An implementation that only strips the host-side trailing dot would
  16536. // fail to match host "example.com" against entry "example.com." because
  16537. // a literal substring search would compare 11 chars against 12.
  16538. ProxyAndTargetServers s;
  16539. auto cli = make_client("example.com", s);
  16540. cli->set_no_proxy({"example.com."});
  16541. auto res = cli->Get("/");
  16542. ASSERT_TRUE(res);
  16543. EXPECT_EQ(0, s.proxy_hits());
  16544. EXPECT_EQ(1, s.target_hits());
  16545. }
  16546. TEST(NoProxyTest, WildcardBypassesEverything) {
  16547. ProxyAndTargetServers s;
  16548. auto cli = make_client("anything.invalid.test", s);
  16549. cli->set_no_proxy({"*"});
  16550. auto res = cli->Get("/");
  16551. ASSERT_TRUE(res);
  16552. EXPECT_EQ(0, s.proxy_hits());
  16553. EXPECT_EQ(1, s.target_hits());
  16554. }
  16555. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16556. ProxyAndTargetServers s;
  16557. Client cli("127.0.0.1", s.target_port());
  16558. cli.set_proxy("127.0.0.1", s.proxy_port());
  16559. cli.set_no_proxy({"127.0.0.1"});
  16560. auto res = cli.Get("/");
  16561. ASSERT_TRUE(res);
  16562. EXPECT_EQ(0, s.proxy_hits());
  16563. EXPECT_EQ(1, s.target_hits());
  16564. }
  16565. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16566. ProxyAndTargetServers s;
  16567. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16568. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16569. cli.set_proxy("127.0.0.1", s.proxy_port());
  16570. cli.set_no_proxy({"::1"});
  16571. auto res = cli.Get("/");
  16572. ASSERT_TRUE(res);
  16573. EXPECT_EQ(0, s.proxy_hits());
  16574. EXPECT_EQ(1, s.target_hits());
  16575. }
  16576. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16577. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16578. // must still be recognized as IPv6 for CIDR matching. Implementations
  16579. // that detect IPv6 only when the host begins with '[' would parse the
  16580. // host as a hostname and miss the match.
  16581. ProxyAndTargetServers s;
  16582. Client cli("fe80::1", s.target_port());
  16583. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16584. cli.set_proxy("127.0.0.1", s.proxy_port());
  16585. cli.set_no_proxy({"fe80::/10"});
  16586. auto res = cli.Get("/");
  16587. ASSERT_TRUE(res);
  16588. EXPECT_EQ(0, s.proxy_hits());
  16589. EXPECT_EQ(1, s.target_hits());
  16590. }
  16591. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16592. ProxyAndTargetServers s;
  16593. Client cli("::1", s.target_port());
  16594. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16595. cli.set_proxy("127.0.0.1", s.proxy_port());
  16596. cli.set_no_proxy({"[::1]"});
  16597. auto res = cli.Get("/");
  16598. ASSERT_TRUE(res);
  16599. EXPECT_EQ(0, s.proxy_hits());
  16600. EXPECT_EQ(1, s.target_hits());
  16601. }
  16602. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16603. ProxyAndTargetServers s;
  16604. Client cli("fe80::1", s.target_port());
  16605. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16606. cli.set_proxy("127.0.0.1", s.proxy_port());
  16607. cli.set_no_proxy({"[fe80::]/10"});
  16608. auto res = cli.Get("/");
  16609. ASSERT_TRUE(res);
  16610. EXPECT_EQ(0, s.proxy_hits());
  16611. EXPECT_EQ(1, s.target_hits());
  16612. }
  16613. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16614. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16615. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16616. // tricks via address-family conversion.
  16617. ProxyAndTargetServers s;
  16618. Client cli("::ffff:127.0.0.1", s.target_port());
  16619. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16620. cli.set_proxy("127.0.0.1", s.proxy_port());
  16621. cli.set_no_proxy({"127.0.0.1"});
  16622. auto res = cli.Get("/");
  16623. ASSERT_TRUE(res);
  16624. EXPECT_GE(s.proxy_hits(), 1);
  16625. EXPECT_EQ(0, s.target_hits());
  16626. }
  16627. TEST(NoProxyTest, IPv4CidrMatch) {
  16628. ProxyAndTargetServers s;
  16629. Client cli("127.0.0.1", s.target_port());
  16630. cli.set_proxy("127.0.0.1", s.proxy_port());
  16631. cli.set_no_proxy({"127.0.0.0/8"});
  16632. auto res = cli.Get("/");
  16633. ASSERT_TRUE(res);
  16634. EXPECT_EQ(0, s.proxy_hits());
  16635. EXPECT_EQ(1, s.target_hits());
  16636. }
  16637. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16638. ProxyAndTargetServers s;
  16639. Client cli("127.0.0.1", s.target_port());
  16640. cli.set_proxy("127.0.0.1", s.proxy_port());
  16641. cli.set_no_proxy({"10.0.0.0/8"});
  16642. auto res = cli.Get("/");
  16643. ASSERT_TRUE(res);
  16644. EXPECT_GE(s.proxy_hits(), 1);
  16645. EXPECT_EQ(0, s.target_hits());
  16646. }
  16647. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16648. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16649. // IPv4 target matches.
  16650. ProxyAndTargetServers s;
  16651. Client cli("127.0.0.1", s.target_port());
  16652. cli.set_proxy("127.0.0.1", s.proxy_port());
  16653. cli.set_no_proxy({"0.0.0.0/0"});
  16654. auto res = cli.Get("/");
  16655. ASSERT_TRUE(res);
  16656. EXPECT_EQ(0, s.proxy_hits());
  16657. EXPECT_EQ(1, s.target_hits());
  16658. }
  16659. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16660. ProxyAndTargetServers s;
  16661. Client cli("127.0.0.1", s.target_port());
  16662. cli.set_proxy("127.0.0.1", s.proxy_port());
  16663. cli.set_no_proxy({"127.0.0.1"});
  16664. auto res = cli.Get("/");
  16665. ASSERT_TRUE(res);
  16666. EXPECT_EQ(0, s.proxy_hits());
  16667. EXPECT_EQ(1, s.target_hits());
  16668. }
  16669. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16670. ProxyAndTargetServers s;
  16671. Client cli("127.0.0.1", s.target_port());
  16672. cli.set_proxy("127.0.0.1", s.proxy_port());
  16673. cli.set_no_proxy({"127.0.0.0/33"});
  16674. auto res = cli.Get("/");
  16675. ASSERT_TRUE(res);
  16676. EXPECT_GE(s.proxy_hits(), 1);
  16677. EXPECT_EQ(0, s.target_hits());
  16678. }
  16679. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16680. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16681. ProxyAndTargetServers s;
  16682. Client cli("127.0.0.1", s.target_port());
  16683. cli.set_proxy("127.0.0.1", s.proxy_port());
  16684. cli.set_no_proxy({"127.0.0.1/"});
  16685. auto res = cli.Get("/");
  16686. ASSERT_TRUE(res);
  16687. EXPECT_GE(s.proxy_hits(), 1);
  16688. EXPECT_EQ(0, s.target_hits());
  16689. }
  16690. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16691. ProxyAndTargetServers s;
  16692. auto cli = make_client("internal.corp", s);
  16693. cli->set_proxy_basic_auth("u", "p");
  16694. cli->set_no_proxy({"internal.corp"});
  16695. auto res = cli->Get("/");
  16696. ASSERT_TRUE(res);
  16697. EXPECT_EQ(1, s.target_hits());
  16698. EXPECT_EQ(0, s.proxy_hits());
  16699. EXPECT_FALSE(s.last_had_proxy_authz())
  16700. << "Proxy-Authorization must not be sent direct to the target";
  16701. }
  16702. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16703. ProxyAndTargetServers s;
  16704. auto cli = make_client("public.example", s);
  16705. cli->set_proxy_basic_auth("u", "p");
  16706. cli->set_no_proxy({"internal.corp"}); // does not match
  16707. auto res = cli->Get("/");
  16708. ASSERT_TRUE(res);
  16709. EXPECT_GE(s.proxy_hits(), 1);
  16710. EXPECT_TRUE(s.last_had_proxy_authz());
  16711. }
  16712. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16713. ProxyAndTargetServers s;
  16714. auto cli = make_client("anything.test", s);
  16715. auto res = cli->Get("/");
  16716. ASSERT_TRUE(res);
  16717. EXPECT_GE(s.proxy_hits(), 1);
  16718. EXPECT_EQ(0, s.target_hits());
  16719. }
  16720. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16721. ProxyAndTargetServers s;
  16722. auto cli = make_client("example.com", s);
  16723. cli->set_no_proxy({"example.com:8080"});
  16724. auto res = cli->Get("/");
  16725. ASSERT_TRUE(res);
  16726. EXPECT_GE(s.proxy_hits(), 1);
  16727. EXPECT_EQ(0, s.target_hits());
  16728. }
  16729. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16730. ProxyAndTargetServers s;
  16731. auto cli = make_client("anything.test", s);
  16732. cli->set_no_proxy({"", " ", "\t"});
  16733. auto res = cli->Get("/");
  16734. ASSERT_TRUE(res);
  16735. EXPECT_GE(s.proxy_hits(), 1);
  16736. EXPECT_EQ(0, s.target_hits());
  16737. }
  16738. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16739. // An entry with leading/trailing whitespace must still match — env-style
  16740. // values are commonly pasted with stray spaces and an implementation
  16741. // that feeds the raw token directly to inet_pton would fail to match
  16742. // valid CIDRs because of the spaces.
  16743. ProxyAndTargetServers s;
  16744. Client cli("127.0.0.1", s.target_port());
  16745. cli.set_proxy("127.0.0.1", s.proxy_port());
  16746. cli.set_no_proxy({" 127.0.0.0/8 "});
  16747. auto res = cli.Get("/");
  16748. ASSERT_TRUE(res);
  16749. EXPECT_EQ(0, s.proxy_hits());
  16750. EXPECT_EQ(1, s.target_hits());
  16751. }
  16752. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16753. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16754. // go direct and must NOT carry Proxy-Authorization.
  16755. std::atomic<int> proxy_hits{0};
  16756. std::atomic<int> target_hits{0};
  16757. std::atomic<bool> target_saw_authz{false};
  16758. no_proxy_test::ScopedServer proxy_mock, target;
  16759. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16760. proxy_hits++;
  16761. res.status = 302;
  16762. res.set_header("Location", "http://127.0.0.1:" +
  16763. std::to_string(target.port()) + "/landed");
  16764. });
  16765. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16766. target_hits++;
  16767. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16768. res.set_content("direct", "text/plain");
  16769. });
  16770. proxy_mock.listen();
  16771. target.listen();
  16772. Client cli("public.example", target.port());
  16773. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16774. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16775. cli.set_proxy_basic_auth("u", "p");
  16776. cli.set_no_proxy({"127.0.0.1"});
  16777. cli.set_follow_location(true);
  16778. auto res = cli.Get("/redir");
  16779. ASSERT_TRUE(res);
  16780. EXPECT_GE(proxy_hits.load(), 1);
  16781. EXPECT_GE(target_hits.load(), 1);
  16782. EXPECT_FALSE(target_saw_authz.load());
  16783. }
  16784. #ifdef CPPHTTPLIB_SSL_ENABLED
  16785. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16786. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16787. // proxy creds would be sent to the (possibly hostile) origin.
  16788. std::atomic<int> target_hits{0};
  16789. std::atomic<bool> target_saw_proxy_authz{false};
  16790. no_proxy_test::ScopedServer target;
  16791. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16792. target_hits++;
  16793. if (req.has_header("Proxy-Authorization")) {
  16794. target_saw_proxy_authz = true;
  16795. }
  16796. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16797. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16798. "nonce=\"abc\", algorithm=MD5");
  16799. });
  16800. target.listen();
  16801. // The proxy address is set to the target's port: the bypass MUST kick in;
  16802. // if it doesn't, the test still routes "via proxy" to the same server and
  16803. // the Proxy-Authorization assertion below catches the leak.
  16804. Client cli("evil.example", target.port());
  16805. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16806. cli.set_proxy("127.0.0.1", target.port());
  16807. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16808. cli.set_no_proxy({"evil.example"});
  16809. auto res = cli.Get("/x");
  16810. ASSERT_TRUE(res);
  16811. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16812. EXPECT_EQ(1, target_hits.load());
  16813. EXPECT_FALSE(target_saw_proxy_authz.load());
  16814. }
  16815. #endif
  16816. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16817. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16818. std::atomic<int> proxy_hits{0};
  16819. std::atomic<int> bypass_hits{0};
  16820. std::atomic<bool> proxy_saw_c_url{false};
  16821. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16822. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16823. proxy_hits++;
  16824. if (req.path.find("/start") != std::string::npos) {
  16825. res.status = 302;
  16826. res.set_header("Location", "http://127.0.0.1:" +
  16827. std::to_string(bypass_server.port()) +
  16828. "/middle");
  16829. return;
  16830. }
  16831. if (req.path.find("/end") != std::string::npos) {
  16832. proxy_saw_c_url = true;
  16833. res.set_content("c-via-proxy", "text/plain");
  16834. return;
  16835. }
  16836. res.set_content("unexpected", "text/plain");
  16837. });
  16838. // public.example's "advertised" port is arbitrary (the request never lands
  16839. // there — it goes through the proxy), but use a dynamic value to stay
  16840. // friendly with sharded parallel runs.
  16841. int public_port = bypass_server.port();
  16842. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16843. bypass_hits++;
  16844. res.status = 302;
  16845. res.set_header("Location", "http://public.example:" +
  16846. std::to_string(public_port) + "/end");
  16847. });
  16848. proxy_mock.listen();
  16849. bypass_server.listen();
  16850. Client cli("public.example", public_port);
  16851. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16852. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16853. cli.set_no_proxy({"127.0.0.1"});
  16854. cli.set_follow_location(true);
  16855. auto res = cli.Get("/start");
  16856. ASSERT_TRUE(res);
  16857. EXPECT_EQ(StatusCode::OK_200, res->status);
  16858. EXPECT_EQ("c-via-proxy", res->body);
  16859. EXPECT_GE(proxy_hits.load(), 2);
  16860. EXPECT_GE(bypass_hits.load(), 1);
  16861. EXPECT_TRUE(proxy_saw_c_url.load());
  16862. }
  16863. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16864. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16865. // request reconnects to the correct endpoint.
  16866. std::atomic<int> proxy_hits{0};
  16867. std::atomic<int> target_hits{0};
  16868. no_proxy_test::ScopedServer proxy_mock, target;
  16869. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16870. proxy_hits++;
  16871. res.set_content("via-proxy", "text/plain");
  16872. });
  16873. target.svr().Get(".*", [&](const Request &, Response &res) {
  16874. target_hits++;
  16875. res.set_content("direct", "text/plain");
  16876. });
  16877. proxy_mock.listen();
  16878. target.listen();
  16879. Client cli("public.example", target.port());
  16880. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16881. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16882. cli.set_keep_alive(true);
  16883. auto res1 = cli.Get("/a");
  16884. ASSERT_TRUE(res1);
  16885. EXPECT_EQ("via-proxy", res1->body);
  16886. EXPECT_EQ(1, proxy_hits.load());
  16887. EXPECT_EQ(0, target_hits.load());
  16888. cli.set_no_proxy({"public.example"});
  16889. auto res2 = cli.Get("/b");
  16890. ASSERT_TRUE(res2);
  16891. EXPECT_EQ("direct", res2->body);
  16892. EXPECT_EQ(1, proxy_hits.load());
  16893. EXPECT_EQ(1, target_hits.load());
  16894. }
  16895. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16896. namespace proxy_tunnel_test {
  16897. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16898. class ScopedSSLServer {
  16899. public:
  16900. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16901. port_ = svr_.bind_to_any_port("127.0.0.1");
  16902. }
  16903. ~ScopedSSLServer() {
  16904. svr_.stop();
  16905. if (th_.joinable()) { th_.join(); }
  16906. }
  16907. SSLServer &svr() { return svr_; }
  16908. int port() const { return port_; }
  16909. void listen() {
  16910. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16911. svr_.wait_until_ready();
  16912. }
  16913. private:
  16914. SSLServer svr_;
  16915. std::thread th_;
  16916. int port_ = 0;
  16917. };
  16918. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16919. class ScopedConnectProxy {
  16920. public:
  16921. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16922. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16923. if (listen_fd_ < 0) { return; }
  16924. int yes = 1;
  16925. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16926. sockaddr_in a{};
  16927. a.sin_family = AF_INET;
  16928. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16929. a.sin_port = 0;
  16930. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16931. return;
  16932. }
  16933. socklen_t alen = sizeof(a);
  16934. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16935. 0) {
  16936. return;
  16937. }
  16938. port_ = ntohs(a.sin_port);
  16939. if (::listen(listen_fd_, 1) != 0) { return; }
  16940. th_ = std::thread([this] { run(); });
  16941. }
  16942. ~ScopedConnectProxy() {
  16943. stop_ = true;
  16944. if (listen_fd_ >= 0) {
  16945. ::shutdown(listen_fd_, SHUT_RDWR);
  16946. ::close(listen_fd_);
  16947. }
  16948. if (th_.joinable()) { th_.join(); }
  16949. }
  16950. int port() const { return port_; }
  16951. int connect_hits() const { return connect_hits_.load(); }
  16952. private:
  16953. void run() {
  16954. while (!stop_.load()) {
  16955. fd_set rfds;
  16956. FD_ZERO(&rfds);
  16957. FD_SET(listen_fd_, &rfds);
  16958. timeval tv{0, 100 * 1000};
  16959. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16960. if (sel <= 0) { continue; }
  16961. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16962. if (client_fd < 0) { continue; }
  16963. std::string req;
  16964. char buf[2048];
  16965. while (req.find("\r\n\r\n") == std::string::npos) {
  16966. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16967. if (n <= 0) { break; }
  16968. req.append(buf, static_cast<size_t>(n));
  16969. }
  16970. if (req.compare(0, 7, "CONNECT") != 0) {
  16971. ::close(client_fd);
  16972. continue;
  16973. }
  16974. connect_hits_++;
  16975. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16976. ::send(client_fd, ok, std::strlen(ok), 0);
  16977. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16978. sockaddr_in o{};
  16979. o.sin_family = AF_INET;
  16980. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16981. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16982. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16983. 0) {
  16984. ::close(client_fd);
  16985. ::close(origin_fd);
  16986. continue;
  16987. }
  16988. auto forward = [](int from, int to) {
  16989. char b[8192];
  16990. for (;;) {
  16991. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16992. if (n <= 0) { break; }
  16993. ssize_t off = 0;
  16994. while (off < n) {
  16995. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16996. if (s <= 0) {
  16997. off = n;
  16998. break;
  16999. }
  17000. off += s;
  17001. }
  17002. }
  17003. ::shutdown(to, SHUT_WR);
  17004. };
  17005. std::thread t1([&] { forward(client_fd, origin_fd); });
  17006. std::thread t2([&] { forward(origin_fd, client_fd); });
  17007. t1.join();
  17008. t2.join();
  17009. ::close(client_fd);
  17010. ::close(origin_fd);
  17011. }
  17012. }
  17013. int forward_port_ = -1;
  17014. int listen_fd_ = -1;
  17015. int port_ = 0;
  17016. std::thread th_;
  17017. std::atomic<bool> stop_{false};
  17018. std::atomic<int> connect_hits_{0};
  17019. };
  17020. } // namespace proxy_tunnel_test
  17021. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17022. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17023. // retry; otherwise proxy creds would be sent to the origin.
  17024. std::atomic<int> origin_hits{0};
  17025. std::atomic<bool> origin_saw_proxy_authz{false};
  17026. proxy_tunnel_test::ScopedSSLServer origin;
  17027. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17028. origin_hits++;
  17029. if (req.has_header("Proxy-Authorization")) {
  17030. origin_saw_proxy_authz = true;
  17031. }
  17032. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17033. res.set_header("Proxy-Authenticate",
  17034. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17035. "algorithm=MD5");
  17036. });
  17037. origin.listen();
  17038. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17039. ASSERT_NE(0, proxy.port());
  17040. SSLClient cli(HOST, origin.port());
  17041. cli.enable_server_certificate_verification(false);
  17042. cli.set_proxy(HOST, proxy.port());
  17043. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17044. auto res = cli.Get("/x");
  17045. ASSERT_TRUE(res);
  17046. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17047. EXPECT_EQ(1, origin_hits.load());
  17048. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17049. EXPECT_EQ(1, proxy.connect_hits());
  17050. }
  17051. #endif